View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
c tutorial

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

  • 130 Lessons
  • 22 Hours
right-top-arrow

Tutorial Playlist

132 Lessons
71

If Else Statement in C

Updated on 14/10/20244,741 Views

In computer programming, control statements are vital as they determine the flow of execution of a program. They dictate how operations are carried out based on certain conditions. In the C programming language, one of the most common control statements used is the "if-else" statement.

Let’s explore this fundamental concept to help you find answers to if…else statement in C questions.

Introduction

In C, the "if-else" statement is a conditional branch statement that allows the program to take a decision based on the result of an expression or condition. It checks for a condition: if the condition is true, it executes a block of code; otherwise, it executes another block of code.

The syntax for the "if-else" statement is:

if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}

What is if-else statement in C

The if-else statement is a conditional statement in C that performs diverse computations based on whether a programmer-specified boolean condition results in true or false. The else part of the statement is optional, which means you may have an 'if' statement without the 'else' clause.

Here’s a simple example of an if-else statement:

#include<stdio.h>

int main()
{
int num = 10;

if(num > 5)
{
printf("Number is greater than 5\n");
}
else
{
printf("Number is not greater than 5\n");
}

return 0;
}

In the above program, the condition num > 5 is true. Hence, ‘Number is greater than 5’ will be printed.

C if...else Ladder

The "if-else" ladder (also known as else-if ladder) is used when multiple conditions are to be tested. If the condition in the 'if' statement is false, it checks the next 'else if' condition, and so on. If all conditions are false, the 'else' statement is executed.

if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if condition2 is true
}
else
{
// block of code to be executed if both conditions are false
}

Example:

#include<stdio.h>

int main()
{
int num = 10;

if(num == 5)
{
printf("Number is 5\n");
}
else if(num == 10)
{
printf("Number is 10\n");
}
else
{
printf("Number is not 5 or 10\n");
}

return 0;
}

In this program, since the number is 10, the output will be ‘Number is 10’.

Let’s take a more real and concrete example of the if…else ladder, and see how we can use it to categorise the grades of a student based on their scores:

#include<stdio.h>

int main() {
int score;

printf("Enter your score: ");
scanf("%d", &score);

if(score >= 90) {
printf("Bravo!\n");
}
else if(score >= 80) {
printf("Well done!\n");
}
else if(score >= 70) {
printf("Good job!\n");
}
else if(score >= 60) {
printf("Could be better!\n");
}
else {
printf("You need to work harder!\n");
}

return 0;
}

In this program, the student's score is first taken as input. Then, it's checked against various conditions:

  • If the score is 90 or more, "Bravo!" is printed.
  • If the score didn't meet the previous condition but is 80 or more, "Well done!" is printed.
  • If the score is still less but is 70 or more, "Good job!" is printed.
  • If the score is at least 60, "Could be better!" is printed.
  • If none of the above conditions are met, "You need to work harder!" is printed.

Here, the order of conditions is crucial. If we start checking from the lowest score, a score of 90 would also be considered "Could be better!" which is not what we want. Hence, the conditions are arranged in descending order of scores.

Flowchart of the if-else statement in C

A flowchart is a graphical representation of an algorithm or a process. It uses various symbols to denote different types of instructions. For the if-else statement, the flowchart helps visualise how the program flow changes based on the evaluated condition.

Here's how to interpret this flowchart:

  • Start: This symbol denotes the start of the program flow.
  • Condition: This diamond-shaped symbol represents the conditional check (true or false) in the if-else statement.
  • True / False: These arrows denote the direction of the program flow based on whether the condition evaluates to true or false.
  • Code Block 1 / Code Block 2: These rectangular boxes represent the block of code that's executed based on the condition's evaluation. Code Block 1 is executed if the condition is true, while Code Block 2 is executed if the condition is false.
  • End: This symbol denotes the end of the program flow.

Taking a real-world example, let's say we're checking if a digit is positive or negative:

#include<stdio.h>

int main() {
int num;

printf("Enter a digit: ");
scanf("%d", &num);

if(num >= 0) {
printf("Digit is positive.\n");
}
else {
printf("Digit is negative.\n");
}

return 0;
}

The flowchart for this code would work as follows:

  • Start: The program begins.
  • Condition: The condition num >= 0 is checked.
  • True: If the number is greater than or equal to zero, it follows the "True" path. The corresponding code block (printf("Digit is positive.\n")) is executed.
  • False: If the number is less than zero, it follows the "False" path. The corresponding code block (printf("Digit is negative.\n")) is executed.
  • End: The program ends.

This flowchart helps understand the flow of the program and how the control shifts between the if and else blocks based on the condition.

How does the if-else statement in C work?

The way the if-else statement operates can be broken down into the following steps:

1. Evaluation of the Condition: The if-else statement begins with the keyword if, followed by a condition enclosed in parentheses ( ). This condition often involves a comparison or logical operator. The condition could be as simple as checking whether a variable is greater than a certain number or involve complex expressions that evaluate to either true (non-zero) or false (zero).

if (num > 10)

Here, the condition num > 10 is checked. If num is indeed greater than 10, this condition evaluates to true.

2. Execution of the 'if' Block: If the condition within the if statement evaluates to true, the code block immediately following the if statement (enclosed in curly braces { }) gets executed. This block can contain any number of statements or be empty.

if (num > 10)
{
printf("Number is greater than 10\n");
}

Here, if num is greater than 10, the message "Number is greater than 10" is printed to the console.

3. Evaluation of the 'else' Block: If the condition within the if statement evaluates to false, the else block (if it exists) is executed. The else keyword is followed by a block of code (again, enclosed in curly braces { }).

if (num > 10)
{
printf("Number is greater than 10\n");
}
else
{
printf("Number is not greater than 10\n");
}

In this case, if the num is not greater than 10, the message "Number is not greater than 10" is printed to the console.

In summary, the if-else statement in C provides a mechanism for branching - the ability to alter the flow of program execution based on whether a condition is true or false. Only one of the code blocks associated with the if or else statement will execute, depending on the evaluation of the initial condition.

Example of if-else statement in C

Let's take a real-world if-else statement example where we want to check if a person is eligible to vote or not. The eligibility criterion is that the person must be 18 years or older.

#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("You are not eligible to vote.\n");
}

return 0;
}

Advantages and Disadvantages of If else statement in C

While the if-else statement is a versatile tool in C programming, like any other construct, it comes with its advantages and disadvantages. Let's break down the benefits and drawbacks, supported with coding examples.

Advantages:

1. Simple and Easy to Understand: The if-else syntax is simple and straightforward, making the code easier to read and understand. For beginners, this provides a convenient entry point into conditional programming.

int num = 10;
if(num > 5)
{
printf("Number is greater than 5\n");
}
else
{
printf("Number is not greater than 5\n");
}

In this code snippet, it's immediately clear that we're checking whether a number is greater than 5, and taking action accordingly.

2. Helps in Decision Making Based on Conditions: The if-else statement is vital in making decisions in the code based on specific conditions. This is the crux of any programming logic.

int temperature = 25;
if(temperature > 30)
{
printf("Turn on the air conditioner.\n");
}
else
{
printf("No need for air conditioning.\n");
}

Here, the decision to turn on the air conditioner depends entirely on the temperature value.

Disadvantages:

1. Can Lead to Complex and Nested Code: While an if-else statement might seem simple, misuse can lead to deeply nested, complicated code structures which are hard to read and understand. This is commonly known as the "Arrow Anti-Pattern".

int num = 10;
if(num > 5)
{
if(num < 20)
{
if(num == 10)
{
printf("Number is 10\n");
}
else
{
printf("Number is between 5 and 20 but not 10\n");
}
}
else
{
printf("Number is greater than 20\n");
}
}
else
{
printf("Number is not greater than 5\n");
}

While logically correct, the above code is overly complex for what it achieves.

2. Inefficient when Checking Multiple Conditions: When there are multiple conditions to check against a single variable, an if-else ladder becomes inefficient, and a switch statement should be used instead.

int day = 3;
if(day == 1)
{
printf("Monday\n");
}
else if(day == 2)
{
printf("Tuesday\n");
}
else if(day == 3)
{
printf("Wednesday\n");
}
// ... And so on for each day of the week

The above code can be much more efficiently written using a switch statement.

Conclusion

The if-else statement is an essential feature of the C programming language. It provides control flow mechanisms that enable your code to execute differently based on various conditions, thus adding logic and versatility to your programs. From checking simple conditions to implementing complex decision-making logic, the if-else construct proves to be a powerful tool in the C programming arsenal.

While we've covered the basics and usage of if-else statements in this article, remember that mastering them requires continuous practice and application in various scenarios, like any other programming concept.

If you're interested in learning more about C programming and other essential concepts in depth, consider enrolling in upGrad’s DevOps Engineer Bootcamp, which will enable you to further enhance your command of programming languages.

FAQs

1. What are some common if...else statements in C questions?
Common questions around the if-else Statement in C typically involve understanding its syntax, usage, and role within the larger context of control statements in C. Queries often include asking how to use it effectively, when to use it versus other control structures, and understanding how it operates in different scenarios.

2. Can you provide an if statement in C example?

Sure, let's consider a simple example where we check if a number comes up to be even or odd:

#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if(num % 2 == 0) {
printf("The number is even.\n");
}
else {
printf("The number is odd.\n");
}

return 0;
}

This if statement in C example checks the condition (num % 2 == 0). If the condition is true (the number is even), it prints "The number is even." Otherwise, the else statement is executed and prints "The number is odd".

3. How does the if-else statement fit among other control statements in C?

The if-else statement is a part of conditional control statements in C, including switch statements. These control the flow of the program based on certain conditions. In addition to conditional statements, C also has looping control statements like for, while, and do-while, which control the flow of the program in a repetitive manner.

Test your C programming skills with a Free Quiz

image
right-top-arrowright-top-arrow
Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .