Basic While Loops in C

The while keyword enables us to implement a loop. A loop allows repeated execution of a statement or block of statements as long as the condition remains true.

The while keyword is followed by a controlling-expression enclosed within parentheses. If the controlling expression evaluates to a nonzero value, the expression is considered to be true, and the body of the loop, consisting of one or more statements enclosed in curly braces, is executed.

#include <stdio.h>

int main(void){
 
  int x = -5;
 
  while(x++){
   printf("x = %d\n", x);
  }
 
  return 0;
 
}

Note that the curly braces are only necessary when the body consists of multiple statements. However, I feel that braces should always be used as it reduces the chance of a problem occurring if we later on decide to add a second statement to the loop.

The condition in a while loop is usually a relational expression.

#include <stdio.h>

int main(void){
 
  int x = 1;
  int y = 21;
 
  while(x!=y){
    printf("x = %d and y = %d\t", x,y);
    printf("x != y\n");
    x++;
    y--;
  }
 
  printf("\nx = %d and y = %d\t", x,y);
  printf("x == y\n");
 
  return 0;

}

When looping, we often use an increment or decrement operator to modify the variable being used in the test expression. However, we can use any sort of expression that modifies the value stored in the tested variable.

 include <stdio.h>

int main(void){
 
  int x = 30;
 
  while(x > 0){
    printf("%d > 0\n", x);
    x = x - 3;
  }
 
  return 0;
 
}

Note that each of the relational and equality operators produces a result of type int regardless of the type of its operands. The value of the result is 0 if the test is false, and 1 if the test is true.

#include <stdio.h>


int main(void){
 
  int i = 73;
  double j = 12.29;
  char k = 'c';
 
 
  printf("k > i = %d\t", k > i);
  printf("k < i = %d\n\n", k < i);
 
  printf("j == i = %d\t", j == i);
  printf("j != i = %d\n\n", j != i);
 
  i = i > k;
  printf("i == 0 = %d\n\n", i == 0);
 
  i = i == 0;
  printf("(i == 1) == (j > i) = %d", (i == 1) == (j > 1));
  return 0;
 
}

Just like if statements, while statements can be nested.

#include <stdio.h>

int main(void){
 
  int i, j;
  i = 0;

 
  while(++i<=10){
    j = 0;
    while(++j<=10){
     printf("%3d\t", i*j);
    }
    printf("\n");
  }
 
  return 0;
 
}