dv24680
dv24680

Reputation: 63

For-loop logic in order to print an inputed character using scanf n number of times

I've been trying to understand the logic behind this for loop but I've been unable to. The problem asks to input an integer n (number of test cases) followed by n number of characters with each characters denoting the day of the week. So I need to output the day n number of times.

#include <stdio.h>
int main()
{
    int n, i;
    char ch;

    scanf("%d",&n);

    for (i = 0; i < 2 * n; i += 1)
    {
        scanf("%c", &ch);
        switch (ch)
        {
        case 'M':
            printf("Monday\n");
            break;
        case 'T':
            printf("Tuesday\n");
            break;
        case 'W':
            printf("Wednesday\n");
            break;
        case 'H':
            printf("Thursday\n");
            break;
        case 'F':
            printf("Friday\n");
            break;
        case 'S':
            printf("Saturday\n");
            break;
        case 'N':
            printf("Sunday\n");
            break;
        }
    }
    return 0;
}

I don't understand the logic for i<2*n. So for example when I input n=2 followed by characters M M, and i is initialized to 0, the condition for 0 < 4 is checked which is true so the first character M is input, and Monday is printed once, now i is incremented to 1 and is checked against 1 < 4 which is true and is printed once again. Now it has already been printed twice, but according to the i < 2 * n logic shouldn't Monday get printed 4 times until 4 < 4 terminates the for loop?

But this logic somehow works correctly.

My logic for i <= n, for some reason does not work and only inputs and prints the character the one time. Where am I going wrong here?

Upvotes: 2

Views: 490

Answers (1)

anastaciu
anastaciu

Reputation: 23802

scanf("%c", &ch); scans the character you input but the \n newline character, caused by the enter, remains on the buffer, (the same is true for the previous scanf in your code), this causes the for loop to run 2 times for every input: first, it scans the character itself and then the \n. This is the reason why your for loop needs to run 4 times instead of the 2 it should.

You will need to discard those \n characters. You can use %*c to discard them, then you can replace n*2 with n in the for loop, the advantage is that the loop runs only half of the times you have now.

This works, not only for block input separated by space, but also for one at a time inputs.

Link to live sample

//...
scanf("%d%*c", &n); //<-- dicard newline character

for (i = 0; i < n ; i += 1) {
    scanf("%c%*c", &ch); //<-- discard newline character
//...

Upvotes: 1

Related Questions