user10990333
user10990333

Reputation:

Counter inside a for loop does not give expected output

This program scans for some characters, and shows how many 'x''s were given as input. I think you'll get a better idea looking at the code instead of me explaining.

#include<stdio.h>
main()
{
    int n,i,t=0;
    scanf("%d",&n);
    char ara[n];
    for(i=0;i<n;i++)
    {
        scanf("%c", &ara[i]);
        if(ara[i]=='x') t++;
    }
    printf("%d",t);
}

suppose, n = 5 and the characters were "xxxxxx". In that case, the value of t should be 5. But it displays 4.

Another thing is that if you remove the first scanf Statement (line 5) and manually set the value of n = 5 everywhere else in the Code:

int n,i,t=0;
//scanf("%d",&n);
n = 5;

then the value of t becomes 5 resulting in the correct output. Is there any possibility that the outer scanf function is affecting the scanf function inside for loop?

Upvotes: 1

Views: 70

Answers (2)

Michael Veksler
Michael Veksler

Reputation: 8475

Your ara array contains the newline right after you entered 5. To discard this newline (and all newlines and spaces before the first 'x') you should put space after %d:

scanf("%d ",&n);

Edit

You could prepend a space before "%c" like in the answer by @Blaze, but then input like the following will be misread:

 5
 x x x x x

It will be read as 'x', 'x', 'x', 'x', 'x' instead of 'x', ' ', 'x', ' ', 'x'.

Addendum:

If you want to discard just one newline, and not all newlines:

scanf("%d",&n);
while (true) {
    char ch = getchar();
    if (ch == EOF || ch == '\n') break;
}

Upvotes: 0

Blaze
Blaze

Reputation: 16876

This is because when you enter your n, you're also entering a newline (or a space). This whitespace is left in the buffer, so the first character read in won't be the x, but that whitespace character.

You can fix that by telling scanf to skip the leading whitespace. Change this line

scanf("%c", &ara[i]);

To this:

scanf(" %c", &ara[i]);

The space in front of the %c makes it ignore that newline/space and instead take the first x entered, giving you the correct result. This is how a reference explains it:

Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

Upvotes: 1

Related Questions