The if-else statement is a fundamental construct in the C programming language that allows you to execute different blocks of code based on certain conditions. It provides a way to control the flow of your program and make decisions based on specific criteria. In this article, we will explore the if-else statement in C and provide examples to illustrate its usage.
The Syntax of the if-else Statement
The syntax of the if-else statement in C is as follows:
if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false }
The condition is an expression that evaluates to either true or false. If the condition is true, the code block within the if statement is executed. If the condition is false, the code block within the else statement is executed.
Example 1: Checking if a Number is Even or Odd
Let’s start with a simple example to demonstrate the usage of the if-else statement. We will write a program that checks if a given number is even or odd.
#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); if (number % 2 == 0) { printf("%d is even.", number); } else { printf("%d is odd.", number); } return 0; }
In this example, we prompt the user to enter a number, and then use the if-else statement to determine if the number is even or odd. The condition number % 2 == 0
checks if the remainder of the division of the number by 2 is equal to 0. If it is, the number is even; otherwise, it is odd.
Example 2: Determining the Grade of a Student
Now, let’s consider a more complex example where we determine the grade of a student based on their score. We will assume a grading scale from 0 to 100, with the following ranges:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- 0-59: F
#include <stdio.h> int main() { int score; printf("Enter the student's score: "); scanf("%d", &score); if (score >= 90) { printf("Grade: A"); } else if (score >= 80) { printf("Grade: B"); } else if (score >= 70) { printf("Grade: C"); } else if (score >= 60) { printf("Grade: D"); } else { printf("Grade: F"); } return 0; }
In this example, we use multiple if-else statements to check the score against different ranges and assign the corresponding grade. The conditions are evaluated sequentially, and the first condition that evaluates to true is executed. If none of the conditions are true, the code block within the else statement is executed, assigning an F grade.
The if-else statement is a powerful tool in C programming that allows you to make decisions based on specific conditions. It provides a way to control the flow of your program and execute different blocks of code accordingly. By understanding the syntax and examples provided in this article, you should now have a solid foundation for using the if-else statement in your C programs.