C while loop

Syntax for while loop

The general format for a while loop is


while (condition) {
    simple or compound statement (body of the loop);
}

Example for while loop


#include<stdio.h>
/*from   ww  w .  jav  a2s .com*/
main(){
   
    int i = 0;
    while (i<5){
        printf(" the value of i is %d\n", i);
        i = i + 1;
    }
}

The code above generates the following result.


while loop nested in a for loop


#include <stdio.h>
//  w  w w. ja  va2 s. c  o  m
int main(void)
{
  long sum = 1L;
  int j = 1;
  int count = 10;
  int i;
  for(i = 1 ; i <= count ; i++)
  {
    sum = 1L;   
    j=1;        
    printf("\n1");

    while(j < i){
      sum += ++j;
      printf("+%d", j);
    }
    printf(" = %ld\n", sum);
  }
  return 0;
}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array