Thread: While Loop

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    2

    While Loop

    Hi,

    I am taking the iTunes U cs50 class and ran into code that i do not quite understand:

    Code:
    #include <cs50.h>
    #include <stdio.h>
    
    // function prototype
    void chorus(int b);
    
    int
    main(void)
    {
    // ask user for number
    printf("How many bottles will there be? ");
    int n = GetInt();
    // exit upon invalid input
    if (n < 1)
    {
    printf("Sorry, that makes no sense.\n");
    return 1;
    }
    // sing the annoying song
    printf("\n");
    while (n)
    chorus(n--);
    // exit when song is over
    printf("Wow, that's annoying.\n");
    return 0;
    }
    
    void
    chorus(int b)
    {
    // use proper grammar
    string s1 = (b == 1) ? "bottle" : "bottles";
    string s2 = (b == 2) ? "bottle" : "bottles";
    
    // sing verses
    printf("%d %s of beer on the wall,\n", b, s1);
    printf("%d %s of beer,\n", b, s1);
    printf("Take one down, pass it around,\n");
    printf("%d %s of beer on the wall.\n\n", b - 1, s2);
    }
    My question is, how does the code know to stop looping when n hits 0? The code says while (n) not while (n>0).

    Thanks in advance!
    Last edited by Learner123; 10-04-2012 at 06:23 AM.

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    In C a plain integer can be used as a boolean value.
    A value of 0 means FALSE; any other value means TRUE.

    So, in your example, n starts with (lets say) 2

    while (2) is the same as while (TRUE)

    then n gets decremented

    while (1) is the same as while (TRUE)

    then n gets decremented

    while (0) is the same as while (FALSE)

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    2
    Thank you very much for your propmt response - - I've been searching for an answer for two full days.

    Thanks again!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-26-2011, 07:36 PM
  2. Replies: 23
    Last Post: 04-05-2011, 03:40 PM
  3. The Infinit loop that doesn't loop.
    By errigour in forum C Programming
    Replies: 1
    Last Post: 11-09-2010, 11:31 AM
  4. for loop ignoring scanf inside loop
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-17-2007, 01:46 AM
  5. Replies: 3
    Last Post: 03-14-2006, 11:09 AM