CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.  
You are here - Home > Programming > C > Basics

Nested If Else Statement


Description

Nested if else statment is same like if else statement, where new block of if else statement is defined in existing if or else block statment.

Used when user want to check more than one conditions at a time.

Syntax

if(condition is true)
{
     if(condition is true)
     {
           statement;
     }
     else
     {
          statement;
     }
}
else
{
     statement;
}

Source code


  • //Using nested if else statement
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • char username;
  • int password;
  • clrscr();
  • printf("Username:");
  • scanf("%c",&username);
  • printf("Password:");
  • scanf("%d",&password);
  • if(username=='a')
  • {
  • if(password==12345)
  • {
  • printf("Login successful");
  • }
  • else
  • {
  • printf("Password is incorrect, Try again.");
  • }
  • }
  • else
  • {
  • printf("Username is incorrect, Try again.");
  • }
  • getch();
  • }

Program working steps

  • First four lines of the program are common containing comments, preprocessor statements and void main function().
  • From 6th to 12th line there is declaration of variables, clearing of the console screen, printing and scaning input from the user.
  • First if condition will be true, if the user has typed 'a' as a username then the program control moves to second if condition and checks for the password, if it true it will print 'login successful' else it will execute block statement 'Password is Incorrect, Try again.'. If the first if condition is false then it will execute last else block statement printing 'Username is Incorrect, Try again.'.
  • In this above example we have use username as single character to use multiple character username we need to use string data type which will be learned further.
  • getch() function takes the single input character from the keyboard and that character is not display on the console screen.

Tip Box

Remember

You should write else keyword below the proper if condition becuase the else may match with the wrong if resulting in the wroing answer.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved