I dont understand why this works

+1 Ash Marz · June 30, 2015

    long num;
    long sum = 0L;
    int status;
    /* initialize sum to zero */
    printf("Please enter an integer to be summed ");
    printf("(q to quit): ");
    status = scanf("%ld", &num);
    while (status == 1) /* == means "is equal to" */ {
        sum = sum + num;
        printf("Please enter next integer (q to quit): "); status = scanf("%ld", &num);
    printf("Those integers sum to %ld.\n", sum);

Post a Reply


Oldest  Newest  Rating
0 Ash Marz · June 30, 2015
it says: 

while(status ==1) 

i dont get that part
0 Alan Johnson · July 1, 2015
You've answered your own question in your code. == means check for equality.

while(status == 1)

Will continuously execute the code inside the while loop until you enter something other than 1.
+1 c student · July 1, 2015
@Alan Johnson
That's not quite correct.  What your status variable is is the return value of the scanf function. The scanf function returns the number of successful inputs.  Example:
int ret = scanf ("%d", &number);

ret will be 1 if the inputted number matches the %d format, otherwise it will be 0.

In the piece of code OP has provided, it checks whether the input matches the %ld format.  If it does not (note where it prompts "Please enter next integer (q to quit): "), it will return 0 into status and therefore break the while loop.

scanf manpage:
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator