Conditions and loops

if, switch, for, while and do-while.

C
#include <stdio.h>

int main(void) {
  int marks = 76;
  if (marks >= 75) {
    printf("Distinction\n");
  } else if (marks >= 50) {
    printf("Pass\n");
  } else {
    printf("Fail\n");
  }

  for (int i = 1; i <= 3; i++) {
    printf("%d ", i * i);
  }
  printf("\n");

  int n = 3;
  while (n > 0) {
    n--;
  }
  printf("%d\n", n);
  return 0;
}
Output
Distinction
1 4 9 
0

A do-while loop runs its body at least once, because the test comes at the end.

C
#include <stdio.h>

int main(void) {
  int day = 2;
  switch (day) {
    case 1:
      printf("Monday\n");
      break;
    case 2:
      printf("Tuesday\n");
      break;
    default:
      printf("Other\n");
  }
  return 0;
}
Output
Tuesday

Without break, a switch falls through into the next case. This is rarely what you want.

โ† Types and operatorsFunctions and arrays โ†’