Introduction
Conditional and looping statements allow decision-making and repetition in C programs. Conditional statements execute code based on certain conditions, while loops repeat a block of code until a condition is met. These are fundamental for building logical and efficient programs.
Key Points
1. Conditional Statements
- if Statement
- Executes a block of code if the condition is true.
- Syntax:
if(condition) { // code }
- if-else Statement
- Provides two branches: executes one if condition is true, another if false.
- Syntax:
if(condition) { // true block } else { // false block }
- Nested if
- if statements inside another if statement for multiple conditions.
- switch-case Statement
- Selects one of many blocks based on variable value.
- Syntax:
switch(variable) { case 1: // code break; case 2: // code break; default: // code }
2. Looping Statements
- for Loop
- Repeats code a known number of times.
- Syntax:
for(initialization; condition; increment/decrement) { // code }
- while Loop
- Repeats code while condition is true.
- Syntax:
while(condition) { // code }
- do-while Loop
- Executes code at least once, then repeats while condition is true.
- Syntax:
do { // code } while(condition);
3. Break & Continue
- break: exits the loop immediately
- continue: skips the current iteration and continues with next
Example Code
#include <stdio.h>
int main() {
int i;
for(i = 1; i <= 5; i++) {
if(i == 3) continue; // skips 3
if(i == 5) break; // exits loop at 5
printf("%d\n", i);
}
int num = 2;
switch(num) {
case 1: printf("One"); break;
case 2: printf("Two"); break;
default: printf("Other");
}
return 0;
}