-1

Can anyone explain this program? How does it print '5' at the end? Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 1;
    while (a++ <= 1)
    while (a++ <= 2);
    printf("%d",a);  //5
    return 0;
}

4 Answers4

7

Note the absence of the ; after the first while statement. This means that there are nested while loops.

while (a++ <= 1)
    while (a++ <= 2);

Let us check the lines one by one.

a = 1; // initialize 
while (a++ <= 1)  // condition is TRUE, after this statement a === 2
   while (a++ <= 2); // condition is TRUE, after this a == 3
   while (a++ <= 2); // condition is FALSE, 
                     // but `a++` is still evaluated. So after this statement a == 4. 
                     // Inner loop exits
while (a++ <= 1)  // condition is FALSE, 
                  // `a++` is evaluated and after this a==5
                  // Outer Loop exits
printf("%d",a);   // print value of a i.e. print 5.
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
1

when it is in the first while the value that is checked is 1 then it gets increased by 1 and goes into the next while in there it's 2 so 2<=2 is true and it gets increased by 1 to 3 while checking 3<=2 it gets increased by 1 anyway cause a++ does not care if the condition is true so now we have a=4 it jumps back to the first while for checking as you know 4<=1 is sill false but it gets increased by one anyway and 5 comes out.

Masihbr
  • 11
  • 2
0
a = 1;                      First iteration         Second iteration
while (a++ <= 1) {          (1 <= 1) True           (4 <= 1) Fail                
                            (a = a + 1) == 2        (a = a + 1) == 5    
    while (a++ <= 2) { };   (a == 2) <= 2 True        
                            (a == 3) first time
                            (a == 4) When while evalutes to fail
}
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
0

If you for reasons unknown can't use a debugger and single step while watching the variable, then you could add some printf debugging code along the way. And fix the indention while you are at it:

#include <stdio.h>

int main()
{
    int a = 1;
    while (printf("Outer while %d\n", a), a++ <= 1)
      while (printf("Inner while %d\n", a), a++ <= 2)
        ;
    printf("Result %d\n", a);
    return 0;
}

Output:

Outer while 1
Inner while 2
Inner while 3
Outer while 4
Result 5

This prints the value each time it is checked, before it is increased. Basically both loops have to check the value a first time when it is in range, then a second time when it is out of range.

Please note that mixing ++ with other operators in the same expression is bad practice. The above is some fishy, artificial code, just used to illustrate the execution path.

Lundin
  • 195,001
  • 40
  • 254
  • 396