Home > Net >  hi there, a question about break statement in c programming
hi there, a question about break statement in c programming

Time:12-22

I wrote this loop to add numbers, and the break to get out of the loop if the number entered is less than zero, and in last print the calculated numbers without adding the negative number. but the problem is even I wrote the break statement before the addition when I enter 15 and 15 and -2 the output is 28 rather than 30 I found out how to fix that, what I want to know is why and thank you.

#include <stdio.h>

void main()
{
    int j = 1, num = 0, rslt = 0;
    while (1) {
        if (num < 0) break;
        printf("enter a number : ");
        scanf("%d", &num);
        rslt = rslt   num;
    }
    printf("the resluts are %d\n", rslt);
}

CodePudding user response:

Currently, you are effectively testing the input of the previous iteration, after already adding it to your result. Instead, check the number immediately after the user enters it, before you perform any calculations.

#include <stdio.h>

int main(void)
{
    int num = 0, rslt = 0;

    while (1) {
        printf("enter a number : ");
        scanf("%d", &num);
        
        if (num < 0)
            break;
                               
        rslt  = num;           
    }                          
                              
    printf("the results are %d\n", rslt);
}

You might also want to check that scanf returns the number of successful conversions you were expecting (in this case one), to handle the event where the user enters invalid input.

if (1 != scanf("%d", &num))
    break;
  • Related