The assigment is to write a program where the user enters numbers, and the program adds the entered number to a sum. At each entry, the sum is printed. The program terminates when the user enters 0.
My code is:
#include <stdio.h>
int main(){
int n;
int i;
int sum = 0;
for(i=0; i<=n; i ){
scanf("%d", &i);
if(i==0){
break;
}
sum = i;
}
printf("%d\n", sum);
return 0;
}
However, the output isn't a favorable one.
If the input is: 1,2,3,4,5,0 The output should be:1,3,6,10,15
Right now it only outputs the total sum 15.
I'm new to programming and thankful for any advice on what I might be doing wrong :)
CodePudding user response:
Just a warning: the statement i<=n
is undefined behavior because you haven't given n
a value, just initialized it with int n
.
You should be using a while (i != 0)
loop instead of a for loop, because you don't know how many times you will be iterating beforehand, you will be looping until the user inputs a 0
.
To print the intermediate sum, you should move the printf
to inside the loop.
CodePudding user response:
n
is uninitialized here. So i<=n
will produce undefined behavior meaning anything can happen there. The best way to do this is to use while
loop.
Solution
#include <stdio.h>
int main(void)
{
int i;
int sum = 0;
while (scanf("%d", &i) == 1)
{
if(i==0)
break;
sum = i;
printf("%d\n", sum);
}
return 0;
}