1. // Abstraction and scope
 3.  #include <cs50.h>
 4.  #include <stdio.h>
 6.  int get_positive_int(string prompt);
 8.  int main(void)
 9.  {
 10.    int i = get_positive_int("Positive integer: ");
 11.    printf("%i\n", i);
 12. }
 14. // Prompt user for positive integer
 15. int get_positive_int(string prompt)
 16. {
 17.    int n;
 18.    do
 19.    {
 20.       n = get_int("%s", prompt);
 21.    }
 22.     while (n < 1);
 23.    return n;
 24.    }

I am having trouble understanding the program positive.c.

Q.1: When the program starts the main function at line 10 calls the "get_positive_int" function, at this point the flow control should move to line 15 and line 11 should not be executed, hence no print message. But the program prints the message.

Q.2 Function "get_positive_int" repeats itself after false value but prints the message why? "get_int" should prompt for the user input but no print the message "Positive integer: ". During this loop why it prints the message as there is no referece to it.

1 Answer 1


At line 10, the program calls get_positive_int with the string argument "Positive integer: "

This takes us to the function in line 15 and eventually to line 20, when get_int is called with the string prompt that was passed as the argument, so get_int will print "Positive integer: "

If you give an invalid number, the loop will run again, and once more, get_int will be called and will print "Positive integer: "

Once you give a valid number, line 23 will return that value back to the calling function (main) and store the value in the variable i (line 10). And then, line 11 will run and print that value of i to the terminal.

Main then ends.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .