You are on page 1of 27

C Programming Decision Making

In programming the order of execution of instructions may have to be


changed depending on certain conditions. This involves a kind of decision making
to see whether a particular condition has occurred or not and then direct the
computer to execute certain instructions accordingly.

Following is the general form of a typical decision making structure found in most
of the programming languages:

C programming language provides following types of decision making statements. Click the following
links to check their detail.

Statement Description
if statement An if statement consists of a boolean expression
followed by one or more statements.

if...else statement An if statement can be followed by an optional else


statement, which executes when the boolean
expression is false.

nested if statements You can use one if or else if statement inside


another if or else if statement(s).

switch statement A switch statement allows a variable to be tested for


equality against a list of values.

nested switch statements You can use one switch statement inside


another switch statement(s).

C - if statement

Syntax:
The syntax of an if statement in C programming language is:

if(condition)
{
//execute your code
}

If the boolean expression evaluates to true, then the block of code inside
the if statement will be executed. If boolean expression evaluates tofalse, then
the first set of code after the end of the if statement(after the closing curly brace)
will be executed.

C programming language assumes any non-zero and non-null values


astrue and if it is either zero or null, then it is assumed as false value.

Flow Diagram:

#include <stdio.h>
void main ()
{
int a = 10;
if( a < 20 )
{
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
}

When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10

C - if...else statement

Meaning of If Statement :
 It Checks whether the given Expression is Boolean or not!!
 If Expression is True Then it executes the statement
otherwise jumps to next_instruction

Syntax
if(expression)
{
Statement(s)-1;
}
Else
{
Statement(s)-2;
}
Next_statements;

If the boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed. C programming language
assumes any non-zero and non-null values as true, and if it is either zero or null,
then it is assumed as false value.
OR
C program to check whether a given number is even
or odd

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter any number:”);
scanf(“%d”,&n);
if(n%2==0)
{
printf(“The number is even“);
}
else
{
printf(“The number is odd”);
}
getch();
}

Example 2:

#include <stdio.h>
Void main ()
{
/* local variable definition */
int a = 100;

/* check the boolean condition */


if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);

return 0;
}

When the above code is compiled and executed, it produces the following result:

a is not less than 20;


value of a is : 100
Program: Write a program to input two numbers and find out the largest

among two in c.  

Solution: By using less than "<" and greater than, ">" sign we can check, Which

number is largest among two numbers. 

---------------------------------------------------------------------------

#include<stdio.h>

#include<conio.h>

Void main()

int a, b;

clrscr();

printf("Enter The Numbers:");scanf(“%d%d”, &a, &b);

if (a>b)               // Checking a is greater if yes than print the if block code

otherwise print else block code.


 {

 printf(" a is greater"); 

 }

else

 {

 printf("b is greater"); 

 }
getch();

Program: Write a program to enter a character & check whether it is a vowel

or consonant.  

Solution: By checking vowels in if statement, we can say entered character is a

vowel or not. If not, then it will print the message "number is consonant". 

---------------------------------------------------------------------------

#include<stdio.h>

#include<conio.h>

Void main()

char ch;

clrscr();

printf("Enter The Character:");scanf(“%c”, &ch);

if (ch=='a'|| ch=='e' ||ch=='i' ||ch=='o' ||ch=='u' ||ch=='A' ||ch=='E' ||ch=='I' ||ch=='O'

||ch=='U') )               

 {

 printf(" Enter Character Is Vowel"); 

 }

else

 {

 printf("Enter Character Is Consonant"); 

 }
getch();

Program: Write a program to enter a number and check whether that

number is divisible by 7 or not.

Solution: For Checking Number is divisible by 7 or not, I am using the module

division concept, Here if any number is divisible by 7 then it will give the

remainder 0, and in module division it store the remainder value.

Example Of Simple Division:

If we divide 40 by 2 then the answer is 20. Because 40 is divided by 2 in 20 times.

Example Of Modules Division:

If we module divides 40 by 2 then the answer is 0. Because if we divide 40 by 2

than remained would be 0. In module division it stores the remained resulting

value.

---------------------------------------------------------------------

#include<stdio.h>

#include<conio.h>

Void main()

int a;

clrscr();

printf("Enter The Number:");


scanf(“%d”, &a);

a = a%7;                 // Using Module Divison Checking and storing the result into

same variable a.

if (a == 0)

 {

 printf("Number is divisible by 7"); 

 }

else

 {

 printf("Number is not divisible by 7 - Enter Another Number"); 

 }

getch();

C - Nested if statements
It is always legal in C programming to nest if-else statements, which means
you can use one if or else if statement inside another if or else if statement(s).

Syntax:
The syntax for a nested if statement is as follows:

if(condition_1)
{
 if(condition_2)
 {
   block statement_1;
 }
 else
 {
   block statement_2;
 }
}
else
{
  block statement_3;
}
block statement_4;

Example of calculate greatest number using nested if

 
#include<stdio.h>
#include<conio.h>
void main()
{
     int x,y,z;
     clrscr();
     printf("\n Enter the value of x,y,z:");
     scanf("%d%d%d",&x,&y,&z);

if(x>y)
{
         if(x>z)
{
           printf("\n X = %d is Greatest",x);
}
         else
{
          printf("\n Z = %d is Greatest",z);
}
}
else
{
         if(y>z)
{
             printf("\n Y = %d is Greatest",y);
}
         else
{
           printf("\n Z = %d is Greatest",z);
}
getch();
}

Enter the value of x,y,z: 23 43 45

Z = 45 is Greatest

Else if Ladder statement


The else...if Ladder syntax is as follows:
if(condition_1)
  block statement_1;
else if(condition_2)
  block statement_2;
else if(condition_n)
  block statement_n;
else
  default statement;

Program: Write a program to enter the temperature and


print the following message according to the given
temperature by using if else ladder statement.
1. T<=0                        "Its very very cold".
2. 0 < T < 0                  "Its cold".
3. 10 < T < =20            "Its cool out".
4.  20 < T < =30           "Its warm".
5.  T>30                        "Its hot".
#inlcude<stdio.h>
#include<conio.h>
void main()
{
  float temp;
  clrscr();
  printf("Enter The Temperature");
  scanf("%f",&T);
  if(T<=0)
     {
      printf("Its very very cold");
   }
  else if(T>0 && T<=10)
           {
            printf("Its cold");
           }
   else if(T>10 && T < =20)
         {
                   printf("Its cool out");
         }
   else if(T<=30 && T>20)
       {
                  printf("Its warm");
       }
   else
             { 
                  printf("Its hot");
             }
getch();
     }

Example 2:

Let consider a problem to display the grade obtained by a student based on the
marks. The criteria to find the grade based on marks as follows:
    Marks        Grade
    0 to 34        F
    35 to 44      E
    45 to 59      D
    60 to 69      C
    70 to 79      B
    80 to 89      A
    90 to 100    A+

Void main()
{
  int marks;
  clrscr();

  printf(“Enter the student’s obtained marks here:\n”);


  scanf(“%d”,&marks);

  if(marks<=34)
     printf(“Grade F”);

  else if(marks<=45)
     printf(“Grade E”);

else if(marks<=59)
     printf(“Grade D”);

else if(marks<=69)
     printf(“Grade C”);

else if(marks<=79)
     printf(“Grade B”);

else if(marks<=89)
     printf(“Grade A”);

else 
     printf(“Grade A+”);

getch();
}
Example 3:

#include<stdio.h>

#include<string.h>

void main()

int n;

printf(" Enter 1 to 4 to select random color");

scanf("%d",&n);

if(n==1)

printf("You selected Red color");

else if(n==2)

printf("You selected Green color");

else if(n==3)

printf("You selected yellow color");

}
else if(n==4)

printf("You selected Blue color");

else

printf("No color selected");

getch ();

Example 4:

Void main()
{
int units, custnum;
float charges;

printf("Enter CUSTOMER NO. and UNITS consumed\n");


scanf("%d %d", &custnum, &units);
if (units <= 200)
charges = 0.5 * units;
elseif (units <= 400)
charges = 100 + 0.65 * (units - 200); elseif (units <= 600)
charges = 230 + 0.8 * (units - 400);
else
charges = 390 + (units - 600);

printf("\n\nCustomer No: %d: Charges = %.2f\n",


custnum, charges);
}
Output

Enter CUSTOMER NO. and UNITS consumed 101 150


Customer No:101 Charges = 75.00

Enter CUSTOMER NO. and UNITS consumed 202 225


Customer No:202 Charges = 116.25

Enter CUSTOMER NO. and UNITS consumed 303 375


Customer No:303 Charges = 213.75

Enter CUSTOMER NO. and UNITS consumed 404 520


Customer No:404 Charges = 326.00

Enter CUSTOMER NO. and UNITS consumed 505 625


Customer No:505 Charges = 415.00

Advantages:
In computer programming, situations involving series of decisions one after the
other, each decision or condition may involve expression of various data types
such as float, integer, char and double. In these situations the if-else-if ladder is
used.

Disadvantages:
 The nested ifs are hard to understand and modify.
 As the depth of nesting increases, the readability of the program decreases.

 In situations involving series of decisions one after the other, each decision
or condition may involve expressions which result in integer value. In these
situations the usage of if-else-if ladder is not recommended. Instead of this
statement, we go for switch statement.
Switch case statement in C:
 Switch case statements are used to execute only specific case statements
based on the switch expression.
 Below is the syntax for switch case statement.

switch (expression)
{
case label1:   statements;
break;
case label2:   statements;
break;
default:    statements;
break;
}

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or


enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.

 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

 The constant-expression for a case must be the same data type as the


variable in the switch, and it must be a constant or a literal.

 When the variable being switched on is equal to a case, the statements


following that case will execute until a breakstatement is reached.

 When a break statement is reached, the switch terminates, and the flow of


control jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at


the end of the switch. The default case can be used for performing a task
when none of the cases is true. Nobreak is needed in the default case.

Example program for switch..case statement in C:


#include <stdio.h>
void main ()
{
int value = 3;
switch(value)
{
case 1:
printf(“Value is 1 \n” );
break;
case 2:
printf(“Value is 2 \n” );
break;
case 3:
printf(“Value is 3 \n” );
break;
case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
}

Code for Program that reads marks of a students and computes and displays
grade in C Programming
#include <stdio.h>
#include<conio.h>

void main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
}

Example 3:

Void main()

int p,q,result;
char op;
clrscr();
printf(“Enter an expression here:\n”);
scanf(“%d %c %d”,&p,&op,&q);
switch(op)
{
 case ‘+’:
 result = p + q;
break;
case ‘-’:
 result = p - q;
break;
case ‘*’:
 result = p * q;
break;
case ‘/’:
 result = p / q;
break;
default:
printf(“Invalid expression.\n”);
}
printf(“The result of the expression %d %c %d = %d”,p,op,q,result);
getch();
}

Break statement in C:
 Break statement is used to terminate the while loops, switch case loops and
for loops from the subsequent execution.
 Syntax: break;

Example program for break statement in C:


#include <stdio.h>
void main()
{
int i;

for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nComing out of for loop when i = 5″);
break;
}
printf(“%d “,i);
}
}

Output:
0 1 2 3 4
Coming out of for loop when i = 5

Continue statement in C:
 Continue statement is used to continue the next iteration of for loop, while
loop and do-while loops.  So, the remaining statements are skipped within
the loop for that particular iteration.
 Syntax : continue;

Example program for continue statement in C:


#include <stdio.h>
Void main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf(“\nSkipping %d from display using ” \
“continue statement \n”,i);
continue;
}
printf(“%d “,i);
}
}

Output:
0 1 2 3 4

Skipping 5 from display using continue statement


Skipping 6 from display using continue statement
7 8 9

Goto statement in C:
 goto statements is used to transfer the normal flow of a program to the
specified label in the program.
 Below is the syntax for goto statement in C.

{
         …….
         go to label;
         …….
         …….
         LABEL:
         statements;
}

Example program for goto statement in C:


#include <stdio.h>
Void main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(“\nWe are using goto statement when i = 5″);
goto HAI;
}
printf(“%d “,i);
}
HAI : printf(“\nNow, we are inside label name \”hai\” \n”);
}

 Output:
0 1 2 3 4
We are using goto statement when i = 5
Now, we are inside label name “hai”

You might also like