Pages

Wednesday, 9 May 2018

C if Statement – Part 2


C if Statement – Part 2


In the last tutorial we have learnt about the basic use of decision control instruction using if statement. Today we will extend that tutorial with some advanced examples.
A bit more about conditions
As I told you earlier that if statement is used with some conditions. Truly speaking it can also be used with some expression.
So the general form of if statement is

if(expression)
{
Statement 1
Statement 2
. . . . .
. . . . .
}

What is expression?
This expression can be any valid expression including relational and arithmetic expression. Some common examples are given below.

if(3+2)
printf(“This will print everytime”);

if(6/2+4)
printf(“This will print everytime”);

if(0)
printf(“This will never execute”);

Conclusion
Truly speaking in C language any non-zero number is considered to be TRUE whereas zero is considered as FALSE.

During the running of decision control instruction, a compiler checks the expression either it evaluates 0 or not. If the result is 0 then it will never execute the body of if statement. But if the expression evaluate to any non-zero number then it will execute the body of if statement.

In the first two examples, expression under if evaluates a non-zero value. So it will print the message.

In the last example, I have written 0. So the printf() statement is not executed.

Note: Usage of expression is very important in C language. While writing big programs it is used very frequently. So I recommend you to understand the basic logic behind it correctly. If you have any problems then you can also post your queries in comments.

Now lets take one slightly complicated program to understand all the basics associated with if statement.

Sample Program
Make one program which will display the total amount after deducting the discount of 10%, if the total is more than 2000.


/*Program to show discount*/
#include <stdio.h>

void main()
{
 float amnt,famnt,dis;
 printf("Enter the total amountn");
 scanf("%f",&amnt);
 famnt=amnt;

 if (amnt>2000)
 {
  printf("You are eligible for discountn");
  dis=0.1*amnt;
  famnt=famnt-dis;
 }
 printf("final amount is %f",famnt);
}
/*Program to show discount*/
#include <stdio.h>

void main()
{
 float amnt,famnt,dis;
 printf("Enter the total amountn");
 scanf("%f",&amnt);
 famnt=amnt;

 if (amnt>2000)
 {
  printf("You are eligible for discountn");
  dis=0.1*amnt;
  famnt=famnt-dis;
 }
 printf("final amount is %f",famnt);
}