if, if-else and nested if statements in C – Full explanation with examples

Write a program in C to check if the number that the user has entered is even or odd

//check whether the number taken from the user is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,z;
printf("enter number\n");
scanf("%d", &i);
z=i%2;
if (z==0)
{
printf("Number is even");
}
else
{
printf("Number is odd");
}
getch();
}

Next, try writing a program to check if given year is a leap year or not. It’s the same as the above code, with just a few minute changes.

Write a program in C to check if the number that the user has entered is positive or negative

//check if number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i, a;
printf("Enter the number\n");
scanf("%d",&i);
if(i>0)
{
printf("Number is positive");
}
if(i<0)
{
printf("Number is negative");
}
if(i==0)
{
printf("Number entered is 0");
}
getch();
}

WAP (Write a program) in C to find the greatest among three numbers with if statements and without using logical operators

//largest among three numbers without using logical operators
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i, j, k, z;
printf("Enter numbers\n");
scanf("%d%d%d",&i,&j,&k);
if(i>j)
{
if(i>k)
{
printf("The first number is the greatest");
}
else
{
printf("The third number is the greatest");
}
}
if(i<j)
{
if(i<k)
{
if(j>k)
{
printf("second number is largest");
}
else
{
printf("The third number is the greatest");
}
}
else
{
printf("j is greatest");
}
}
if(i==j)
{
if(i>k)
{
printf("i and j are equal and greater than k");
}
if(i<k)
{
printf("k is the largest number");
}
if(i==k)
{
printf("All three numbers are equal");
}
}
getch();
}

Write a program in C to find the greatest among three numbers using logical operators

//find greatest of three numbers using logical operators
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,j,k;
printf("Enter the three numbers\n");
scanf("%d%d%d",&i,&j,&k);
if((i>j)&&(i>k))
{
printf("i is the largest");
}
if((j>i)&&(j>k))
{
printf("j is the greatest");
}
if((k>i)&&(k>j))
{
printf("k is greatest");
}
if((i==j)&&(i>k))
{
printf("i and j are equal and greater than k");
}
if((i==j)&&(i<k))
{
printf("k is the greatest");
}
if((i==j)&&(j==k))
{
printf("all the numbers are same");
}
getch();
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.