Skip to main content

C Programming #4 (Decision Control Instruction)

Decision!
While writing program when its is executed it execute in the sequence which it is written but in serious programming sequence is according to some condition so here is the need to make decision .Which is implemented in C using :

  • The if statement
  • The if-else statement
  • The conditional operator
The if statement:
The general form of if statement looks like this:
if(this condition is true)
execute this statement;
Example:
#include<stdio.h>
int main()
{
int num;
printf("Enter a number less than 10");
scanf("%d",&num);
if(num<10)
printf("What an obedient servant you are!\n");
return 0;
}
The if-else statement:
In this form when the if statement turn to be false then the else statement is executed
Example:
/*Calculation of gross salary*/
#include<stdio.h>
int main()
{
float bs,gs,da,hra;
printf("Enter basic salary");
scanf("%f",&bs);
if(bs<1500)
{
hra=bs*10/100;
da=bs*90/100;
}
else
{
hra=500;
da=bs*98/100;
}
gs=bs+hra+da;
printf("gross salary=Rs%f\n",gs);
return 0;
}
At the start I have used /* this is used to write comments if you want to tell someone what program is this then you can take help of comments and it can also be used in between program.
Nested if-else:
/*A quick demo of nested if-else*/
#include<stdio.h>
int main()
{
int i;
printf("Enter either 1 or 2");
scanf("%d",&i);
if(i==1)
printf("You would go to heaven !\n");
else
{
if(i==2)
printf("Hello was created with you in mind\n");
else
printf("How about mother earth !\n");
}
return 0;
}

Note:You can compile all of these program and try new things if you have any question you are free to ask in comments.

Comments