Thread: See this code

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    9
    Rep Power
    0

    See this code


    Can someone tell me why is the loop getting executed just once



    #include<stdio.h>
    int main()
    {
    int a,p=0,n=0,z=0;
    char b='y';
    while(b=='y')
    {
    printf("Enter any number\n\n");
    scanf("%d", &a);
    if(a>0)
    p=p+1;
    else if(a<0)
    n=n+1;
    else
    z=z+1;
    printf("Do you want to enter another number");
    scanf("%c", &b);
    }
    printf("The total number of positives entered are %d", p);
    printf("The total number of negatives entered are %d", n);
    printf("The total number of zeros entered are %d", z);
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Use code tags to preserve your code's indentation:
    Code:
    #include<stdio.h>
    
    int main()
    {
        int a,p=0,n=0,z=0;
        char b='y';
        while(b=='y')
        {
            printf("Enter any number\n\n");
            scanf("%d", &a);
            if(a>0)
                p=p+1;
            else if(a<0)
                n=n+1;
            else
                z=z+1;
            printf("Do you want to enter another number");
            scanf("%c", &b);
        }
        printf("The total number of positives entered are %d", p);
        printf("The total number of negatives entered are %d", n);
        printf("The total number of zeros entered are %d", z);
        
        return 0;
    }
    Also do not break your promises to the compiler. You told it you would return an int, so return an int!

    Originally Posted by Henry Spencer
    If you lie to the compiler, it will get its revenge.
    I suspect that your description of the problem is woefully inadequate. Here is what I assume actually happened:
    1. You enter a number and it does its thing.
    Contents of the stdin buffer: "\n"

    2. It displays the prompt, "Do you want to enter another number". scanf("%c" reads the '\n' from the stdin buffer and stores it in b. That sets b to either '\x0a' or '\x0d' ('\n' in Windows/DOS is a two character sequence, CRLF, so I don't know which one actually gets stored in b).

    3. b is not equal to 'y' so the program does not enter the loop again.

    scanf("%c", &b);
    tells scanf to read in the next character, regardless of what it is. Such as the newline that's left in the input buffer by the previous scanf call.

    scanf(" %c", &b);
    tells scanf to read skip any white space and to read in the next printable character. Please note the space preceding the percent sign, since that is what tells scanf to expect and skip white space (space, newline, tab, etc).
    Last edited by dwise1_aol; August 16th, 2013 at 11:24 AM.

IMN logo majestic logo threadwatch logo seochat tools logo