M3 Conditional Statements and Loops in C
M3 Conditional Statements and Loops in C
Conditional Statements
Conditional statements allow a program to make decisions and execute different code based on specific
conditions.
● Definition: Enables the program to evaluate conditions and take different paths based on the result (true or
false).
● Common Usage:
○ Checking user input.
○ Controlling the flow of operations.
○ Making logical decisions.
Conditions
Example:
Copy code
int age = 18;
if (age >= 18) {
printf("You are eligible to vote.");
}
Relational Operators
== Equal to a == b
!= Not equal to a != b
1. if Statement
Syntax:
Copy code
if (condition) {
// Code to execute if condition is true
}
Example:
Copy code
if (score > 50) {
printf("You passed the exam.\n");
}
2. if-else Statement
Syntax:
Copy code
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
Copy code
if (age >= 18) {
printf("You can vote.\n");
} else {
printf("You are too young to vote.\n");
}
Syntax:
Copy code
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the above conditions are true
}
Example:
Copy code
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 75) {
printf("Grade B\n");
} else {
printf("Grade C\n");
}
4. Switch Statement
Syntax:
Copy code
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no cases match
}
Example:
Copy code
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
Loops
Loops are used to execute a block of code multiple times based on a condition.
1. while Loop
Syntax:
Copy code
while (condition) {
// Code to execute
}
Example:
Copy code
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
2. do-while Loop
● Executes the code block at least once, then checks the condition.
Syntax:
Copy code
do {
// Code to execute
} while (condition);
Example:
Copy code
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
3. for Loop
Syntax:
Copy code
for (initialization; condition; update) {
// Code to execute
}
Example:
Copy code
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
Nested Loops
Example:
Copy code
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
printf("i=%d, j=%d\n", i, j);
}
}
Infinite Loops
Structured Programming