Simple ‘if’ Statement

Estudies4you

Simple ‘if’ Statement

Example 1:
While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses.

#include<stdio.h>           //#include is the instruction to the compiler to include the header file stdio.h in which the standard input/output functions are defined
int main(void)    //Any C program is written inside as main function.
{
int qty, dis=0;     // ‘qty’ and ‘dis’ integer variables are declared and the value of ‘dis’ is assigned as zero
float rate, tot;    // ‘rate’ and ‘tot’ are defined as float.
printf(“Enter quantity and rete:”);           //Text is displayed asking the user to enter the quantity and rate.
scanf(“%d%f”, &qty,&rate);        // The values of quantity and rate are scanned. If ‘qty’ is greater than 1000. ‘dis’ is 10. Then, the total expenses is calculated.
if (qty>1000)
dis=10;
tot=(qty*rate)-(qty*rate*dis/100);
printf(“\nTotal expenses = Rs.%f”, tot);
return 0;
}
OUTPUT:
Enter quantity and rate:
1200
15.50
Total expenses = Rs. 16740.00000

Example 2:
Sample C program using ‘if’ clause
#include<stdio.h>
int main(void)
{
int a;
if(3+2%5);           // In the first “if” statement, the expression evaluates to 5 and since 5 is a non-zero, it is considered to be TRUE. Hence the printf() gets executed.
printf(“This works”);      
if(a=10)                                //In the second “if”, 10 gets assigned to ‘a’ so the if is now reduced to if(a) or if(10) since 10 is a non-zero, it is TRUE. Hence again printf() goes to work.
printf(“Even this works”);
if(-5)      //in the third “if”, -5 is a non-zero number, hence TRUE. So again printf() goes to work. In place of -5 even if a float like 3.14 were used it would be considered to be TRUE.
printf(“Surprisingly even this also works”);
return 0;
}
OUTPUT:
This works
Even this works
Surprisingly even this works 

Example 3:
Sample C program using, “if” clause
#include<stdio.h>
int main(void)
{
int bonus, cy, yoj, yr_of_ser;      // Current year and Year of Joiing
printf(“Enter current year and Year of Joining”);
scanf(“%d%d”,&cy,&yoj);
yr_of_ser=cy-yoj;
if(yr_of_ser>3)
{
bonus=2500;
printf(“Bonus=Rs. %d”,bonus);
}
return 0;
}
OUTPUT:
Enter current year and Year of Joining
2013 2009
Bonus = Rs.2500
To Top