Thursday, 16 July 2015

C language- if statement

C has three major decision making instructions-the if statement, the if-else statement, and the switch statement.

In sequential control structure various steps are executed sequentially, we don't have to do anything at all . That is by default, the instructions in a program are executed sequentially. However in reality, we rarely want the instructions to be executed sequentially. Many a times we want a set of instructions to be executed in one situation and a different set of instructions in the other case.


             Hence a decision control instruction can be implemented in C using
1. The if-statement
2.The if-else statement
3.The conditional operators


//Syntax of if-statement

if(condition is true)
execute this statement;


In the () we can write anything which finally results either 1 or 0
If the result is 1 the statement immediately followed by the if-statement is executed then the control shifts to the next statement.

1.//program to allow a user into a website

#include<stdio.h>
#include<conio.h>
int main()
{
int age;
printf("hello user please enter your age\n");
scanf("%d",&age);
if(age>18)
printf("you can see the content of this website");
printf("whether you are >18 or <18 this statement gets printed");
getch();
}


output:
hello user please enter your age
20
you can see the content of this website
whether you are >18 or <18 this statement gets printed


2.//program to print even numbers
#include<stdio.h>
#include<conio.h>
int main()
{
int i, n;
printf("enter the final number");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
if(i%2==0)
printf("%d\n",i);
}
getch();
}

output:
enter the final number
10
0
2
4
6
8
10


3.//calculation of total amount
#include<stdio.h>
#include<conio.h>
int main()
{
int qty,dis=0;
float rate,tot;
printf("enter quantity and rate\n");
scanf("%d%f",&qty,&rate);
if(qty>1000)
dis=10;
tot=(qty*rate)-(qty*rate*dis/100);
printf("total expenses=rs %f\n",tot);
return 0;
getch();
}

output:
enter quantity and rate
1500
10
total expenses =rs 1350.0000


4.//logical condition
#include<stdio.h>
#include<conio.h>
int main()
{
int a=300,b,c;
if(a>=400)
b=300;
c=200;
printf("%d\n%d\n",b,c);
return 0;
getch();
}

output:
0
200


5.//logical statement
#include<stdio.h>
#include<conio.h>
int main()
{
int x=10,y=20;
if(x==y)
printf("%d\n%d\n",x,y);
return 0;
getch();

}

output:
no output as the condition did not satisfy

No comments:

Post a Comment