Reputation: 45
c program is not printing the correct sum. I try different numbers each time and even tried working using a variable to store the value of the index in the array at each iteration.
#include <stdio.h>
#include <malloc.h>
//find sum using pointers
int find_sum(int *a,int n) {
int sum=0;
int i;
for (i=0; i<n; i++){
sum=sum + *(a+i);
}
printf("sum= %i",sum);
}
int main(){
int n;
printf("Enter length of array: ");
scanf("%i",&n);
int *a=(int *)malloc(n*sizeof(int));
int i;
for (i=0; i<n; i++){
printf("Enter %i numbers",n);
int b=*(a+i);//used to store the value at that index.
scanf("%i",&b);
}
find_sum(a,n);
return 0;
}
the output turns out to be :
Enter length of array: 3 Enter 3 numbers1 Enter 3 numbers2 Enter 3 numbers3 sum= 0
Upvotes: 3
Views: 297
Reputation: 437422
Consider the line:
int b=*(a+i); //used to store the value at that index.
This creates a new local int
called b
that now contains what was at a+i
(i.e. it's unknown at this point).
You then replace that local int
with what the user entered:
scanf("%i",&b);
But you never go back and update a
.
I might suggest:
int b;//used to store the value at that index.
scanf("%i",&b);
*(a+i) = b;
E.g.
int main() {
int n;
printf("Enter length of array: ");
scanf("%i",&n);
int *a=(int *)malloc(n*sizeof(int));
int i;
for (i=0; i<n; i++) {
printf("Enter number %i: ",n);
int b;
scanf("%i", &b);
*(a+i) = b;
}
find_sum(a, n);
free(a); // if you malloc, don't forget to `free`
return 0;
}
Or, if you don't want to deal with malloc
and free
(which are so easy to introduce memory errors), you can just use an array:
int main() {
int n;
printf("Enter length of array: ");
scanf("%i", &n);
int a[n];
int i;
for (i=0; i<n; i++) {
printf("Enter number %i: ", n);
scanf("%i", &a[i]);
}
find_sum(a, n);
return 0;
}
Upvotes: 5