[go: up one dir, main page]

0% found this document useful (0 votes)
46 views23 pages

Day 3 - Decision Making and Branching

The document discusses different types of decision making statements in C programming language including if, else-if, switch statements and various nested conditional structures. It also covers jump statements like break, continue and their usage in loops. Examples are provided to explain the syntax and working of each statement.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views23 pages

Day 3 - Decision Making and Branching

The document discusses different types of decision making statements in C programming language including if, else-if, switch statements and various nested conditional structures. It also covers jump statements like break, continue and their usage in loops. Examples are provided to explain the syntax and working of each statement.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Placement Training – Day 3

(Decision making and branching)


Decision Making in C
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met. C language
handles decision-making by supporting the following statements:
1. if statement
a. simple if
b. if else statements
c. nested if statements
d. if-else-if ladder
2. switch statements
3. Jump Statements:
a. break
b. continue
c. goto
d. return

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


1. Decision making with if statement
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are,
a) Simple if statement
b) if....else statement
c) Nested if....else statement
d) else if ladder
a) Simple if statement
The general form of a simple if
statement is,
if(expression)
{
statement inside;
}
statement outside;

If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
int main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
return 0;
}
Output:
x is greater than y

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


b) if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}

If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and
statement-block2 is executed.
Example:
#include <stdio.h>
int main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
return 0;
}
Output:
y is greater than x

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


c) Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{ statement block3; }
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is
true the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
int main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
Output:
Enter 3 numbers:5
89
3
b is the greatest

d) else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example:
#include <stdio.h>
int main( )
{
int a;
printf("Enter a number...");

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
return 0;
}
Output:
Enter a number:64
Divisible by 8

* Points to Remember
➢ In if statement, a single statement can be included without enclosing it into curly braces
{ ... }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one statement
inside if condition, then we must enclose them inside curly braces.
➢ == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not comparison.
➢ Other than 0(zero), all other values are considered as true.
if(27)
printf("hello");
In above example, hello will be printed.

2. The switch statement:


When many conditions are to be checked then using nested if...else is very difficult, confusing
and cumbersome. So, C has another useful built-in decision-making statement known as

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


switch. This statement can be used as multiway decision statement. The switch statement tests
the value of a given variable or expression against a list of case values and when a match is
found, a block of statements associated with that case is executed.
Syntax:
switch (expression)
{
case value 1 :
statement block 1;
break;
case value 2:
statement block 2;
break;
:
:
default:
default block;
}
statement n;
The expression is an integer expression or characters. Value 1, value 2, ...... are constants,
constant expressions (evaluable to an integral constant) or character and are known as case
labels. Each of these values should be unique within a switch stateme nt, statement block 1,
statement block 2, ........ are statement list and may contain 0 or more statements. There is no
need to put braces between these blocks. The case labels end with a colon (:).
When the switch is executed, the value of the expression is successively compared against the
values value 1, value 2, ...... If a case is found whose value matches with the value of the
expression, then the block of statement that follows that case are executed. The break statement
at the end of each block, signals the end of a particular case and causes an exit from the switch
statement transferring the control to the statement n following the switch block. The default is
an optional case. When present, it will be executed if the value of the expression does no t match
with any of the case values and then the statement n will be executed. If not present no action
takes place if all matches fails and the control goes to statement n.
Example:
Consider an organization, in which DA (Dearness Allowance) of an employee is calculated
depending on the category of employee.
Codes are given to different categories and da is calculated as follows:
For code 1,10% of basic salary.

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


For code 2, 15% of basic salary.
For code 3, 20% of basic salary.
For code >3 da is not given.
Example:
# include<stdio.h>
int main ()
{
float basic , da , salary ;
int code ;
char name[25];
da=0.0;
printf("Enter employee name\n");
scanf("%[^\n]",name);
printf("Enter basic salary\n");
scanf("%f",&basic);
printf("Enter code of the Employee\n");
scanf("%d",&code);
switch (code)
{
case 1:
da = basic * 0.10;
break;
case 2:
da = basic * 0.15;
break;
case 3:
da = basic * 0.20; break;
default :
da = 0;
}
salary = basic + da;
printf("Employee name is\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da, salary);
return 0;
}
Output:
Enter employee name
Vino
Enter basic salary
50000
Enter code of the Employee
3
Employee name: Vino
DA: 10000.000000
Total salary: 60000.000000

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


3. Jump Statements in C
These statements are used in C for unconditional flow of control throughout the functions in a
program. They support four type of jump statements:
a) break statement:
This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stops there and control returns from the
loop immediately to the first statement after the loop.
Syntax:
break;
Basically, break statements are used in the situations when we are not sure about the actual
number of iterations for the loop or we want to terminate the loop based on some condition.

Example:
#include <stdio.h>
int main()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


return 0;
}
Output:
0 1 2 3 4 5 came outside of loop i = 5

b) continue statement:
This loop control statement is just like the break statement. The continue statement is opposite
to that of break statement, instead of terminating the loop, it forces to execute the next iteration
of the loop.
As the name suggest the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and next iteration of the loop will begin.
Syntax:
continue;

Example:
#include <stdio.h>
int main()
{
int j;
for (j=0; j<=8; j++)
{
if (j==4)
{
continue;

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


}
printf("%d ", j);
}
return 0;
}
Output:
01235678

c) goto statement:
The goto statement in C/C++ also referred to as unconditional jump statement can be used to
jump from one point to another within a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked
as a label. Here label is a user-defined identifier which indicates the target statement. The
statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can
also appear before the ‘goto label;’ statement in the above syntax.

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


Example:
#include <stdio.h>
int main()
{
int sum=0,i=1;
addition:
if(i<=5)
{
sum=sum+i;
i=i+1;
goto addition;
}
printf("%d", sum);
return 0;
}
Output:
15

d) return statement:
The return in C or C++ returns the flow of the execution to the function from where it is called.
This statement does not mandatorily need any conditional statements. As soon as the statement
is executed, the flow of the program stops immediately and return the control from where it
was called. The return statement may or may not return anything for a void function, but for a
non-void function, a return value is must be returned.
Syntax:
return[expression];
Example:
#include <stdio.h>
int Print()
{
int a,b;
scanf("%d%d",&a,&b);
return(a+b);

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


}
int main()
{
printf("%d",Print());
return 0;
}
Output:
3
6
9
Example programs
1. What is the output of the program?
#include <stdio.h>
int main()
{
if( 4 > 5 )
printf("Hurray..\n");
printf("Yes");
return 0;
}
Output:
Yes

2. What is the output of the program?


int main()
{
if( 4 < 5 )
printf("Hurray..\n");
printf("Yes");
else
printf("England")

return 0;
}
Output:
Compile Time error

3. What is the output of the program?


int main()
{
if( 10 > 9 )
printf("Singapore\n");
else if(4%2 == 0)
printf("England\n");
printf("Poland");

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


return 0;
}
Output:
Singapore
Poland

4. What is the output of the program?


int main()
{
if(-5)
{
printf("Example\n");
}
if(5)
{
printf("If statement\n");
}
printf("Outside if");
return 0;
}
Output:
Example
If statement
Outside if

5. What is the output of the program?


#include <stdio.h>
int main()
{
if(10.23)
{
printf("Inside if\n");
}
printf("Outside if");
return 0;
}
Output:
Inside if
Outside if

6. What is the output of the program?


#include <stdio.h>
int main()
{
if("a")
{
printf("Inside string controlled if\n");
}
if('a')
{

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


printf("Inside char controlled if\n");
}
printf("Outside if");
return 0;
}
Output:
Inside string controlled if
Inside char controlled if
Outside if

7. What is the output of the program?


#include <stdio.h>
int main()
{
if(TRUE)
{
printf("Inside true if\n");
}
if(FALSE)
{
printf("Inside false if\n");
}
printf("Outside if");
return 0;
}
Output:
Compile time error

8. What is the output of the program?


#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main()
{
if(TRUE)
{
printf("Inside true if\n");
}
if(FALSE)
{
printf("Inside false if\n");
}
printf("Outside if");
return 0;
}
Output:
Inside true if
Outside if

9. What is the output of the program?

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


#include <stdio.h>
int main()
{
int age=20;
if(age>=18)
printf("Eligible ");
else
printf("Not eligible ");
printf("to vote");
return 0;
}
Output:
Not eligible to vote

10. What is the output of the program?


#include <stdio.h>
int main()
{
int x;
if (x)
printf("hi");
else
printf("how are u");
return 0;
}
Output:
how are u

11. What is the output of program?


#include <stdio.h>
int main()
{
int x = 5;
if (x < 1);
printf("Hello");
return 0;
}
Output:
Hello

12. What is the output of the program?


#include<stdio.h>
int main()
{
if(-5)
{
printf("a");
printf("b");
}
else

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


{
printf("c");
printf("d");
}
return 0;
}
Output:
ab

13. What is the output of the program?


#include<stdio.h>
int main()
{
if(-5);
{
printf("a");
printf("b");
}
else
{
printf("c");
printf("d");
}
return 0;
}
Output:
Compile time error

14. What is the output of the program?


#include<stdio.h>
int main()
{
if(-5)
{
printf("a");
printf("b");
}
else;
{
printf("c");
printf("d");
}
return 0;
}
Output:
abcd

15. What is the output of the program?


#include<stdio.h>
int main()

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


{
if("true") printf("a");
else printf("b");
return 0;
}
Output:
a
CTS Question and Answers
1. Ritik wants a magic board, which displays a character for a corresponding number for
his science project. Help him to develop such an application.
For example when the digits 65,66,67,68 are entered, the alphabet ABCD are to be
displayed.
[Assume the number of inputs should be always 4 ]
Sample Input 1:
Enter the digits:
65
66
67
68
Sample Output 1:

65-A
66-B
67-C
68-D
Program:
#include <stdio.h>
int main()
{
int n1,n2,n3,n4;
scanf("%d%d%d%d",&n1,&n2,&n3,&n4);
printf("%d-%c\n",n1,n1);
printf("%d-%c\n",n2,n2);
printf("%d-%c\n",n3,n3);
printf("%d-%c\n",n4,n4);
return 0;

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


}
Output:
65
66
67
68
65-A
66-B
67-C
68-D

2. Write a program to calculate the fuel consumption of your truck. The program should
ask the user to enter the quantity of diesel to fill up the tank and the distance covered
till the tank goes dry. Calculate the fuel consumption and display it in the format (liters
per 100 kilometers).
Convert the same result to the U.S. style of miles per gallon and display the result. If
the quantity or distance is zero or negative display” is an Invalid Input”.
[Note: The US approach of fuel consumption calculation (distance / f uel) is the inverse
of the European approach (fuel / distance). Also note that 1 kilometer is 0.6214 miles,
and 1 liter is 0.2642 gallons.]
The result should be with two decimal places.
Sample Input 1:
Enter the no of liters to fill the tank
20
Enter the distance covered
150
Sample Output 1:
(Liters/100KM)
13.33
(Miles/gallons)
17.64
Program:
#include <stdio.h>
int main()

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


{
int quantity,distance;
float gallons,miles,c1,c2;
scanf("%d%d",&quantity,&distance);
if(quantity>=0 && distance>=0)
{
c1=((float)quantity/(float)distance)*100;
gallons=0.2642*(float)quantity;
miles=0.6214*(float)distance;
c2=miles/gallons;
printf("%0.2f\n",c1);
printf("%0.2f",c2);
}
else
printf("Invalid input");
return 0;
}
Output:
20
150
13.33
17.64

3. Vohra went to a movie with his friends in a Wave theatre and during break time he
bought pizzas, puffs and cool drinks. Consider the following prices:
Rs.100/pizza
Rs.20/puffs
Rs.10/cooldrink
Generate a bill for What Vohra has bought.
Sample Input 1:
Enter the no of pizzas bought:10
Enter the no of puffs bought:12
Enter the no of cool drinks bought:5
Sample Output 1:

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


Bill Details
No of pizzas:10
No of puffs:12
No of cooldrinks:5
Total price=1290
Program:
#include <stdio.h>
int main()
{
int pizza,puff,cd,total,n1,n2,n3;
scanf("%d%d%d",&n1,&n2,&n3);
pizza=n1*100;
puff=n2*20;
cd=n3*10;
total=pizza+puff+cd;
printf("%d",total);
return 0;
}
Output:
10
12
5
1290
4. HICET wants to recognize the department which has succeeded in getting the
maximum number of placements for this academic year. The departments that have
participated in the recruitment drive are CSE, ECE, MECH. Help the college find the
department getting maximum placements. Check for all the possible output given in the
sample snapshot
Note : If any input is negative, the output should be “Input is Invalid”. If all department
has equal number of placements, the output should be “None of the department has got
the highest placement”.
Sample Input 1:
Enter the no of students placed in CSE:90
Enter the no of students placed in ECE:45

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


Enter the no of students placed in MECH:70
Sample Output 1:
Highest placement
CSE
Program:
#include <stdio.h>
int main()
{
int cse,ece,mech;
scanf("%d%d%d",&cse,&ece,&mech);
if(cse==ece && ece==mech)
{
printf("None of the department has got the highest placement");
}
else if(cse<0 || ece<0 || mech<0)
{
printf("Invalid input");
}
else if(cse>ece && cse>mech)
{
printf("CSE");
}
else if(ece>mech)
printf("ECE");
else
printf("MECH");
return 0;
}
Output:
90
45
70
CSE

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology


5. Rhea Pandey’s teacher has asked her to prepare well for the lesson on seasons. When
her teacher tells a month, she needs to say the season corresponding to that month.
Write a program to solve the above task.
Spring – March to May,
Summer – June to August,
Autumn – September to November and,
Winter – December to February.
Month should be in the range 1 to 12. If not the output should be “Invalid month”.
Sample Input 1:
Enter the month:11
Sample Output 1:
Season: Autumn
Program:
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
if(n>=3 && n<=5)
printf("Spring");
else if(n>=6 && n<=8)
printf("Summer");
else if(n>=9 && n<=11)
printf("Autumn");
else if(n==12 && n>=1 && n<=2)
printf("Winter");
return 0;
}
Output:
6
Summer

Ramya Devi M AP CSE | Hindusthan College of Engineering and Technology

You might also like