C Language | Flow Control | if Statements

The if statement selects which code to execute based on a condition.

Branching a Program

An if statement executes a statement only when its condition is true.

if (condition) statement

In C, zero is false and any nonzero value is true.

Code 1

#include <stdio.h>

int main() {
 int iBool;
 printf("Enter zero or another value. >");
 scanf("%d" , &iBool);

 if (iBool) printf("You entered true.\n");
 if (!iBool) printf("You entered false.\n");
 return 0;
}

Use else to execute an alternative statement when the condition is false.

if (condition) statement1
else statement2

Code 2

#include <stdio.h>

int main() {
 int iBool;
 printf("Enter zero or another value. >");
 scanf("%d" , &iBool);

 if (iBool) printf("You entered true.\n");
 else printf("You entered false.\n");
 return 0;
}

Chain else if clauses when a program needs to test multiple alternatives.

Code 3

#include <stdio.h>

int main() {
 char chVar;
 printf("Do you like C? Y/N>");
 scanf(" %c" , &chVar);

 if (chVar == 'Y' || chVar == 'y')
   printf("Good. Keep learning.\n");
 else if (chVar == 'N' || chVar == 'n')
   printf("Keep going anyway.\n");
 else
   printf("Invalid input.\n");
 return 0;
}

Compound Statements

An if or else controls one statement. To execute multiple statements together, use a compound statement, also called a block.

{
 statement1
 statement2
}

Indent nested blocks consistently so their structure remains clear.

Code 4

#include <stdio.h>

int main() {
 int iBool;
 printf("Enter zero or another value. >");
 scanf("%d" , &iBool);

 if (iBool) {
   printf("You entered true.\n");
   return 1;
 }
 else {
   printf("You entered false.\n");
   return 0;
 }
}