Wednesday, 8 January 2014

C Programming Tutorial V - Decision making statements, if, if-else, nested if, multiple if

Statements
A statement is a syntactic construction that performs an action when a program is executed.
A statement is a complete instruction given to a program.
Types of Statement
Expression Statement
The simplest kind of statement is an expression statement which is followed by a semicolon.
e.g. function call statements, variable declaration statements, assignment statement etc.
Compound Statement
A compound statement consists of several individual statements enclosed within a pair of braces {}. Unlike expression statement, compound statement does not end with semicolons.
Control Statement
C program is a set of statements which are normally executed sequentially in the order in which they appear. But control statement is one which can change the order of execution of statements based on a certain condition or repeat a group of statements until a specified condition is met.
Different control statements
Category
Relevant Keywords
 Selection or conditional
 if, switch
 Iteration
 for, while, do-while
 Jump
 break, goto, return, continue
 Label
 case, default
Decision Making and Branching
While being a programmer it is very essential to take decisions.
if, switch and conditional operators are called decision making statements.
If statement
It is most powerful decision making statement and is used to control the flow of execution of statements. It evaluates expression and returns result either true or false.
It has mainly three types single if, multiple if and nested if. Let us first discuss about single if and if-else.
The working of if is very interesting and easily understands. If statement first checks condition and evaluate result either true or false. True statement is written immediately after if and false part is in else statement. See the following diagram it will check condition and execute either true or false part.

Within a single if you only have to execute true part therefore if-else is mostly useful in programming language because it is not only execute true part but also take a decision to which part will get execute deepening upon given criteria. See the following syntax.
if(expression)
{
   true block statements;
}
else
{
   false block statements;
}
Let us take an example. Assume that you have two integers and want to print greater value. It will perform by using if-else.
//Program to print greater value
#include<stdio.h>
#include<conio.h>
void main()
{
  int num1,num2;   //declare two variables
  clrscr();
  printf("\nEnter two numbers");
  scanf("%d%d",&num1,&num2);
  if(num1 > num2)     //if checks condition and take decision which part will get execute
       printf("\nNumber1 is greater");
  else
      printf("\nNumber2 is greater ");
  getch();
 }
o/p
Enter two numbers
12
23
Number2 is greater
By studding above example you should write another program to check given value is positive or negative. For this program you simply input one value and if it is greater than zero then only it is +ve otherwise –ve.
Let us take example of even/odd number.
//Program to check whether given value is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
  int num;      //here we should have only one variable
  clrscr();
  printf("\nEnter number");
  scanf("%d",&num);
  if(num%2 == 0)     //it checks whether remainder is zero
       printf("\nNumber is even");
  else
      printf("\nNumber is odd");
  getch();
 }
o/p:
Enter number
 6                   //after modulus (%) we will get zero
Number is even
OR
Enter number
 7                   //after modulus (%) we will not get zero
Number is odd
Multiple (nested/ladder) if-else
A chain of ifs in which the statement associated with each else is again if.
if(expression1)
        statement1;
else if(expression2)
        statement2;
else if(expression3)
        statment3;
|
|
|
else if(expression n)
        Statement;;
else
         Statement;
In case of single if, we have checked two possibilities and it is only useful to when you have to find either true or false result.
Nested or multiple if is use when you have more than two possible results. In above program of greater number we had two possibilities either number1 is greater or number2. Think of what happened when we have more than two numbers. In this case no doubt about we will have more than two possible results. Let us assume that we have age of three persons and simply have to find eldest person. Let us create a program.
//Program to compare age of three persons.
#include<stdio.h>
#include<conio.h>
void main()
{
  int age1,age2,age3;      //age of 1st, 2nd and 3rd person respectively
  clrscr();
  printf("\nEnter age of three persons respectively");
  scanf("%d%d%d",&age1,&age2,&age3);
  if(age1>age2 && age1>age3)     //it checks whether 1st person is eldest
       printf("\n1st person is eldest");
  else
 if(age2>age1 && age2>age3)     //it checks whether 2nd person is eldest
       printf("\n2nd person is eldest");
else
 if(age3>age1 && age3>age2)     //it checks whether 3rd person is eldest
       printf("\n3rd person is eldest");
else
if(age1==age2 && age2==age3)     //it checks whether 3rd person is eldest
      printf("\nAll are same”);
  getch();
 }
o/p:
Enter number
 6                  
12
3
2nd person is eldest. //and vice versa
Let us take another example in which we will use single and nested if.
It is a simple program to create marksheet of student.
//prog for marksheet of student by standatrd rule
#include<stdio.h>
#include<conio.h>
void main()
{
 int rlno,s1,s2,s3,tot;   //variables for rollno, marks of three subjects and total marks
 float per;
 char name[20],status; //variables status is accepts only single character e.g.  for Pass ‘P’
 clrscr();
 printf("\nEnter roll no of student");
 scanf("%d",&rlno);
 printf("\nEnter name of student");
 scanf("%s",&name);
 printf("\nEnter marks of 3 subjects");
 scanf("%d%d%d",&s1,&s2,&s3);
 tot = s1+s2+s3;
 per = tot/3;
 printf("\nTotal = %d",tot);
 printf("\nPercentage = %.2f",per);
//if marks of all subjects are more than or equal to 35 then only status will be pass else fail.
 if(s1>=35 && s2>=35 && s3>=35)    
      status = 'P';
 else
      status='F';
 printf("\nStatus = %c",status);
 if(status == 'P') //if status is pass then only calculate grade
{
 if(per >= 75)      //if per is more than or equal to 75
  printf("Grade = A\n"); //\n is allowed at the beginning or at the end of statement
 else
 if(per>=60 && per<75)
  printf("Grade = B\n");
 else
 if(per>=50 && per<60)
  printf("Grade = C\n");
else
 if(per>=35 && per<50)
  printf("Grade = D\n");
}
else
 printf("Grade = Fail\n");
 
getch();
}
o/p:
Enter roll no of student
1
Enter name of student
John
Enter marks of 3 subjects
78
82
66
Total = 226
Percentage =75.33
Status = P
Grade = A
From above program you should be modify program of pay slip and item bill by adding appropriate criteria for bonus and discount respectively.

Multiple If
Whenever more than one if statement uses within a program then it is called multiple if. Each if execute as a separate block and useful to execute result.
Let us consider example of program to sort three numbers.
//prog to sort three numbers in ascending order
#include<stdio.h>
#include<conio.h>
void main()
{
  int a,b,c,temp;  //temp variable is for swapping values
  clrscr();
  printf("\nEnter any three numbers");
  scanf("%d%d%d",&a,&b,&c);
  printf("\nBefore sorting a = %d\t b = %d\t c = %d",a,b,c);
   if(a > b)         //1st value compare to 2nd value
   {
     temp = a;
     a = b;
     b = temp;
   }
   if(a > c)         //1st value compare to 3rd value
   {
     temp = a;
     a = c;
     c = temp;
   }
   if(b > c)       //2nd value compare to 3rd value
   {
     temp = b;
     b = c;
     c = temp;
   }
   printf("\nAfter sorting a = %d\t b = %d\t c = %d",a,b,c);
   getch();
}

In above program we have only three values for sorting therefore as per general logic we have to compare values and swap them hence we finally got values in ascending order. You can be apply logic for descending order.

No comments:

Post a Comment