Nested If Else Statement - C Language Tutorial


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

  1. if(condition is true)
  2. {
  3.      if(condition is true)
  4.      {
  5.            statement;
  6.      }
  7.      else
  8.      {
  9.           statement;
  10.      }
  11. }
  12. else
  13. {
  14.      statement;
  15. }

Source code

  1. //Using nested if else statement
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. char username;
  7. int password;
  8. clrscr();
  9. printf("Username:");
  10. scanf("%c",&username);
  11. printf("Password:");
  12. scanf("%d",&password);
  13. if(username=='a')
  14. {
  15. if(password==12345)
  16. {
  17. printf("Login successful");
  18. }
  19. else
  20. {
  21. printf("Password is incorrect, Try again.");
  22. }
  23. }
  24. else
  25. {
  26. printf("Username is incorrect, Try again.");
  27. }
  28. getch();
  29. }

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.

Thank you for sharing Your Knowledge with others who need It.-Team LetML

Post a Comment

Copyright © LetML. Blogger Templates Designed by OddThemes