You are on page 1of 14

TM's

Lecture Notes in C Programming (LNCP)


Unit 2 Part 2
Decision making & branching
Ver. 1.5
TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

Table of Contents
Decision making & branching statements in C 3
1. if statement 3
1.1 Simple if statement 3
1.2 if..else statement 4
1.3 Nested if..else statement 5
1.4 else if ladder 7
2. switch statement 8
4. Conditional operator( ?: ) 12
5. goto statement (SLE) 13

2 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

​Decision making & branching statements in C


❑ if statement
❑ switch statement
❑ Conditional operator
❑ goto statement (SLE)

Also called as decision-making statements or control statements

​1. if statement
❑ if is a keyword in C
❑ Gen. format
if(test expression)
❑ Two possible outcomes for test condition(True or False)

​1.1 Simple if statement


General format:

if(condition)
{
statements;
}
// Rest of code

Program: Finding absolute value of a number.


int main()
{
int num = 0;
printf("Enter a number:");
scanf("%d",&num);
if(num<0)
{
// if block
Printf("I'm here\n");
num *=-1;
}
printf("Absolute value is %d",num);
return 0;
}
Output:
Enter a number:-17
I'm here
Absolute value is 17

Enter a number:10
Absolute value is 10

3 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

In the example above, num<0 gives 1 or 0(True or False) based on value of num. if block is executed only if
num<0 is 1(True)

​1.2 if..else statement


General format:

if(condition)
{
statements set 1
}
else
{
statements set 2
}
//Rest of the code

❑ if..else statement
// Sample program: if else statement
#include<stdio.h>
int main( )
{
int experience = 0,income =0;
printf("Enter experience and income");
scanf("%d %d",&experience,&income);
if(experince>5 && income <30000)
{
//if block
printf("Employee is Underpaid\n");
}
else
{
// else block
printf("Employee is NOT Underpaid\n");
}
return 0;
}
Output:
Enter experience and income:7 40000
Employee is NOT Underpaid

Enter experience and income:6 15000


Employee is Underpaid
In the example above, expression experince>5 && income <30000 finally evaluates to 1 or 0(True or False)
based on values of experience and income. if block is executed only if it is evaluated to 1(True).
Otherwise(expression evaluates to 0(False) ), the else block is executed.

4 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

​1.3 Nested if..else statement


General format:
if(condition) // level 1
{

if(condition2) // level 2
{
// do something
}
else // else of level 2
{
// do something else
} // else level end
}
else
{ //else of level 1
if(condition3)
{
// do something
}
else
{
// do something else
}
}
❑ Nested if..else statement (prg311)
// Nested if-else statement
#include<stdio.h>

int main()
{
int exp = 0,income =0;
printf("Enter exp and income:");
scanf("%d %d",&exp,&income);

if(exp >= 5)
{
if(income <30000)
{
printf("1.Employee is Underpaid\n");
}
else
{
printf("2.Employee NOT Underpaid\n");
}

5 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

else
{
if(income <10000)
{

printf("3.Employee is Underpaid\n");
}

else
{
printf("4.Employee NOT Underpaid\n");
}

}
return 0;
}
Output:
Enter exp and income:6 25000
1.Employee is Underpaid

Enter exp and income:6 35000


2.Employee NOT Underpaid

Enter exp and income:4 8000


3.Employee is Underpaid

Enter exp and income:3 11000


4.Employee NOT Underpaid

Flow chart of ‘Nested if…else’

6 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

​1.4 else if ladder


General Format:

if(condition 1)
statement-1;
else if(condition 2)
statement-2;
else if(condition 3)
statement-3;
.
.
.
else if(condition-n)
statement-n
else
default-statement;

Flowchart of else if ladder

Example program for else..if ladder

7 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

// Grade of student
#include<stdio.h>
int main()
{
int mark;
printf("Enter mark(<= 100):");
scanf("%d", &mark);

if(mark>=90)
{
printf("S Grade.");
printf("Congrats..!!");
} // // Flower bracket must since more than 1 statement within if part
else if(mark>=75)
{ printf("A Grade"); } // Flower bracket optional since only 1 statement
else if (mark>=60)
printf("B Grade");
else
printf("Grade is low"); // Default case.

// Out of else if ladder block


printf("\nGrading Done");
return 0;
}

Output:
Enter mark (<= 100):91
S Grade. Congrats..!!
Grading Done
General guidelines for if

Enter mark (<= 100):84


A Grade
Grading Done

Enter mark (<= 100):74


B Grade
Grading Done

Enter mark (<= 100):59


Grade is low
Grading Done

❑ Give matching indentation for if and its matching else.


❑ else part is not mandatory for an if statement.
❑ else part cannot exist without a matching if part.
❑ Multiple statements within an if or else scope must be enclosed with { }.

​2. switch statement


❑ Multi-way decision making statement in C

8 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

❑ Remember if statement is a two-way decision statement inC

Flowchart of switch-case

General Syntax of switch-case:


switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
………
………
default :
default block;
break;
}

The switch expression should be an integral type variable (int or char) or an expression that evaluates to and
integer value.

switch statement (Sample pgms.)


❑ Program: Integer for switch expression

// switch statement using integer type selection


#include<stdio.h>
int main()
{
int choice;
printf("Enter your choice:\n1: Add 2:subtract 3: Multiply
4:Divide ::");
scanf("%d", &choice);

9 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

switch(choice)
{
case 1:
printf("Addition selected");
break;
case 2:
printf("Subtraction selected");
break;
case 3:
printf("Multiplication selected");
break;
case 4:
printf("Division selected");
break;
default:
printf("Invalid choice");
} // end switch
return 0;
} // end main

Output:
Enter your choice:
1: Add 2:subtract 3: Multiply 4:Divide ::1
Addition selected

Enter your choice:


1: Add 2:subtract 3: Multiply 4:Divide ::4
Division selected

Enter your choice:


1: Add 2:subtract 3: Multiply 4:Divide ::7
Invalid choice

❑ Program: character for switch expression


// switch statement using character type selection variable
#include<stdio.h>
int main()
{
char choice;
printf("Enter your choice:\n+: Add \n-:subtract \n*: Multiply
\n /:Divide ::");
scanf("%c", &choice);

switch(choice)
{
case '+':

printf("Addition selected\n");
break;

10 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

case '-':
{ // Optional { }
printf("Subtraction selected\n");
break;
}
case '*':
printf("Multiplication selected\n");
break;
case '/':
printf("Division selected");
break;
default:
printf("Invalid choice");
}
return 0;
}
Output:
Enter your choice:
+: Add
-:subtract
*: Multiply
/:Divide ::*
Multiplication selected

❑ Program : Simple Calculator


//Simple calculator
# include <stdio.h>
int main()
{
char choice;
int num1,num2;
printf("Enter operator either + or - or * or / : ");
scanf("%c",&choice);
printf("Enter two operands: ");
scanf("%d%d",&num1,&num2);

switch(choice) {
case '+':
printf("%d + %d = %d",num1, num2, num1+num2);
break;
case '-':
printf("%d - %d = %d",num1, num2, num1-num2);
break;
case '*':
printf("%d * %d = %d",num1, num2, num1*num2);
break;
case '/':
if(num2 == 0)
{

11 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

printf("Divide by Zero error.\n"); return -1;


}
printf("%d / %d = %d",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown
*/
printf("Error! operator is not correct");
break;
}
return 0;
}
Output:
Enter operator either + or - or * or / : *
Enter two operands: 5 4
5 * 4 = 20

​4. Conditional operator( ?: )


❑ General format
conditional expression ? Expression 1: Expression 1
E.g: a = x>40?x+50:x-10;

Salary of a sales person is defined by below function (x = no. of products sold)

Consider this code using else if ladder to code this function:


if(x == 40)
salary =300;
else if(x<40)
salary = 4*x+100;
else
salary = 4.5*x+100;

❑ The above code using conditional operator:


salary = (x==40)?300:((x<40)?(4*x+100):(4.5*x+300));

❑ Here is the complete program.


#include<stdio.h>
int main()

12 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

{
int x,salary;
printf("Enter no. of products sold:");
scanf("%d",&x);
salary = (x==40)?300:(x<40)?(4*x+100):(4.5*x+300);
printf("Salary: %d",salary);
return 0;
}
Output:
Enter no. of products sold:40
Salary: 300

Enter no. of products sold:30


Salary: 220

Enter no. of products sold:50


Salary: 525

​5. goto statement (SLE)


❑ Used for unconditional branching.
❑ Transfers execution unconditionally to a pre-defined(labeled) statement.
❑ Labeling is used to mark the destination
❑ Not a recommended mechanism for branching: Increase program complexity and reduce readability.
❑ Use only if unavoidable.
❑ goto works only within same function.(No jump across functions)
❑ goto statement (General format)
goto mylabel;
………..
………..
………..
mylabel :
statements;

Example program for goto statement :


#include<stdio.h>
void main()
{
printf("India\n");
printf("USA\n");
printf("JAPAN\n");

goto label1; // Unconditional jump

printf("China\n");
printf("England\n");
printf("Germany\n");
label1: // Destination
printf("Italy\n");
}

13 (For non-commercial educational use only)


TM’s C Programming Lecture Notes ver.1.5 Decision making & branching

Output:
India
USA
JAPAN
Italy

14 (For non-commercial educational use only)

You might also like