CodesandTutorials
Home   Programming   Hardware   Networking
 
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.  

C Categories

Else If Statement

« Previous Point - If Else Statement Next Point - For Loop Statement »

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


  • //Find whether input year is leap year or not
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • 	int year;
  • 	clrscr();
  • 	printf("Enter the year:");
  • 	scanf("%d",&year);
  • 	if(year%400==0)
  • 	{
  • 		printf("It is a leap year");
  • 	}
  • 	else if(year%100==0)
  • 	{
  • 		printf("It is not a leap year");
  • 	}
  • 	else if(year%4==0)
  • 	{
  • 		printf("It is a leap year");
  • 	}
  • 	else
  • 	{
  • 		printf("It is not a leap year");
  • 	}
  • 	getch();
  • }

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.

« Previous Point - If Else Statement Next Point - For Loop Statement »

Tip Box

At the last of else if statement, you can use else statement which is optional.


Advertisement

Rate Website
   

 


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