INTRODUCTION
Conditional statements in C are used to evaluate something based on the condition. The flow of the program may change based on the condition.
It allows you to make logical comparison between a value and what you expect. It has two results. The 1st result is if your comparison is TRUE, the 2nd if your comparison is FALSE.
1. if condition : for one condition
syntax :
if(condition)
{
statement 1
statement 2...
}
Example
code :
#include<stdio.h>
int num;
int main()
{
printf("enter the number \n");
scanf("%d",&num);
if (num>0)
{
printf("positive");
}
}
2.if-else condition : for two conditions
if condition specify a block of code to be executed, if a specified condition is true.
else condition specify a block of code to be executed, if the same condition id false.
if we don't want to write else condition we can write if condition but in 2nd if condition we have to write opposite condition.
Example
code : with if - else
#include<stdio.h>
int num;
int a;
int b;
int c;
int main()
{
printf("enter the first angle \n");
scanf("%d",&a);
printf("enter the second angle \n");
scanf("%d", &b);
printf("enter the thirt angle \n");
scanf("%d", &c);
num=a+b+c;
printf("%d \n",num);
if (num==180)
{
printf("triangle\n");
}
else
{
printf("not triangle");
}
}
code : without else
#include<stdio.h>
int num;
int main()
{
printf("enter the number \n");
scanf("%d",&num);
if (num>0)
{
printf("positive \n");
}
if(num<0)
{
printf("negative");
}
}
* if-else ladder :for more than 2 conditions
syntax
#include<stdio.h>
int main()
{
if(condition 1)
{
}
if(condition 2)
{
}
if(condition 3)
{
}
else
{
}
* nested if condition : condition inside condition
syntax
#include<stdio.h>
int main()
{
if(condition1)
{
if (condition 2)
{
if(condition 3)
{
}
else
{
}
}
else
{
}
}
else
{
}
}
3.else if condition :
else if condition specify a new condition to test, if the 1st condition is false.
Example
#include<stdio.h>
char n;
float age;
float w;
float h;
int main()
{
printf("nationality \n");
scanf("%c", &n);
printf("age \n");
scanf("%f", &age);
printf("weight \n");
scanf("%f", &w);
printf("height \n");
scanf("%f",&h);
if(n=='I')
{
printf("selected \n");
}
else if((age>'18' && age<'25') && (w>'60' && w<75) && (h>'5.9' && h<'6.3'))
{
printf(" selected \n");
}
else
{
printf("not selected \n");
}
}
No comments:
Post a Comment