Nested if block:
- Defining if block inside another if block.
- Nested if condition evaluates only when outer condition is valid.
#include<stdio.h>
int main()
{
if(1)
{
printf("Outer block statements \n");
if(1)
{
printf("Inner block statements \n");
}
}
return 0;
}
Nested if condition evaluates only when outer condition is valid.
#include<stdio.h>
int main()
{
if(0)
{
printf("Outer block statements \n");
if(1)
{
printf("Inner block statements \n");
}
}
return 0;
}
Question:
- Read one number
- Check the number is divisible by 3 or 5 or both or none.
Example:
- 9 : Divisible by 3
- 15 : Divisible by 3 and 5
- 10 : Divisible by 5
- 13 : Not divisible by 3 or 5
#include<stdio.h>
int main()
{
int n;
printf("Enter a number : ");
scanf("%d", &n);
if(n%3==0)
{
if(n%5==0)
printf("%d is divisible by 3 and 5 \n", n);
else
printf("%d is divisible by only 3\n", n);
}
else
{
if(n%5==0)
printf("%d is divisible by only 5\n", n);
else
printf("%d is not divisible by 3 or 5\n", n);
}
return 0;
}
Flow charts of Nested – if:
Flow-1:
Flow-2:
Biggest of 3 numbers using nested – if:
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter 3 numbers : ");
scanf("%d%d%d", &a, &b, &c);
if(a>b)
{
if(a>c)
printf("a is big \n");
else
printf("c is big \n");
}
else
{
if(b>c)
printf("b is big \n");
else
printf("c is big \n");
}
return 0;
}
Leap year program:
- 4 divisible – leap year (16, 44, 1660….)
- 400 divisible – leap year (800, 2000….)
- 100 divisible – not leap year (100, 200, 300, 500…)
#include<stdio.h>
int main()
{
int year;
printf("Enter Year name:");
scanf("year: %d",&year);
if(year%400==0 || (year%4==0 && year%100!=0))
{
printf("%d is leap year \n", year);
}
else
{
printf("%d is not a leap year \n",year);
}
return 0;
}
Note: try the above code using Nested-if