Thread: Nested while and || operator

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    11

    Nested while and || operator

    Please refer to this code:
    Code:
    #include <stdio.h>
    
    int array[5];
    
    int main( void )
    {
       int ctr = 0,
           nbr = 0;
    
        printf("This program prompts you to enter 5 numbers\n");
        printf("Each number should be from 1 to 10\n");
    
        while ( ctr < 5 )
        {
            nbr = 0;
            while (nbr < 1 || nbr > 10)
            {
                printf("\nEnter number %d of 5: ", ctr + 1 );
                scanf("%d", &nbr );
            }
    
            array[ctr] = nbr;
            ctr++;
        }
    
        for (ctr = 0; ctr < 5; ctr++)
            printf("Value %d is %d\n", ctr + 1, array[ctr] );
    
        return 0;
    }
    How does the code filter the program to accept numbers 1 to 10 only if while (nbr < 1 || nbr > 10) validates both expressions as TRUE?

  2. #2
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    If Either is true, not both.

    It says, if number read is less than 1 OR greater than 10, loop again and re-prompt and read in a new number. When the number is in range [1,10] then the loop exits.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Quote Originally Posted by Tclausex View Post
    If Either is true, not both.

    It says, if number read is less than 1 OR greater than 10, loop again and re-prompt and read in a new number. When the number is in range [1,10] then the loop exits.
    Yes, I think I got it now - If either of the statements is TRUE, the statement will loop with the same ctr value which is "1" the first time. Then when the statement is FALSE, which is when a number between 1 to 10 is entered, the loop will exit and go to the outer while statement where it stores the entered number in the array, and increments the counter of that outer while statement. Right?

  4. #4
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Well, ctr is 0 to start with, but yes, that's the gist of it.

  5. #5
    Registered User
    Join Date
    Feb 2013
    Posts
    11
    Quote Originally Posted by Tclausex View Post
    Well, ctr is 0 to start with, but yes, that's the gist of it.
    Ah yes, ctr is 0, it's just +1 first at the inner while loop. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ternary Operator to choose which operator to use
    By cncool in forum C Programming
    Replies: 7
    Last Post: 06-27-2011, 01:35 PM
  2. nested enum operator overloading
    By BdON003 in forum C++ Programming
    Replies: 3
    Last Post: 11-21-2009, 05:41 PM
  3. Replies: 3
    Last Post: 12-09-2008, 11:19 AM
  4. Replies: 2
    Last Post: 07-07-2008, 03:46 AM
  5. Replies: 1
    Last Post: 07-07-2008, 03:38 AM