C - Statement while Statement


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 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++;/*  w ww  .  j av  a  2s .c  o  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;

Related Topics