Else If Statement - C Language Tutorial

Description

As if else statement are too complicated for humans to write when they are nested more deeply. To reduce this complication of statements else if clause can be used.

Syntax :

if(test expression1 is true)
     statement1;
else if(test expression2 is true)
    statement2;
else if(test expression3 is true)
    statement3;

It is combination of if else statement, At the start if test expression1 of if statement evalutes false, then the program control moves downward till any of the elseif statement evalutes true. After evaluting true any of the elseif statement it executes the statements and exits the clause.

Source code

  1. //Find whether input year is leap year or not
  2. #include <stdio.h>
  3. #include <conio.h>
  4. void main()
  5. {
  6. int year;
  7. clrscr();
  8. printf("Enter the year:");
  9. scanf("%d",&year);
  10. if(year%400==0)
  11. {
  12. printf("It is a leap year");
  13. }
  14. else if(year%100==0)
  15. {
  16. printf("It is not a leap year");
  17. }
  18. else if(year%4==0)
  19. {
  20. printf("It is a leap year");
  21. }
  22. else
  23. {
  24. printf("It is not a leap year");
  25. }
  26. getch();
  27. }

Program working steps

Leap year means a year with a extra day added at the end of february month i.e. 29th feb, so total days of the year becomes 366 days.
First 9 lines of the program are easy to understand.
To find the leap year, we need to check three conditions. First condition is checked using if statement and other two conditions are checked using elseif statement. If any of the three statement evalutes false then the last else statement will be executed.
Without getch() function the console screen will flash up and exit, to avoid this we use it as it takes single input character from the keyboard and doesn't displays it.



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

Post a Comment

Copyright © LetML. Blogger Templates Designed by OddThemes