+ 4
Why the output is 0 ? ( C language )
I try to define a function to sum up elements of array, it doesn't work. input: 3 3 2 1 outupt: 0 (Why?) https://code.sololearn.com/cdoeDsxqQyIj/?ref=app
9 Respuestas
+ 16
you are passing value of x as 0 (due to loop, it becomes 0) in the function for calculating sum.
you can take initial value of x in some another variable k, and pass k as argument while calling function :
printf("%d \n",sum(array, k));
//where k is value of x before loop
+ 10
Dheeraj Rachaboyina
I am pasting code below, there is ● where I added or modified statement.
#include <stdio.h>
int main() {
//define a function to sum up array element
int sum(int a[], int n) {
int temp = 0;
while (n-- > 0) {
temp += a[n];
}
return temp;
}
int x;
scanf("%d", &x);
int array[x];
int k=x; //here ●
while (x-- > 0) {
scanf("%d", &array[x]);
}
printf("%d \n", sum(array, k)); //here ●
return 0;
}
+ 3
Kk bro..thanks
+ 2
Even though replacing with k .. it's not working bro..getting output as 0
+ 2
U are decrementing x in the loop and passing it which will be 0.
So u need to store the value of x in some other variable and use it as counter.
// Created by Kevin Lee (from Xi'an)
#include <stdio.h>
int main() {
//define a function to sum up array element
int sum(int a[], int n) {
int temp = 0;
while (n-- > 0) {
temp += a[n];
}
return temp;
}
int x, i;
scanf("%d", &x);
i = x;
int array[x];
while (i-- > 0){
scanf("%d", &array[i]);
}
printf("%d \n", sum(array, x) );
return 0;
}
+ 1
Because x value is not initialized explicitly🤔
+ 1
Yes it should be
0
Try this and make sure you enter the enter key after each input I was trying to use commas.... #include <stdio.h>
int main() {
//define a function to sum up array element
int sum(int a[], int n) {
int temp = 0;
while (n > 0 ) {
temp += a[--n];
}
return temp;
}
int x;
scanf("%d", &x);
int k = x;
int array[x];
while (x > 0) {
scanf("%d", &array[--x]);
}
printf("%d \n", sum(array, k) );
return 0;
}
you where decrementing your loop counters before accesing their index this way you access the index then update your counter
0
Stanley ice Isn't - - x and - - n ?