An Initial Example
You are already somewhat familiar with the while loop, but let's review it with a program that sums integers entered from the keyboard (see Listing 6.1). This example makes use of the return value of scanf() to terminate input.
Listing 6.1. The summing.c Program
/* summing.c -- sums integers entered interactively */ #include <stdio.h> int main(void) { long num; long sum = 0L; /* initialize sum to zero */ int status; printf("Please enter an integer to be summed. "); printf("Enter q to quit.\n"); status = scanf("%ld", &num); while (status == 1) /* == means "is equal to" */ { sum = sum + num; printf("Please enter next integer to be summed. "); printf("Enter q to quit.\n"); status = scanf("%ld", &num); } printf("Those integers ... |
Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.