-3

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

chqrlie
  • 131,814
  • 10
  • 121
  • 189
noobcoder
  • 33
  • 1
  • 6
  • 3
    Are you counting the case where `a` is 89 for the `while` test and 90 for the `if` test? – aschepler Nov 15 '16 at 00:21
  • Which values of `a` do you believe result in an A being output? Can you modify your code to test your belief? – Paul Hankin Nov 15 '16 at 00:24
  • 1
    The probable misunderstanding here is the behavior of `a++`. It is compared with 'Z' *before* it is incremented, but then it's used on the next line after the increment operation, as @aschepler indicated. Try it with `++a` instead and notice what happens. – eddiem Nov 15 '16 at 00:25
  • 2
    You could improve your understanding of what's going on by printing: `printf("%d %c %c\n", a, a, b);` instead of what you have. This would allow you to see the values driving the decision in the body of the loop. It would be better if you printed a newline at the end of the output even without the debugging print. – Jonathan Leffler Nov 15 '16 at 00:27
  • It will be clear and easy if you change your printf to `printf("%d, ",a);` – jaeheung Nov 15 '16 at 00:28
  • when a is 89, 89%5 is not 0 so 90<90 is not possible? or is it like this: first while tests 89<90 then it increments a to 90 inside while loop, 90 %5 is 0 and that's why 5 A's ? – noobcoder Nov 15 '16 at 00:33
  • When `a` is 89 in the `while`, it is `90` in the `if` (because the increment occurs after the value is read for the test but before anything in the `if` is executed). So `a % 5` is `0` when `a` is `90` in the `if`. – Jonathan Leffler Nov 15 '16 at 00:37
  • I understand. Thank you Jonathan and everyone else :) – noobcoder Nov 15 '16 at 00:40

1 Answers1

2

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 https://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators

Community
  • 1
  • 1