Sum of array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
+ 3

Sum of array

Hello I've an exercise to sum numbers in an array in C language. All numbers are integers(whole numbers) and there are spaces between them f.e. 7 -3 8 . I've made a program but it doesn't work. The result is always 0. Here is my attempt: https://code.sololearn.com/cyRz7BXUwZLN/?ref=app Thank you in advance for any help

11th Dec 2018, 9:09 AM
Mikołaj Kozak (Hero of Olympus)
+ 9
I think you need to look into what getchar() does. https://www.tutorialspoint.com/c_standard_library/c_function_getchar.htm Using it the way you do in your loop condition is not great. You will lose your first entry using this method at the very least. Try using scanf() in the loop condition to check for EOF. For example: retValue=scanf("%d", &temp)!=EOF In your summation loop you again use getchar() but you've gotten all the input in the last loop. Nothing should be left in stdin. Try using the i variable from the previous loop as the condition and create a new variable for the counter. I.e for(int b=0; i<=i-1;++b) See: https://code.sololearn.com/c89w1Vha60ZY/?ref=app Or you could do as Danijel has suggested :)
11th Dec 2018, 10:07 AM
jay
+ 9
Everytime the loop is processed the condition is evaluated. To evaluate the condition the code must be run, so yes, it can do this as long as the code segment evaluates to True or False. In our case the code takes the input puts it into the temp variable and then checks the return code from scanf Since i is declared outside and before the first loop its value is known to your second loop. See scoping: https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm
11th Dec 2018, 10:36 AM
jay
+ 9
Mikołaj Kozak (Hero of Olympus) there is a further improvement that could be made to the code I provided. Can you guess what it is? Hint: It has something to do with the variable temp Edit: Since it's my bedtime and I have a busy day tomorrow (not sure when I'll get time to answer again) the answer is: The temp variable isn't needed. We can simply state the array variable and index inside the loop condition as so: for(i=0; scanf("%d", &num[i]) !=EOF; ++i);
11th Dec 2018, 11:01 AM
jay
11th Dec 2018, 9:59 AM
Danijel Ivanović
+ 3
Thank you for that helped me a lot with understanding that topic.
11th Dec 2018, 1:04 PM
Mikołaj Kozak (Hero of Olympus)
+ 3
Once you have got all array elements in first loop then simply run a while loop till 'i>=0' and add them to result variable, What you have done is actually a very complex method so you are not getting expected output.
11th Dec 2018, 8:55 PM
#DARK_PROGRAMMER_✔
+ 2
Soo the condition in for loop do 2 things check for EOF and safe numbers? And inside the loop is saved index of the last number?
11th Dec 2018, 10:33 AM
Mikołaj Kozak (Hero of Olympus)
0
Тут русские есть?
12th Dec 2018, 7:36 AM
юлия Гординская