I try to make a pascal triangle of n rows and I have to make a fucntion for allocate memory for the matrix, a function to print and free memory I think I have a lot of trouble in my code
in the function build I try to allocate the memory for the matrix and charge it i use a function full for chage the matrix, I think my principal problem is that I have an irregular matrix I don't know how to procede, maybe make an array of arrays or somthing like that could be better, sorry for my english
int main()
{
int **triangle=NULL;
int n;
printf("size of triangle");
scanf("%d",&n);
build(&triangle,n);
print(triangle,n);
return 0;
}
void build(int***triangle,int n){
*triangle=(int**)calloc(n,sizeof(int*));
int i;
for(i=0;i<n;i++){
*(triangle)[i]=(int*)calloc(i+1,sizeof(int));
}
full(*triangle,n);
}
void full(int**triangle,int n){
int i;
int j;
for(i=0;i<n;i++){
for(j=0;j<i;j++){
if(j==0){
triangle[i][j]=1;
}
else
if(j==i){
triangle[i][j]=1;
}
else
triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
}
}
}
void print(int **triangle,int n){
int i;
int j;
for(i=0;i<n;i++){
for(j=0;j<i;j++){
printf("%d",triangle[i][j]);
}
}
}
*(triangle)[i]=(int*)calloc(i+1,sizeof(int));
should be
(* triangle)[i]=(int*)calloc(i+1,sizeof(int));
Related
i wrote a program to find the determinant of a n by n matrix using recursion(laplace theorem) .
they are three functions
1)determinant() to find the determinant of n*n matrix
2)create() to dynamically allocate a n*n array
3)copy() to create n-1*n-1 minor of n*n array
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int determinant(int **a,int size,int noentry);// find determinant using recursion
int copy(int **b,int **a,int size,int noentry);//copy elements to minor
int **create(int size); // dynamically allocate a two dimensional array
int main()
{
int **a,size,i,j,y;
printf("enter the order of the determinant \n");
scanf("%d",&size);
a=create(size);
printf("enter your elements \n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&a[i][j]);
}
}
y=determinant(a,size,0);
printf("the determinant is %d \n",y);
return 0;
}
int determinant(int **a,int size,int noentry)
{
int i;
static int det=0;
if(size<=2)
return a[0][0]*a[1][1]-a[0][1]*a[1][0];
else
{
for(i=0;i<size;i++)
{
int **b;
b=create(size-1);
copy(b,a,size-1,i);
det= det+pow(-1,i)*a[0][i]*determinant(b,size-1,i);
}
return det;
}
}
int copy(int **b,int **a,int size,int noentry)
{
int i,j,k;
for(i=1;i<=size;i++)
{
k=0;
for(j=0;j<=size;j++)
{
if(j==noentry)
continue;
else
{
b[i-1][k]=a[i][j];
k++;
}
}
}
return size;
}
int **create(int size)
{
int **b;
if(size<=0)
{
printf("the size cannot be negative/null \n");
return NULL;
}
int i;
printf("entered the create function \n");
b=(int **)malloc(sizeof(int *)*size);
for(i=0;i<size;i++)
b[i]=(int *)malloc(size*sizeof(int));
return b;
}
the program is working correctly for 3 by 3 matrix but no for 4 by 4 matrix i can't spot the error.
First, you never free allocated bloc which is bad. You should create a destroy method to free a previously allocated matrix and call it once per create call.
Next, you pass an unused noentry parameter to determinant. It should just be: int determinant(int **a,int size);
But the cause of your error is that in determinant method, det variable is static. As you recurse in determinant, each new invocation should have its own det copy instead or sharing the same one.
TL/DR: just remove the static qualifier for det variable in determinant function.
Last advice: debugging would be easier if you allocated your matrices... matrix wise!
int **create(int size)
{
int i;
int **b;
if(size<=0)
{
printf("the size cannot be negative/null \n");
return NULL;
}
printf("entered the create function \n");
b=(int **)malloc(sizeof(int *)*size);
b[0]=(int *)malloc(size * size*sizeof(int));
for(i=1;i<size;i++)
b[i]=b[0] + i * size;
return b;
}
void destroy(int **a) {
free(a[0]);
free(a);
}
That way the whole matrix uses contiguous memory to allow to see its content easily in a debugger by watching at sizeĀ² integers starting at a[0]. And as a side effect, the destroy function is damned simple.
Just to be exhaustive, the fixed determinant function becomes:
int determinant(int **a,int size)
{
int i;
int det=0;
int m1 = 1;
if(size<=2)
return a[0][0]*a[1][1]-a[0][1]*a[1][0];
else
{
for(i=0;i<size;i++)
{
int **b;
b=create(size-1);
copy(b,a,size-1,i);
det= det+m1*a[0][i]*determinant(b,size-1);
destroy(b);
m1 = - m1;
}
return det;
}
}
I'm writing a code for my C programming class and stumbled upon a problem. I'm supposed to write a program which will show as an output Pascal's triangle. I'm to use 1d arrays and in each iteration make the array bigger by using realloc. The trouble is that even though the code compiles and runs when I type eg '7' (as the height of the tringle) in the 7th column there will be trash number. I have no idea why it happens. I'm a beginner in dynamic memory allocation, so please by gentle.
Here's my code:
int i,n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = (int*)malloc(sizeof(int));
int *tab2, liczba=2;
for(i=0;i<n;i++)
{
tab2=(int *)realloc(tab,i+1);
tab2[i]=&liczba;
print(tab2, i+1);
printf("\n");
}
void print(int *tab, int size)
{
int i;
for(i=0;i<size;i++) printf("%d\t", tab[i]);
}
#include <stdio.h>
#include <stdlib.h>
void print(int *tab, int size);
int main(void){
int i, j, n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = NULL;
for(i=1;i<=n;++i){
int *temp = realloc(tab, i * sizeof(*tab));
if(temp)
tab = temp;
else {
perror("realloc");
free(tab);
exit(EXIT_FAILURE);
}
tab[i-1] = (i == 1) ? 1 : 0;
for(j=i-1;j>0;--j){
tab[j] += tab[j-1];
}
print(tab, i);
}
free(tab);
return 0;
}
void print(int *tab, int size){
int i;
for(i=0;i<size;i++){
if(i)
putchar('\t');
printf("%d", tab[i]);
}
putchar('\n');
}
#include<stdio.h>
void countingSort(int array[], int k, int n){
int i,j;
int B[100],C[1000];
for (i=0;i<=k;i++)
{
C[i]=0;
}
for (j=0;j<n;j++)
{
C[array[j]]++;
}
for (i=1;i<=k;i++)
{
C[i]+=C[i-1];
}
for (j=0;j<n;j++)
{
B[--C[array[j]]]=array[j];
}
printf("Sortiran niz je: \n");
for(i=0;i<n;i++)
{
printf("%d ", B[i]);
}
printf("\n");
}
void max(int array[], int *k,int n){
int i;
printf("Broj elemenata u nizu je %d\n",n);
for(i=0;i<n;i++)
{
if(array[i]>*k) {
*k=array[i];
}
}
}
int main(int brArg, char *arg[]){
FILE *ulaz;
ulaz=fopen(arg[1],"r");
int array[1000];
int i=0,j,k=0,n,x,m;
while(fscanf(ulaz,"%d", &array[i])!=EOF)
i++;
fclose(ulaz);
n=i;
max(array,&k,n);
countingSort(array,k,n);
return 0;
}
My code works excellent for positive integers but I need to modify it so it can also sort negative integers. I hope you can help me. I don't have anything else to say but I can't post a question unless I write something here about it, so I hope it's enough.
Use a linked list, the generic list Glist exists in the GObject library. If you only need to deal with 32bit integers you can use it with very little extra programming. As you read the integers from file perfom an insertion sort in that while loop.
I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].
The program I"m trying to finish is a program using the bubble sort algorithm. I am not sure what is the problem or in which function the problem is in. The problem is the program does not sort the array in properly. (It also must be arranged in ascending order).
Here is the code:
#include <stdio.h>
#include "simpio.h"
void getArray (int arr[], int size);
void sortArray (int arr[], int size);
void swap (int arr[], int num, int number);
void dispArray (int arr[], int size);
bool checkBigger (int arr[], int num, int number);
main()
{
int size;
printf("Enter number of elements: ");
size=GetInteger();
int arr[size];
getArray(arr, size);
sortArray(arr, size);
dispArray(arr, size);
getchar();
}
void getArray (int arr[], int size)
{
int num;
printf("Please enter the value of the elements: \n");
for(num=0; num<size; num++)
{
arr[num]=GetInteger();
}
}
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=num+1;
checkBigger(arr, num, number);
}
}
}
void swap (int arr[], int num, int number)
{
int tem;
tem=arr[num];
arr[num]=arr[number];
arr[number]=tem;
}
void dispArray (int arr[], int size)
{
int num;
printf("The sorted list is:\n");
for(num=0; num<size; num++)
{
printf("%d\t", arr[num]);
}
}
bool checkBigger (int arr[], int num, int number)
{
if(arr[num]>arr[number])
{
swap(arr, num, number);
}
}
Thank you very much.
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=d+1;
checkBigger(arr, d, number);
}
}
}
pretty sure your problem is with you algorithm, try to simulate your algorithm in pen and paper. it will help your understanding of your code and the algorithm better :)
for your convenience here i am including a bubble sort algorithm i did some while ago
void bubbleSort( int a[], int n)
{
int i,j,temp; // for a={1,2,3,4,5} n is 5
n = n - 1; // bcz otherwise it will get out of index
for(i=0; i<n; i++)
{
for(j=0; j<n-i; j++)
{
if(a[j]>a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
}
i hope this helps
All I follow from the above examples is an implementation of the exchange sort.
The exchange sort on the outer loop checks each entry in the table against the first element, exchanging when necessary. At then end of the inner loop, the lowest element is in position 1, then it begins with position 2, comparing it to the remaining elements, and doing an exchange. Even if the array was already in order, the sort cannot stop. It has to do a n*(n-1) compares. An array of 50 elements, already sorted will do 50*49 comparisons.
The bubble sort works differently
set a swap flag to zero. Then
slide along the array, comparing position(i) to position(i+1). If a swap takes place, you do the sort again.
here is some pseudo code.
swap = 0
do {
for (i=o;i< no-elements-1;i++) {
if (array[i] > array[i+1])
{
do the exchange
set swap=1
}
/**/
} while (swap == 1);
The above illustrates the bubble sort.
Note. if the data is in order, there is no swap and there is no second loop. The sort algorithm is able to quit early.
if a fifty element array is in order, the sort would have done 50 comparisons and would have stopped.
The exchange sort, which is described earlier would have to do 50*49 or 2450 comparisons.
// BUBBLE SORT.
#include <stdio.h>
#define MAX 20
int main()
{
int arr[MAX];int no;
printf("PLEASE ENTER THE CURRENT SIZE OF THE ARRAY\n");
scanf("%d",&no);
int i;
printf("PLEASE ENTER THE ELEMENTS OF THE ARRAY\n");
for(i=0;i<no;i++)
scanf("%d",&arr[i]); /*reading the elements*/
/* sorting begins*/
int j,k,l;
int temp;
int flag=0;
for(k=0;k<no-1;k++)
{
flag=0;
j=k;
for(i=0;i<no-j-1;i++) /* not going to the part that has been sorted*/
{
if(arr[i]>arr[i+1])
{
flag=1;
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
else
continue;/* not necessary*/
}
if(flag==0) /*implies that the array is alraedy sorted*/
break;
}
printf("THE SORTED LIST:\n\n");
for(i=0;i<no;i++)
printf("%d\n",arr[i]);
}