Skip to content

if-else in C

1. if Statement:

The if statement in C is the most fundamental form of conditional execution. It allows for the execution of a block of code if a specified condition evaluates to true.

Syntax:

if (condition)

{

 // Code block to execute if condition is true

 }

Behavior:

  • The condition within the parentheses is evaluated.
  • If the condition is true, the code block within the curly braces {} is executed.
  • If the condition is false, the code block is skipped, and program execution continues after the if statement.

Example:

int num = 10;

 if (num > 0)

{

printf(“Number is positive\n”);

}

2. if-else Statement:

The if-else statement in C provides a way to execute different blocks of code based on the evaluation of a condition. It executes one block of code if the condition is true and another block of code if the condition is false.

Syntax:

if (condition)

 {

 // Code block to execute if condition is true

}

Else

 {

 // Code block to execute if condition is false

 }

Behavior:

  • The condition within the parentheses is evaluated.
  • If the condition is true, the code block within the first set of curly braces {} is executed.
  • If the condition is false, the code block within the second set of curly braces {} (after else) is executed.

Example:

int num = -5;

if (num > 0)

{

printf(“Number is positive\n”);

 }

 Else

 {

 printf(“Number is not positive\n”);

 }

3. else-if Statement:

The else-if statement in C allows for evaluating multiple conditions sequentially. It is used when there are more than two possible outcomes based on the evaluation of different conditions.

Syntax:

if (condition1)

 {

 // Code block to execute if condition1 is true

 }

else if (condition2)

{

// Code block to execute if condition2 is true

}

else

{

// Code block to execute if none of the above conditions are true

 }

Behavior:

  • Conditions are evaluated sequentially, from top to bottom.
  • If the first condition is true, the corresponding code block is executed, and subsequent conditions are not evaluated.
  • If none of the conditions are true, the code block within the else statement (if present) is executed.

Example:

int num = 0;

if (num > 0)

{

 printf(“Number is positive\n”);

}

else if (num < 0)

 {

printf(“Number is negative\n”);

}

Else

 {

printf(“Number is zero\n”);

 }

Conclusion:

Conditional statements in C, including if, if-else, and else-if, provide the essential mechanism for implementing decision-making logic in programs. They allow programmers to control the flow of execution based on specific conditions, enabling the creation of flexible and responsive code. By understanding how to use these conditional statements effectively, programmers can write structured, readable, and functional C programs to address various programming challenges.