if else statement in c

If-Else Statement in C: A Practical Guide

The if–else statement is a control flow construct that is used in the C programming language and other programming languages to execute different blocks of code based on the evaluation of a Boolean expression.

if-else statement provides a way to make decisions within a program and can be used to handle different scenarios or to perform different actions based on user input.

Example:

Imagine you are building a simple automated teller machine (ATM) for a bank.

One of the features of the ATM is to allows customers to withdraw cash from their accounts.

You need to write a program in C to handle this functionality.

To do this, you can use an if – else statement to check whether the customer has sufficient funds in their account to make the withdrawal.

This is just one example of how an if–else statement can be used in a real-life situation.

In this tutorial, we will cover the basics of the if–else statement, including its syntax and some practical examples of how it can be used in C programs.

By the end of this tutorial, you should have a good understanding of how to use if – else statements to control the flow of your C programs.

Required Knowledge

Ready to dive in? Let’s go!

The if statement in C – Syntax, and Example

The if statement in C is used to execute a block of code conditionally, based on the value of a Boolean expression.

The general syntax of an if statement is as follows:

if (condition){
     // code to be executed if condition is true;
}

Here are the steps involved in executing an if statement in C:

  1. The condition in the parentheses is evaluated.
  2. If the condition is TRUE, the code inside the curly braces is executed.
  3. If the condition is FALSE, the code inside the curly braces is skipped and execution continues with the next statement after the if block.

See how an if statement works in C with this illustration:

Checking if a users amount is less than or greater than 100

if else statement in c

Code:

#include <stdio.h>
#program to check if balance is less than 100

int main(void) {
    int balance = 40;

    if (balance < 100) {
        printf("Balance is less than 100\n");
    }
    return 0;
}

In this example, the condition balance < 100 is TRUE, so the message “Balance is less than 100” will be printed on the console.

Output
Balance is less than 100

if else statement in C – Syntax, and Example

The else statement is used in conjunction with an if statement to specify a block of code to be executed if the condition in the if statement is FALSE.

The general syntax for using an if else statement is as follows:

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

Here are the steps involved in executing an if – else statement in C:

If the condition is evaluated to be TRUE,

  1. Statements inside the body of the if are executed
  2. Statements inside the body of else are skipped from execution

If the condition is evaluated to be FALSE,

  1. Statements inside the body of else are executed
  2. Statements inside the body of if are skipped from execution.

Example of if – else statement in C with illustration:

if else statement in c

Code:

#include <stdio.h>

int main() {
    int balance;  // Declare a variable balance

    // Prompt the user to enter a value for balance
    printf("Enter balance: ");
    scanf("%d", &balance);  // Read the value entered by the user and store it in balance
    // Check if balance is greater than or equal to  100
    if (balance >= 0) {
        // If balance is greater, print "Successful Withdrawal"
        printf("Successful Withdrawal\n");
    } 
    else {
        // If balance is less, print "Insufficient funds"
        printf("Insufficient funds\n");
    }
    return 0;
}

This code will

  1. prompt the user to enter their balance,
  2. read the value entered by the user, and
  3. then check if the value is greater than or less than 100
// Balance is greater than 100
Output
Enter balance: 200
Successful Withdrawal
// Balance is less than 100
Output
Enter balance: 50
Insufficient funds

else if statement in C

The else if statement is a type of control flow statement that allows you to specify multiple conditions and execute different code blocks depending on which condition is true.

It is used in conjunction with the if statement

The code reads the blocks one after the other until it reaches a TRUE condition and executes the corresponding code block.

Here is an example of an if else statement ladder in C:

#include <stdio.h>
int main(void){
    int x = 10;

    if (x > 5) {
       printf("x is greater than 5\n");
    } 
    else if (x == 5) {
       printf("x is equal to 5\n");
    } 
    else {
       printf("x is less than 5\n");
    }
    return 0;
}

In this example,

  1. the value of x is 10, so the first condition x > 5 is TRUE and the code block printf(“x is greater than 5\n”) is executed.
  2. If the value of x was 5, the second condition x == 5 WOULD HAVE BEEN TRUE and the code block printf(“ x is equal to 5\n”) would have been executed.
  3. If the value of x was less than 5, NEITHER OF THE FIRST TWO CONDITIONS would have been TRUE, and the code block in the else statement would have been executed.

Nested if Statements in C

We can use nested-if statements to test multiple conditions.

Syntax of nested if statement:

if (condition1) {
   // code to be executed if condition1 is true
   if (condition2) {
      // code to be executed if condition2 is true
   } else {
      // code to be executed if condition2 is false
   }
} 
else {
   // code to be executed if condition1 is false
}

In this syntax above,

  1. The code inside the first if statement will only be executed if condition1 is TRUE. If condition1 is FALSE, the code inside the else block will be executed.
  2. Inside the first if block, there is another if statement with a corresponding else block. This nested if statement tests condition2.

If condition2 is TRUE, the code inside the second if block will be executed. If condition2 is FALSE, the code inside the else block will be executed.

Nested if statements allow you to test multiple conditions and execute different code blocks based on the results of these tests.

Practical Example of if–else statements in C and Explanations.

Here is an example of using if – else statement in C to solve a real-life problem:

Suppose you are writing a program to help a library manage its collection of books. The library wants to classify its books as either “juvenile” or “adult” based on their target audience.

The classification should be based on the age range of the target audience.

Books with a target audience of ages 0 -17 should be classified as “juvenile” and books with a target audience of ages 18 and above should be classified as “adult”.

Take a crack at the problem yourself by giving the project a try – then compare your solution to the one we provide.

Great job trying out the project on your own! Keep up the good work.

Here is how you could use if – else statements in C to solve this problem:

#include <stdio.h>
#include <string.h>

int main(void) {
   int target_age;  // the age range of the target audience for a book
   char classification[10];  // the classification of the book (either "juvenile" or "adult")
   // prompt the user to enter the age range of the target audience for a book
   printf("Enter the age range of the target audience for a book (0-12 for juvenile, 13 and above for adult): ");
   scanf("%d", &target_age);
   // classify the book as either "juvenile" or "adult" based on the age range of the target audience
   if (target_age >= 0 && target_age <= 12) {
      strcpy(classification, "juvenile");
   } 
else {
      strcpy(classification, "adult");
   }
   // print the classification of the book
   printf("The classification of the book is: %s\n", classification);
   return 0;
}

In the example above, we prompt the user to enter the age range of the target audience for a book

The if statement checks whether the age range is between 0 and 17 (inclusive).

If it is, the book is classified as “juvenile”.

If the age range is 18 and above, the book is classified as “adult”

Finally, We print the classification of the book.

Note:

In the C programming language, the printf is a function from the stdio.h library that is used to print a formatted string to the standard output device (usually the screen).

scanf is a function that reads input from the user and stores it in a variable. The %d format specifier tells scanf to read an integer from the input.

The second argument to scanf which is &target_age, is the address of the target_age variable, where the input will be stored.

The & operator is necessary here because scanf expects a pointer to the location where the input should be stored.

By using the & operator to get the address of targer_age, you are passing a pointer to target_age to scanf.

This allows scanf to store the input in the target_age variable.

strcpy is a function in the c programming language that copies a string from one location to another. It is defined in the string.h header file.

The syntax for the strcpy function is as follows:

char *strcpy(char *dest, const char *src);

Here, dest is a pointer to the destination array where the string is to be copied, and src is a pointer to the source of the string to be copied. The function returns a pointer to the destination string (dest).

The strcpy function copies the string pointed to by src (including the null character) to the array pointed to by dest.

Conclusion

if-else statements are an essential part of programming in C and many other languages.

They allow you to control the flow of your program based on certain conditions, and they are the fundamental building blocks of more complex programs.

Whether you are new to programming or an experienced developer, it is important to understand how if-else statements work and how to use them effectively.

With a little practice and some creativity, you can use if-else statements to solve a wide range of problems and build powerful, dynamic programs.

So, the next time you sit down to write some code in C, don’t be afraid to use if-else statements to add some intelligence and decision-making capabilities to your program.

You will be amazed at what you can accomplish with a little bit of logic and a lot of creativity.

If you enjoyed reading this post, we would love to hear your thoughts in the comments section below. Your feedback and insights are always welcome.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *