noobcoder noobcoder - 21 days ago 7
C Question

C: Why does this code print this?

can somebody explain why does this code print 5 A's

AAAAA
and not 4 A's
AAAA


value of char
'A' - 65
,
'B' - 66
and
'Z' - 90


#include <stdio.h>

int main() {
char a='B',b='A';
while(a++<'Z') {
if(a%5==0)
printf("%c",b);
}
return 0;
}


I calculated multiple times and I got 4 A's as a result, so I do not understand why correct answer is 5 A's

Thanks.

Answer

Let's iterate through your code "manually".

Stop condition: a < 90 ('Z')

    a = 'B' = 66
    ...
    a = 70 => 'A' printed
    ...
    a = 75 => 'A' printed
    ...
    a = 80 => 'A' printed
    ...
    a = 85 => 'A' printed
    ...
    a = 89 =>
        - condition is checked (a++ < 90) and evaluates to true and since you use an postfix increment operator (a++), variable a gets incremented after the comparison and therefore, inside the next operation "if(a%5==0)", variable a has now the value of 90, thus passing the check and getting your 5th 'A' printed

Check http://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators

Comments