CBasics
C Control Statements (if, else, switch)
Learn C control statements such as if, else, else-if, and switch to control the flow of execution and make decisions in C programs.
What are Control Statements in C?Link to this section
Control statements are used to control the flow of execution in a C program. They allow the program to make decisions and execute different blocks of code based on conditions.
By default, C programs execute statements sequentially. Control statements change this normal flow.
Types of Control Statements :Link to this section
C provides several control statements, including:
- if statement
- if–else statement
- else-if ladder
- switch statement
The " if "Statement :Link to this section
The if statement executes a block of code only when a given condition is true.
Explanation:
If the condition evaluates to true, the code inside the if block runs.
The " if–else " Statement :Link to this section
The if–else statement provides an alternative block of code when the condition is false.
The " else-if " Ladder :Link to this section
When multiple conditions need to be checked, the else-if ladder is used.
note
Conditions are evaluated from top to bottom. Once a true condition is found, the remaining conditions are skipped.
The switch Statement :Link to this section
The switch statement is used when a variable is compared against multiple fixed values.
Explanation:
- case specifies a value
- break stops execution
- default runs if no case matches
Importance of the " break "Statement :Link to this section
The break statement prevents fall-through, where multiple cases execute unintentionally.
warning
Omitting break can cause unexpected results.
When to Use if–else vs switch :Link to this section
Use if–else when
- Conditions involve ranges - Logical operators are requiredUse switch when
- Comparing a single variable - Checking fixed constant valuesWhy Control Statements are Important :Link to this section
Control statements allow programs to:
- Make decisions
- Handle different scenarios
- Implement business logic
tip
Most real-world programs rely heavily on control statements.
Check Your Understanding
Question 1 of 5Which statement executes code only when a condition is true?
Practice Challenges
- Write a program to check whether a number is positive, negative, or zero.
- Create a grading system using else-if ladder.
- Use switch to display the name of the day based on a number.
- Convert an if–else ladder into a switch statement where possible.
- Predict the output of a switch statement with missing break.