Home > front end >  C If() Statement does not runs even if condition is true [closed]
C If() Statement does not runs even if condition is true [closed]

Time:09-30

I want to make simple calculator, that counts problems you entered, when user enters 0_0 it prints results of problems user wrote.

int a[20], b[20], result[20];
int n = 0;
char operation[20]; // 
printf("Enter:\n");



while(1)
{
    if(a[n] == 0 && operation[n] == '_' && b[n] == 0) // Even user types 0_0 cycles does not breaks
    {
        
        break;
    }
    scanf("%i%c%i", &a[n], &operation[n], &b[n]);
    
    n  ;
    
}

Why even if I type 0_0 cycles does not breaks. Whats wrong with a[n], b[n], operation[n] thanks a lot in advance for answer!

CodePudding user response:

You could have spotted the mistake with a simple dry run.

  • Initially n = 0 and a[0], b[0], operation[0] have garbage values.
  • Now, the control enters the loop, the condition inside if is evaluated. This condition evaluates false because of the above point.
  • Now, you're reading the values entered by the user.
  • Say, now n = 0, and a[0] = 0, operation[0] = '_' and b[0] = 0 (after entering the values).
  • But now, n gets incremented to 1.
  • The if condition again evaluates to false because n is not 0 now.

This continues for ever (possibly).

CodePudding user response:

The if statement is placed before you take the users input. So the if never checks the user input but instead checks some uninitialized array values (because n is incremented just after the scan).

You need to read input first and then do the if. So simply swap the if and the scanf

if (scanf("%i%c%i", &a[n], &operation[n], &b[n]) != 3)
{
    // Illegal input. Add error handling here... or simply exit like:
    exit(1);
}

if(a[n] == 0 && operation[n] == '_' && b[n] == 0)
{
    
    break;
}

n  ;

Further notice that you need to make sure that the while stops when n reach 20 (i.e. to avoid writing outside the arrays). Perhaps do

 while(1) --->  while(n < 20)
  •  Tags:  
  • c
  • Related