Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Apr 20, 2024
Difficulty: Easy

if else Statement in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

If-else statements are a fundamental concept in C programming that allow you to control the flow of your program based on certain conditions. They let you specify different actions to take depending on whether a condition is true or false. With if-else statements, you can make your program respond intelligently to different situations & inputs. 

if else Statement in C

In this article, we will cover what if & if-else statements are, their syntax, how to use them effectively in C programs with examples, & their advantages & disadvantages. 

C if Statement

The 'if' statement in C is one of the simplest forms of decision-making statements. It evaluates a condition: if the condition is true, the code inside the 'if' block is executed. If the condition is false, the code inside the block is skipped. This functionality is fundamental in programming when we need the program to make choices or execute specific operations based on certain criteria.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example 

Let's consider a basic example. Suppose we want to check if a number is positive. Here’s how we might write this using an if statement in C:

  • C

C

#include <stdio.h>

int main() {

   int number = 10;  // Change this number to test with different values

   if (number > 0) {

       printf("The number is positive.\n");

   return 0;

}

Output

The number is positive.


In this example, the program checks if number is greater than 0. If true, it prints that the number is positive. Change the value of number to see different outcomes when you run the code.

C if-else Statement

After understanding the 'if' statement, we'll now look at the 'if-else' statement, which is an extension of the 'if' statement. While the 'if' statement performs an action when the condition is true, the 'if-else' statement allows us to specify an alternative action if the condition is false.

How does it work?

When you use an 'if-else' statement, the program first checks the condition inside the 'if'. If this condition is true, the program executes the block of code following the 'if'. If the condition is false, the program skips the 'if' block and executes the code inside the 'else' block.

Example
 

  • C

C

#include <stdio.h>

int main() {

   int age = 18;  // Change this value to test different outcomes


   if (age >= 18) {

       printf("You are eligible to vote.\n");

   } else {

       printf("You are not eligible to vote.\n");

   }

   return 0;

}

Output

You are eligible to vote.


In this code, the program checks if the age variable is 18 or more. If yes, it prints that the user is eligible to vote. Otherwise, it informs the user that they are not eligible.

Syntax of if-else

Understanding the syntax of the if-else statement is key to using it effectively in your C programs. The syntax is straightforward and follows a clear structure:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Components of the if-else Syntax

  • Condition: This is a boolean expression that evaluates to true or false. It’s placed inside the parentheses after the 'if' keyword.
     
  • If block: The code inside this block runs if the condition is true.
     
  • Else block: The code inside this block runs if the condition is false.

It's important to note that:

  • The code blocks can contain one or more statements.
     
  • The curly braces {} are required if the code block contains multiple statements. If there's only one statement, the braces can be omitted (although it's still considered good practice to include them for clarity & consistency).
     
  • The else block is optional. If you omit the else block, the if-else statement becomes a simple if statement.

Here’s how you can use this syntax in a real scenario:

  • C

C

#include <stdio.h>

int main() {

   int score = 85;  // Change the score to see different outputs

   if (score >= 50) {

       printf("Congratulations! You passed.\n");

   } else {

       printf("Try again next time.\n");

   }

  return 0;

}

Output

Congratulations! You passed.

In this example, the program checks if the score is 50 or above. If this condition is true, it prints a congratulatory message. If the condition is false, it advises trying again.

How to Use if-else in C?

Using the if-else statement in C is a fundamental skill for controlling the flow of your program based on conditions. Here's a step-by-step guide to using if-else effectively:

  • Identify the Condition: First, determine the condition under which you want different actions to occur.
     
  • Write the If Block: This block should contain the code that executes when your condition is true.
     
  • Write the Else Block: This block should contain the code that executes when your condition is false.

Example

  • C

C

#include <stdio.h>

int main() {

   int score = 72;  // Change this score to see different grades

   if (score >= 90) {

       printf("Your grade is A.\n");

   } else if (score >= 80) {

       printf("Your grade is B.\n");

   } else if (score >= 70) {

       printf("Your grade is C.\n");

   } else if (score >= 60) {

       printf("Your grade is D.\n");

   } else {

       printf("Your grade is F.\n");

   }

   return 0;

}

Output

Your grade is C.


In this example, the score is checked against several conditions to determine the grade. The program prints the corresponding grade based on where the score falls within these ranges.

How if-else Statement Works?

The if-else statement in C allows your program to choose between two paths based on whether a condition is true or false. Here's a deeper look at how this mechanism functions:

  • Evaluation of Condition: The statement starts by evaluating a condition placed within the parentheses of the if. This condition is a boolean expression that results in either true or false.
     
  • Execution of Blocks:
     
  • If the condition is true: The program executes the block of code inside the if statement.
     
  • If the condition is false: The program skips the if block and executes the code inside the else block.

Understanding with a Flow Diagram

To clarify the operational flow of an if-else statement, consider this simple diagram:

Understanding with a Flow Diagram

Let's look at an example where we determine if a number is odd or even:

  • C

C

#include <stdio.h>

int main() {

   int number = 23;  // Try changing this number to test the output

   if (number % 2 == 0) {

       printf("%d is even.\n", number);

   } else {

       printf("%d is odd.\n", number);

   }

   return 0;

}

Output

23 is odd
  • In this code, the condition (number % 2 == 0) checks if the number is divisible by 2 (an even number).
     
  • If true, it prints that the number is even.
     
  • If false, it prints that the number is odd.

Flowchart of the if-else Statement

A flowchart is a visual representation that illustrates the sequence of operations to be performed to get the result of a program. It's particularly useful in explaining the logic before the actual coding begins. Here’s how the if-else statement can be depicted in a flowchart:

Flowchart of the if-else Statement

Let's go through the flowchart step by step:

  • The flowchart starts with the "Start" symbol, indicating the beginning of the if-else statement.
     
  • It then moves to the "Condition" diamond symbol, where the condition is evaluated. The condition is an expression that can be either true or false.
     
  • From the "Condition" symbol, there are two paths:
     
  • If the condition is true, the flow moves to the "Code Block 1" rectangle symbol, representing the code block that is executed when the condition is true.
     
  • If the condition is false, the flow moves to the "Code Block 2" rectangle symbol, representing the code block that is executed when the condition is false.
     
  • After executing the respective code block (either "Code Block 1" or "Code Block 2"), the flow converges back to a single path.
     
  • The flowchart ends with the "End" symbol, indicating the completion of the if-else statement.

Examples of if-else Statement in C

Example 1: C Program to Check Whether a Given Number is Even or Odd

This program determines if a number is even or odd, a fundamental task in many programming scenarios.

  • C

C

#include <stdio.h>

int main() {

   int number;

   printf("Enter a number: ");

   scanf("%d", &number);

   if (number % 2 == 0) {

       printf("The number %d is even.\n", number);

   } else {

       printf("The number %d is odd.\n", number);

   }

   return 0;

}

Output

Enter a number: 26
The number 26 is even.


In this example:

The user inputs a number.

The program uses the modulus operator % to determine the remainder when the number is divided by 2.

If the remainder is 0, the number is even; otherwise, it's odd.

Example 2: C Program to Check Whether a Person is Eligible to Vote or Not

This example checks if the age entered by the user meets the minimum voting age requirement.

  • C

C

#include <stdio.h>

int main() {

   int age;

   printf("Enter your age: ");

   scanf("%d", &age);


   if (age >= 18) {

       printf("You are eligible to vote.\n");

   } else {

       printf("Sorry, you are not eligible to vote.\n");

   }


   return 0;

}

Output

Enter your age: 35
You are eligible to vote.

In this program:

  • The user inputs their age.
     
  • The program checks if the age is 18 or older.
     
  • If true, it prints that the user is eligible to vote.
     
  • If false, it informs the user they are not eligible.

Advantages of if-else Statement

  • Decision Making: The if-else statement allows you to make decisions in your program based on different conditions. It enables your program to execute different code blocks depending on whether a condition is true or false. This decision-making capability is essential for creating programs that can adapt to various situations & inputs.
     
  • Program Flow Control: With if-else statements, you can control the flow of your program. You can specify which code blocks should be executed under certain conditions & which ones should be skipped. This helps in creating logical & efficient program flow, ensuring that the appropriate actions are taken based on the program's state or user input.
     
  • Code Readability: If-else statements enhance the readability of your code. By using if-else statements, you can clearly separate different conditions & their corresponding actions. This makes your code more structured, easier to understand, & maintainable. It helps other developers (or yourself in the future) to grasp the logic of your program quickly.
     
  • Error Handling: If-else statements are useful for handling errors or exceptional cases in your program. You can use them to check for invalid inputs, out-of-range values, or other error conditions. By providing appropriate error messages or taking alternative actions in the else block, you can gracefully handle errors & prevent program crashes.
     
  • Code Reusability: If-else statements allow you to write modular & reusable code. You can encapsulate specific conditions & their corresponding actions into separate if-else blocks. This modular approach makes it easier to reuse the code in different parts of your program or in other programs altogether.
     
  • Flexibility: If-else statements provide flexibility in executing different code based on conditions. You can have multiple if-else statements nested within each other or use them in combination with other control structures like loops. This flexibility enables you to create complex decision-making logic & handle various scenarios effectively.

Disadvantages of if-else Statement

  • Complex Nested Structures: If-else statements can become complex & difficult to read when there are multiple levels of nesting. When you have if-else statements inside other if-else statements, the code can become harder to understand & maintain. Deeply nested if-else statements can lead to what is known as the "pyramid of doom" or "arrow anti-pattern," making the code less readable & more error-prone.
     
  • Limited Scalability: As the number of conditions & branches increases, if-else statements can become cumbersome to manage. If you have many conditions to check, the if-else structure can grow quite large & become difficult to extend or modify. In such cases, alternative control structures like switch statements or lookup tables might be more suitable & scalable.
     
  • Lack of Expressiveness: If-else statements are not always the most expressive way to represent complex decision-making logic. Sometimes, the conditions & their corresponding actions can be more clearly expressed using other techniques such as polymorphism, function pointers, or design patterns. If-else statements may not always convey the intent of the code as clearly as other approaches.
     
  • Potential for Errors: If-else statements rely on the correct evaluation of conditions. If the conditions are not properly defined or if there are logical errors in the conditions, it can lead to unexpected program behavior. Missing an important condition or having overlapping conditions can introduce bugs that are difficult to identify & debug.
     
  • Inefficient for Large Number of Conditions: If you have a large number of conditions to check, using if-else statements can lead to inefficient code. Evaluating each condition sequentially can be time-consuming, especially if the number of conditions is significant. In such cases, alternative approaches like lookup tables or binary search might provide better performance.
     
  • Limited Reusability: While if-else statements can be used to create modular & reusable code, they may not always promote the highest level of code reusability. If the conditions & actions are tightly coupled within the if-else blocks, it can be challenging to reuse that code in different contexts without modification.

Frequently Asked Questions

Can if-else statements be nested in C?

Yes, you can nest if-else statements within each other to handle more complex decision structures. This is useful when multiple conditions need to be evaluated sequentially.

Is there a limit to the number of else-if statements you can have?

No, there is no strict limit in C on the number of else-if clauses you can use after an if statement. However, for readability and maintenance, it's advisable to keep the number minimal or use a switch-case statement instead.

How can I improve the performance of nested if-else statements?

To enhance performance, always place the most likely condition to succeed at the beginning of the if-else chain. This reduces the number of checks the program needs to perform on average.

Conclusion

In this article, we have learned the fundamental concepts of if-else statements in C programming. We've explored their syntax, how they work, and provided practical examples of their use. We also talked about the advantages & disadvantages of if-else statements also. This knowledge is crucial for making decisions in your programs, allowing you to handle various scenarios with ease.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
C if Statement
3.
Example 
3.1.
C
4.
C if-else Statement
4.1.
How does it work?
4.2.
Example 
4.3.
C
4.4.
Syntax of if-else
4.5.
Components of the if-else Syntax
4.6.
C
4.7.
How to Use if-else in C?
4.8.
Example
4.9.
C
5.
How if-else Statement Works?
6.
Understanding with a Flow Diagram
6.1.
C
7.
Flowchart of the if-else Statement
8.
Examples of if-else Statement in C
8.1.
Example 1: C Program to Check Whether a Given Number is Even or Odd
8.2.
C
8.3.
Example 2: C Program to Check Whether a Person is Eligible to Vote or Not
8.4.
C
9.
Advantages of if-else Statement
10.
Disadvantages of if-else Statement
11.
Frequently Asked Questions
11.1.
Can if-else statements be nested in C?
11.2.
Is there a limit to the number of else-if statements you can have?
11.3.
How can I improve the performance of nested if-else statements?
12.
Conclusion