Learning If Statement in C

Learning If Statement in C

4 mins read76 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Sep 3, 2024 13:48 IST

The if statement in C is a control structure that evaluates a condition. If the condition is true, it runs the associated code; if false, the code is ignored. It’s fundamental in directing program flow. Let's understand more!

2023_08_MicrosoftTeams-image-2.jpg

The if statement is a fundamental control structure in the C programming language. It allows you to conditionally execute a code block based on whether a particular expression evaluates to true or false.

Explore Online C Programming Courses

What is the “if statement in C”?

The if statement in C is a type of control statement that falls under the category of selection statements. It allows the program to evaluate a condition and, based on its result, decide whether or not to execute a specific block of code. This conditional execution allows programmers to dictate the flow of their program based on specific criteria.

Flowchart :

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4.24 K
6 weeks
475
6 weeks
– / –
45 hours
4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
4 K
80 hours

Syntax:

if (condition)
{
    // statements to execute if condition is true
}

Flowchart of if statement:

2023_08_if-3.jpg
Control Statements in C | Meaning and Types
Control Statements in C | Meaning and Types
Control statements in C are used to determine the order in which the instructions within a program are executed. They are of three types: Selection, Iteration & Jump statements. Think...read more
If Else Statement in C Programming: Syntax and Examples
If Else Statement in C Programming: Syntax and Examples
Have you heard of the if-else statement in the c programming language? Let us understand this concept in detail and understand it using examples! Through this article, you will know...read more
C programming Keywords: A list and Explanation of Usage
C programming Keywords: A list and Explanation of Usage
Keywords in C refer to a set of reserved words with predefined meanings that are used to write programs in the C programming language. These keywords cannot be used as...read more

How to use the if statement in C?

Let’s understand how to use the if statement in C with the help of examples & a scenario!

Example 1:

A very basic example to understand how to implement it.


 
#include <stdio.h>
int main() {
int number = 7;
if (number > 3) {
printf("The number is greater than 3.\n");
}
return 0;
}
Copy code

Output :

The number is greater than 3.

When you run this program, it will print “The number is greater than 3.” because the condition (number > 3) is true. If the number was 2, then the printf statement inside the if block wouldn’t execute, and there would be no output.

 

Example 2:

In this program below, we aim to determine the type of a triangle based on the lengths of its three sides: a,b & c. By evaluating specific conditions:

  1. Validity Check: We first check whether the sides provided can form a valid triangle. A triangle is invalid if the sum of the lengths of any two sides is not greater than the length of the third side.
  2. Equilateral Triangle: The triangle is called equilateral if all three sides are equal in length.
  3. Isosceles Triangle: The triangle is called isosceles if two sides have equal lengths while the third side is different.
  4. Scalene Triangle: The triangle is called scalene if all three sides have distinct lengths.

 
#include <stdio.h>
int main() {
double a = 2, b = 5, c = 5;
// Check for Invalid triangle first
if (a + b <= c || a + c <= b || b + c <= a)
printf("These sides don't form a valid triangle.\n");
// Equilateral triangle
if (a == b && b == c)
printf("The triangle is equilateral.\n");
// Isosceles triangle
if ((a == b && a != c) || (a == c && a != b) || (b == c && b != a))
printf("The triangle is isosceles.\n");
// Scalene triangle
if (a != b && a != c && b != c)
printf("The triangle is scalene.\n");
return 0;
}
Copy code

Output :

The triangle is isosceles.

So, we got the output “The triangle is isosceles because” because the two sides are the same.

Example 3:

Let’s now take a scenario-based question:

You are working on an e-commerce website. The company has a special offer where:

  1. If a customer buys more than 10 items of a single product, they get a 5% discount.
  2. If a customer buys more than 50 items of a single product, they get a 10% discount.

Using only ‘if’ statements, here’s how we will code our logic in C:


 
#include <stdio.h>
int main() {
int itemsPurchased = 25; // Fixed value for this scenario
double originalPrice = 2.0; // Example price per item
double discountedPrice;
// Calculate the total price without discount
double totalPrice = itemsPurchased * originalPrice;
if(itemsPurchased > 50) {
discountedPrice = totalPrice * 0.90; // 10% discount
printf("You get a 10%% discount! Total price after discount: $%.2lf\n", discountedPrice);
}
if(itemsPurchased > 10 && itemsPurchased <= 50) {
discountedPrice = totalPrice * 0.95; // 5% discount
printf("You get a 5%% discount! Total price after discount: $%.2lf\n", discountedPrice);
}
if(itemsPurchased <= 10) {
printf("No discount. Total price: $%.2lf\n", totalPrice);
}
return 0;
}
Copy code

Output :

You get a 5% discount! Total price after discount: $47.50

As our items purchased are more than 10, using the if statement, we get our output.

The code is designed so that the discounts are mutually exclusive. A customer will get either a 10% discount or a 5% discount, but not both. If a customer buys 52 items, for instance, they’ll receive the 10% discount, not the 5% one.

Addition of Two Numbers in C
Addition of Two Numbers in C
Delve into C programming with a foundational task: adding two numbers. This guide walks you through each step, from declaring variables to getting the output, making it a perfect starting...read more

Top 10 Pattern Programs in C
Top 10 Pattern Programs in C
Have you ever wondered how intricate patterns can be created with simple loops in C? Pattern programs in C are a fascinating way to learn about nested loops and control...read more

Learning Loops in C
Learning Loops in C
In C programming, a loop is a control structure that allows a set of instructions to be executed repeatedly based on a specified condition. Loops provide an efficient way to...read more

Conclusion :

Thus, The if statement in C is a control structure used for conditional execution. It evaluates a given expression, and if the result is non-zero (true), the subsequent block of code within its scope is executed. The code block is skipped if the expression evaluates to zero (false). This allows developers to introduce decision-making capabilities in their programs, directing the execution flow based on specific conditions.

FAQs

What is an "if" statement in C?

The "if" statement in C is a control flow statement that is used to execute a block of code based on a condition. It evaluates an expression that results in a boolean value (true or false). If the expression evaluates to true (any non-zero value), the block of code inside the "if" statement is executed. If the expression is false (zero), the block of code is skipped.

How is the basic syntax of an "if" statement structured in C?

The basic syntax of an "if" statement in C is as follows:

if (condition) {
    // code to execute if condition is true
}

Can "if" statements be nested in C?

Yes, "if" statements can be nested within each other. This means you can have an "if" statement inside another "if" statement. This is useful for checking multiple conditions.

What is the difference between "if" and "else if" statements in C?

The "else if" statement is used after an "if" statement to check additional conditions if the previous "if" condition is false. It provides a way to execute different blocks of code based on multiple conditions. 

Can an "if" statement exist without curly braces in C?

Yes, an "if" statement can be used without curly braces {} if only a single statement is to be executed conditionally.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio