Home > Back-end >  How do I use Do While to stop a loop?
How do I use Do While to stop a loop?

Time:11-15

I am writing a simple program that takes an input and adds it to a sum and then prints it, but then asks for another input and also adds that to the sum. However when 0 is in the input, the program should stop. That part is not working, here is what I have tried.

#include <stdio.h>


int main(){

int n, summa, t;

summa = 0;
t=1;
do{
scanf("%d", &n);
if(n==0){t=0;
}
summa = n   summa;


printf("%d\n", summa);

}
while(t == 0);{return 0;}
return 0;}

CodePudding user response:

I believe you intended your conditional to be t != 0.

Here's a reformatted version of your code with the new conditional, see if that functions as you expected.

#include <stdio.h>

int main() {
    int n, summa, t;
    summa = 0;
    t = 1;

    do {
        scanf("%d", &n);

        if (n == 0) {
            t = 0;
        }

        summa = n   summa;
        printf("%d\n", summa);
    }
    while(t != 0);

    return 0;
}
  • Related