For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
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.
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
}
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.
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:
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.
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:
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:
This flowchart helps understand the flow of the program and how the control shifts between the if and else blocks based on the condition.
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.
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;
}
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.
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.
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.
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.
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.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.