0
Sum of numbers
I want to calculate the sum by taking numbers in separate lines until the number zero is entered. But my code only reads the first line and re-enters the loop, what is the reason? Ex: Input: 100 7 83 0 Output: 190 https://code.sololearn.com/ctzC1vr9nSnP/?ref=app
7 Answers
+ 1
If you did not use scanf inside the while loop you can not repeat asking for user input .setting a = 1 whill ensure that user will enter any number until he enter 0 then condition a!=0 is false and then stop execution of while loop
Shakiba Majd
+ 2
Provide some intial value to a which is not 0 and ask for values inside while loop then,
int main() {
int sum=0,a=1;
while (a!=0){
scanf("%d",&a);
sum=sum+a;
}
printf("%d",sum);
return 0;
}
+ 2
Shakiba Majd scanf only reads value until you don't start a new line by pressing enter key
You can't do something like this
45
56
78 ,and expect one scanf to read all those multiple line values and add them
but if you want to only use one scanf then you can use char array to ask for input like 45 56 78 and then process that string to add values but that is obviously what you don't want
uninitialized variable(a) in this case has a value of 0 so the loop will never start , That's why I am initializing it with value other than 0
+ 1
#include <stdio.h>
int main()
{
int sum=0,a;
do
{
scanf("%d",&a); //take in loop to repeatedly accept input..
sum=sum+a;
}while (a!=0); //when input 0 then loop stops..
printf("%d",sum); //print final sum...
return 0;
}
+ 1
Abhay Thank you so much for your explanation đ
0
Abhay But what's the difference between scanf inside of loop and outside of loop? And why we write a=1?
0
Abhay Yeah I got it, thanks again.