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

How do I use Do While to stop a loop?

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;}

>Solution :

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

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;
}
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