Code Scrappers

If-else Statements

The if statement executes a single statement, or a group of statements, when the expression following if evaluates to true. By using else we can execute other statements if the expression evaluates to false.

Syntax of if-else statement:

if (condition )
{

	Statement....;

		…………..

		Statement...;

}

else

{

 Statement....;

	…………..

	Statement....;

}

For Example :


if (i > j)

{

		z = i;

}
else

{

		z = j;

}

NOTE 1: The group of statements after the if is called an ‘if block’. Similarly, the statements after the else form the ‘else block’

C Programs using if-else statements

1. Write a C program to check if the number is even or odd

#include<stdio.h>

void main()

{

int num;

printf("Enter a number(integer) :\n");

scanf("%d",&num);

if ( num%2 == 0 )

{

	printf("It is an even number\n");

}
else

{

	 printf("It is an odd number\n");

}


}

Output: Enter a number(integer) :
3
It is an odd number

Output: Enter a number(integer) :
4
It is an even number

2. Write a program to check whether a given year is leap year or not


#include <stdio.h>

void main()

{

int y;

printf("Enter the year :\n");

scanf("%d", &y);

if ( (y%4 == 0) && ( y%100 != 0) || ( y%400 == 0 ))

{

		printf("The year %d is a leap year\n", y);
}

else

{


		printf("%d is not a leap year\n", y);

}



}

Output: Enter the year :
1996
The year 1996 is a leap year

Output: Enter the year :
2015
2015 is not a leap year

<< Back Next >>