With a while loop, the repeating continues as long as a specified logical expression evaluates to true.
The general syntax for the while loop is as follows:
while( expression ) statement1; statement2; statement1 and statement2 could each be a block of statements.
The condition for continuation of the while loop is tested at the start.
If expression starts out false, none of the loop statements will be executed.
The following code use while loop to sum integers
#include <stdio.h> int main(void) { unsigned long sum = 0UL; // The sum of the integers unsigned int i = 1; // Indexes through the integers unsigned int count = 0; // The count of integers to be summed // Get the count of the number of integers to sum printf("\nEnter the number of integers you want to sum: "); scanf(" %u", &count); // Sum the integers from 1 to count while(i <= count) sum += i++;//from ww w . ja va 2 s .co m printf("Total of the first %u numbers is %lu\n", count, sum); return 0; }
Consider the following code:
while(i <= count)
sum += i++;
the loop body contains a single statement that accumulates the total in sum.
This continues to be executed with i values up to and including the value stored in count.
The postfix increment operator makes i incremented after its value is used to compute sum on each iteration.
What the statement really means is this:
sum += i; i++;