Thursday, June 20, 2024

CONTROL STATEMENT

Control statements are fundamental elements in programming that allow you to control the flow of execution based on certain conditions. Here’s a brief overview of the various control statements:

  • if: Executes a block of code if a condition is true.
  • else: Executes a block of code if the if condition is false.
  • else if: Tests additional conditions if the previous conditions are false.
  • switch/case: Executes one block of code among many based on the value of an expression.


1. if Statement

The if statement executes a block of code if a specified condition is true.

  • Syntax:
if (condition) {
// code to be executed if condition is true
}
  • Example:
int age = 18;
if (age >= 18) {
printf("You are an adult.\n");
}


2. else Statement

The else statement follows an if statement and executes a block of code if the condition in the if statement is false.

  • Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
  • Example:
int age = 17;
if (age >= 18) {
printf("You are an adult.\n");
} else {
printf("You are not an adult.\n");
}



3. if/else if/else Statement

This structure allows you to test multiple conditions and execute different blocks of code based on which condition is true.

  • Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
  • Example:
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}



4. switch/case Statement

The switch statement allows you to execute one code block out of many based on the value of a variable.

  • Syntax:
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// more cases...
default:
// code to be executed if expression doesn't match any constant
}
  • Example:
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}

 

No comments:

Post a Comment