Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrong with output

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading