Thursday, 16 July 2015

C language- if-else statement

The if statement will execute a single statement, or a group of statements when the expression following if evaluates to be true.It does nothing when the expression evaluates to false.
     By using if-else statement we can execute one group of statements if the expression evaluates to be true and another group of statements if the expression evaluates to false.


syntax:

if(condition)
do this;
else
do this;


if(condition)
{
execute 1;
execute 2;
}
else
{
execute 3;
execute 4;
}




1.//program to check if the given number is even or odd
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
printf("enter a number\n");
scanf("%d",&x);
if(x%2==0)
printf("the given number is even");
else
printf("the number is odd");
return 0;
getch();

}

output:
enter a number
20
the given number is even


2.//Is 3=3.0?
#include<stdio.h>
#include<conio.h>
int main()
{
int x=3;
float y=3.0;
if(x==y)
{
printf("x and y are equal\n");
printf("3 and 3.0 are equal\n");
}
else
{
printf("x and y are not equal");
}
return 0;
getch();
}

output:
x and y are equal
3 and 3.0 are equal


3.//find error
#include<stdio.h>
#include<conio.h>
int main()
{
int x=2;
if(x==2&&x!=0);
printf("hello\n");
else
printf("bye");
return 0;
getch();
}

output: error
'else' without a previous 'if'


4.//interesting

#include<conio.h>
int main()
{
int x,y,z;
printf("enter three numbers\n");
scanf("%d%d%d",&x,&y,&z);
if(x&&y&&z)  
printf("you entered all non zero numbers\n");
else
printf("you entered a zero");
return 0;
getch();
}

output:
enter three numbers
1
5
8
you entered all non zero numbers
//if(&&5&&8)  is equal to  if(1&&1&&1)







No comments:

Post a Comment