+ 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

6th Jul 2019, 5:51 AM
Merida
Merida - avatar
9 ответов
+ 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
6th Jul 2019, 6:09 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 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; }
6th Jul 2019, 7:27 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 3
Kk bro..thanks
6th Jul 2019, 7:29 PM
Dheeraj
Dheeraj - avatar
+ 2
Even though replacing with k .. it's not working bro..getting output as 0
6th Jul 2019, 6:56 PM
Dheeraj
Dheeraj - avatar
+ 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; }
12th Jul 2019, 9:44 AM
N Hrishikesh Prabhu
N Hrishikesh Prabhu - avatar
+ 1
Because x value is not initialized explicitly🤔
7th Jul 2019, 2:41 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
Yes it should be
9th Jul 2019, 1:08 AM
Stanley ice
Stanley ice - avatar
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
8th Jul 2019, 2:46 AM
Stanley ice
Stanley ice - avatar
0
Stanley ice Isn't - - x and - - n ?
9th Jul 2019, 12:47 AM
Merida
Merida - avatar