Course Content
C Tutorial
About Lesson

Conditional Statements (if, else, switch)

Conditional statements form the backbone of decision-making in C programming. They allow the execution of specific code blocks based on certain conditions. In C, the primary conditional statements include if, else, and switch, each serving distinct purposes in controlling program flow.

The ‘if’ Statement in C

The if statement evaluates a condition and executes a block of code if the condition is true. It’s fundamental in creating branching logic within programs, enabling different actions based on varying conditions.

Syntax of ‘if’ Statement

The basic syntax of the ‘if’ statement in C is:

if (condition) {
// Code block executed if the condition is true
}

The ‘else’ Statement in C

When coupled with ‘if’, the else statement allows the execution of a different block of code if the condition in the ‘if’ statement is false. It provides an alternative path when the initial condition isn’t met.

Syntax of ‘if-else’ Statement

The syntax for using ‘if-else’ in C:

if (condition) {
// Code block executed if the condition is true
} else {
// Code block executed if the condition is false
}

The ‘switch’ Statement in C

The switch statement offers an efficient way to handle multiple potential conditions by evaluating an expression and executing a specific block of code based on its value.

Syntax of ‘switch’ Statement

The basic syntax of the ‘switch’ statement in C:

switch (expression) {
case constant1:
// Code block executed if expression matches constant1
break;
case constant2:
// Code block executed if expression matches constant2
break;
default:
// Code block executed if no match is found
}

Key Considerations

  • Use ‘if’ statements for simple conditions and ‘switch’ for multiple cases with a single expression.
  • ‘else if’ statements can be employed to test multiple conditions in sequence after an initial ‘if’.
  • ‘switch’ statements work with integral types and can only compare equality, while ‘if’ statements allow more flexible conditions