ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Chapter 4: C language Decision Statements

prodevelopertutorial July 5, 2018

 

In this chapter we are going to study:

  1. If condition
  2. If-else condition
  3. If-else-if condition
  4. Nested-if
  5. Switch Statement

These conditional statements help us to navigate the program flow based on certain conditions.

Above mentioned are the control statements that C language supports.

If condition:

If statement is used, when we need to execute a set of statements if the condition is true. If it becomes false, we shall start to execute the next statements.

The condition expression should be a Boolean expression and should result in only true or false.

The syntax of simple if statement:

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

Programming example to check if pin is valid or not:

#include<stdio.h>
int main()
{
  int pin;
  printf("Enter pin number \n");
  scanf("%d", &pin);


  if (pin == 8525)
  {
    printf("Pin is valid \n");
  }
printf("Thank You \n");
return 0;
}

 

if else statement

if else statement is used when there is a need to execute set of statements if the condition is true or execute another set of statements if the condition is false.

For example, if you entered the correct password, the system should allow to log in, else the system should throw an error message.

Syntax:

if(condition_expression)
{
  //execute statements if condition is true
}
else
{
  //execute statements if condition is false
}

Programming example to check if login password is valid or not:

#include<stdio.h>
int main()
{
  int password;
  printf("Enter Login password \n");
  scanf("%d", &password);


  if (password == 8525)
  {
    printf("Password is valid \n");
  }
  else
  {
    printf("Password is in-valid \n");
  }

    printf("Thank You \n");
return 0;
}

 

If-else-if statement

Consider the following example:

 

If today is Saturday I need to go to movie

else if today is Sunday I need to buy grocery

else I have to go to office as this is weekday.

In these type of situations, we need to use if..else..if statements.

Below is the syntax

if (condition1)
{
  //Statements 1
}

else if (condition2)
{
  //statements 2
}
else
{
  //statements 3
}

if the condition1 is true statements1 will be executed and shall be out of the if..else ladder. If condition1 is false, it will go and check for condition2 if true statements2 will be executed and come out of if..else ladder. If condition2 is also false, then default statements3 will be executed.

 

Programming example to give grades to a student.

#include<stdio.h>
int main()
{
  int marks;
  printf("Enter marks of a student \n");
  scanf("%d", &marks);


  if (marks >= 80)
  {
    printf("Student has got A grade \n");
  }
  else if (marks >= 80)
  {
    printf("Student has got B grade \n");
  }
  else
  {
    printf("Student has got C grade \n");
  }

    printf("Thank You \n");
return 0;
}

 

Nested if statement.

There can be an if statement inside an if block. Then it is called as nested if.

Consider the below example: While searching a store, we look if the product is available or not. If the product is available, then we shall check the price of the product and keep it the shopping cart.

Syntax:

if (condition1)
{
  //statements1 

  if(condition2)
  {
    //statements2
  }

}
else
{
  //statements3

}

From the above we can see that if condition 1 is true, all the statements under condition 1 will be executed. Then condition2 will be checked, if true all the statements under condition 2 will be executed.

Program example:

#include<stdio.h>

int main()
{
  int num_1 = 1;
  int num_2 = 2;
  
  if (num_1 == 1)
  {
    printf("Inside if condition \"num_1 ==1\" \n");
      if (num_2 == 2) // Nested if statement
      {
        printf("Inside if condition \"num_2 == 2\" \n");
      }
  }
  else
  {
    printf(" In else part");
  }
return 0;
}

Go ahead, change the values of “num_1” and “num_2” to get different output.

 

Switch statement

Instead of using if…else..if ladder, we can use the switch statement. The switch statement can be useful in situations where a particular code needs to be executed based on multiple choices like a menu.

Syntax:

switch(value)
{
  case value1:
    //statements1
  break;

  case value2:
    //statements2
  break;

  case value3:
    //statements3
  break;

  default:
    //statements4
}

Note:

  1. In switch statement, break is necessary. If you miss break statement, then the next case will be executed.
  2. Default statement will be executed when none of the cases matches.
  3. The case in the switch statement should always be a number or an alphabet. You cannot include Boolean expression there.

 

Programming Example:

#include<stdio.h>

int main()
{
	int num = 4;


	switch(num)
	{
		case 1:
			printf("The number is one\n");
			break;

		case 2:
			printf("The number is two\n");
			break;

		case 3:
			printf("The number is three\n");
			break;

		case 4:
			printf("The number is four\n");
			break;

		case 5: // we have missed the break statement. Check what happens when the number is 5
			printf("The number is five\n");

		case 6:
			printf("The number is six\n");
			break;

		default:
			printf("This is default case\n");
	}	


	return 0;
}

Output:

When the number is 4.

The number is four



When the number is 5, the output is:



The number is five

The number is six

 

Note:

  1. In the condition expression, 0 is considered as false all other values are considered as true including negative numbers.
  Example 1:

  if (0)

    printf("prodevelopertutorial.com\n");

  In this case " prodevelopertutorial.com" will not be printed

  Example 2:

  if (10)

    printf("prodevelopertutorial.com\n");

  In this case " prodevelopertutorial.com" will be printed

 

  1. As seen in the above example, if there is only one statement following if condition, there is no need to be enclosed in braces.

 

  Example 1: No need of flower brace

    if (45)

      printf("prodevelopertutorial.com\n");

 

  1. If you forget to put braces for multiple statements to be executed, only first statement is executed according to the condition other statements after that will be executed normally.
  Example 1: We forgot to include multiple statements in braces

    if (0)

                  printf("prodevelopertutorial.com\n");

                   printf("Forgot to include in brace\n");

                   printf("This statement will also get executed\n");

   

    Output:
    if(0) is false, it will not execute the next statement, but executes other statements.


      Forgot to include in brace

      This statement will also get executed

 

  1. Multiple conditional statements can be included using relational operators.
  Example 1: We need to check a number is greater than 0 and is equal to 55

   

      if ((num > 0)&&( num == 55))

 

  1. Be careful while using equal to operator “==”, if you miss one equal sign, it will be an assignment operator “=” and the result will always true.

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

One Response

  1. jack
    Log in to Reply

    Mistake in if-else if-else program
    else if (mark<=79)
    {
    printf("he got b grade ")

    August 6, 2020

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT