If Statements

Lesson 18
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

In C, an if statement is used to execute a block of code conditionally, depending on whether a given condition is true or false. The syntax of an if statement is as follows:

if (condition) {
  // code to be executed if condition is true
}

Here, condition is any expression that can be evaluated to either true or false. If the condition is true, then the code within the braces is executed. If the condition is false, then the code within the braces is skipped.

For example, consider the following function that checks if a given integer is positive or negative:

void check_sign(int num) {
  if (num > 0) {
    printf("%d is positive.\n", num);
  } else if (num < 0) {
    printf("%d is negative.\n", num);
  } else {
    printf("%d is zero.\n", num);
  }
}

In this function, the if statement is used to check whether the given number is positive, negative, or zero. Depending on the result of the condition, the appropriate message is printed to the console.

In addition to the basic if statement, there are also several variations that can be used in different situations. These include:

  • The if-else statement, which allows for two different blocks of code to be executed depending on the result of the condition.
  • The nested if statement, which allows for multiple levels of conditions to be checked.
  • The switch statement, which provides a way to execute different blocks of code based on the value of a variable.

By using these variations of the if statement, you can create more complex conditional logic in your programs.