0% found this document useful (0 votes)
17 views70 pages

Day 3 - Material - 20-09-2022

Uploaded by

arpitshirbhate25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views70 pages

Day 3 - Material - 20-09-2022

Uploaded by

arpitshirbhate25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

CSE1012 - Problem Solving and Programming

Session - 3

Dr. L.PAVITHRA
Assistant Professor (sr)
SCOPE
VIT University

1
ALGORITHM & FLOWCHART
For Control Structure

2
Control Structure
• Control flow is the order that instructions are executed in a
program.
• A control statement is a statement that determines control
flow of a set of instructions.
• There are four fundamental forms of control that
programming languages provide,
• Sequential control statement
• Selection control statement
• Iterative control statement
• Jump control statement

3
4
Sequential control
statement

5
Sequential control statement
• Sequential execution is when statements are executed one after
another in order. You don't need to do anything more for this to
happen.
• Example: Addition of 2 numbers

6
Selection control
statement

7
Selection control statement
• Selection used for decisions, branching - choosing between 2 or more
alternative paths.
• Tells the computer that IF a condition is true, THEN execute a set of
instructions, or ELSE execute another set of instructions
• ELSE part is optional, as there is not always a set of instructions if the
conditions are false.
Algorithm:
IF <condition(s)> THEN
<TRUE instruction(s)>
ELSE
<FALSE instruction(s) 8
• In Selection Control Statement are
• If statement
• If -else statement
• If-elif ladder
• Nested statement

9
If statement
Example
# If the number is positive, we print an
appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.“)

10
If -else statement
Example
# Program checks if the number is positive or
negative And displays an appropriate
message
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
11
If –elif ladder • '''In this program, we check if
the number is positive or
negative or zero and display
an appropriate message'''

num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
12
Algorithm for Conditional Problems

PROBLEM: To decide if a fire alarm should be sounded

ALGORITHM:

1 IF fire is detected condition

2 THEN sound fire alarm action

13
Algorithm for Conditional Problems

PROBLEM: To decide whether or not to go to school

ALGORITHM:

1 IF it is a weekday AND it is not a holiday

2 THEN go to school

3 ELSE stay at home

14
Algorithm for Conditional Problems
• PROBLEM: Pass/ Fail and Average
Write an algorithm to find the average of 3 marks of a student. Also check
whether the student has passed or failed. For a student to be declared
pass, average marks should not be less than 65.
• ALGORITHM:
Step 1 : Read Marks1, Marks2, Marks3
Step 2 : Total = Marks1 + Marks2 + Marks3
Step 3 : Average = Total / 3
Step 4 : Set Output = “Student Passed”
Step 5 : if Average < 65 then Set Output = “Student Failed“
Step 6 : Display Output
15
Flow Chart - Selection

16
Algorithm for Conditional Problems
PROBLEM: Leap Year or Not
ALGORITHM:

Step 1 : Read YEAR

Step 2 : IF ({YEAR%4==0 AND YEAR%100!=0)OR (YEAR%400==0))


Display "Year is a leap year"
ELSE
Display “Year is not a leap year"
ENDIF
17
Conditional Pay Calculation
• Assume your are calculating pay at an hourly rate, and overtime pay(over
40 hours) at 1.5 times the hourly rate.
• IF the hours are greater than 40, THEN the pay is calculated for
overtime, or ELSE the pay is calculated in the usual way.

18
Example Decision Structure

19
NESTED IF/THEN/ELSE INSTRUCTIONS
• Multiple decisions.
• Instructions are sets of instruction in which each level of a
decision is embedded in a level before it.

20
NESTED IF/THEN/ELSE INSTRUCTIONS

21
Practice problems

22
Practice problem-1:
Draw flowchart & algorithm to illustrate the following.
A grocery store calculates discounts allowed to customers on the
following basis: Find out the amount to be paid by the customer
after discount.
Order quantity Normal
discount
>0 and <100 5%
>=100 and <200 7%
>=200 and <500 9%
>= 500 10%

23
ALGORITHM
1. Start
2. Input bill amount that >0 and Discount rate
3. Purchase goods at Vishnu limited
4. Get bill amount
5. Check
i. If bill amount is >0 and <100 then Discount rate=0.05
ii. else if bill amount is >=100 and <200 then Discount rate=0.07
iii. else if bill amount is >=200 and <500 then Discount rate=0.09
iv. else if bill amount >= 500 then Discount rate=0.1
v. else discount rate=0
6. Calculate Discount amount=Discount rate*Bill amount
7. Calculate Amount To Be Paid=Bill amount-Discount amount
8. Output Amount To Be Paid. 24
25
Practice problem-2
A farmer has field which is B meters wide and L meters long. The field
yields C cubic meters of grain per hectare ( 1 Hectare = 10,000 square
meters ). The farmer has a number of rectangular tins, L1 meters long,
B1 meters wide and H1 meters high to store the grain.
The program should output,
(i) number of completely filled tins,
(ii) volume of grain in the partially filled tin. Write algorithm &
flowchart.

26
ALGORITHM
1. Start
2. Input land size(B meters wide and L meters long), Field Yield (C cubic meters
of grain per hectare), Rectangular tin size (L1 meters long, B1 meters wide
and H1 meters high) :
i. Get B, L, C , L1, B1 & H1 that must be >0
3. Calculate Land area as (B*L) sq.meter.
4. Calculate Field yield as C*land area/10000
5. Calculate volume of each tin as (L1*B1*H1)
6. Calculate Number of completely filled ins as Field yield/Volume of each tin
7. Calculate volume of grain in the partially filled tin as Field yield % Volume of
each tin.
8. Stop
27
28
Assignment Task -1

29
Exercises
Do Algorithm & FLOWCHART for the following
1. A(x1,y1) and B(x2,y2) are the two points of a graph. you are asked to find the distance
between them. Draw flow chart & algorithm.
2. Check whether the student passed in mathematics based on his mark
3. Determine the climate based on current temperature
4. Given an integer N, Find whether it is possible to write in terms of 2 power or not.
5. Aravind decided to visit his friend. It turned out that the Aravind house is located at point 0
and his friend's house is located at point x(x > 0) of the coordinate line. In one step the
Aravind can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum
number of steps he need to make in order to get to his friend's house
Sample Input 0 : 5
Sample Output 0 : 1
Sample Input 1 : 10
Sample Output 1 : 2 30
Iterative control statement

31
Iterative control statement
• A loop statement allows us to execute a statement or
group of statements multiple times.

• In python we have
• For loop statement
• While loop statement

32
For loop statement
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 1, 8]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)

33
While loop statement
# Program to add natural numbers up to sum = 1+2+3+...+n
# Size of input
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
34
Algorithm for Iterative Problems
This type of loop keeps on carrying out a command or commands UNTIL a given
condition is satisfied, the condition is given with the UNTIL command, for
example:-
PROBLEM: To wash a car
ALGORITHM:
1 REPEAT
2 wash with warm soapy water
3 UNTIL the whole car is clean
35
Is it Repetitive Structures ?

• Write a program to find the average of marks scored by a

student in three subjects

No,Why?

36
ALGORITHM
Step 1 : Read Number Of Students

Step 2 : Read Marks1, Marks2, Marks3

Step 3 : Total = Marks1 + Marks2 + Marks3

Step 4 : Average = Total / 3

Step 5 : Set Output = “Student Passed”

Step 6 : If (Average < 65) then Set Output = “Student Failed"

Step 7 : Display Output

37
Iterational Algorithms – Repetitive Structures
• Write a program to find the average of marks scored by him
in three subjects for ‘N’ students. And then test whether he
passed or failed. For a student to pass, average should not be
less than 65.

38
ALGORITHM
Step 1 : Read Number Of Students

Step 2 : Let Counter = 1

Step 3 : Read Marks1, Marks2, Marks3

Step 4 : Total = Marks1 + Marks2 + Marks3

Step 5 : Average = Total / 3

Step 6 : Set Output = “Student Passed”

Step 7 : If (Average < 65) then Set Output = “Student Failed"

Step 8 : Display Output

Step 9 : Set Counter = Counter + 1


39
Step 10 : If (Counter <= NumberOfStudents ) then goto step 3
Flow Chart Iterational

40
Bigger Problems
• If you are asked to find a solution to a major problem, it can sometimes be very
difficult to deal with the complete problem all at the same time.
• For example building a car is a major problem and no-one knows how to make
every single part of a car.
• A number of different people are involved in building a car, each responsible for
their own bit of the car’s manufacture.
• The problem of making the car is thus broken down into smaller manageable tasks.
• Each task can then be further broken down until we are left with a number of step-
by-step sets of instructions in a limited number of steps.
• The instructions for each step are exact and precise. 41
Top Down Design
• Top Down Design uses the same method to break a programming problem down
into manageable steps.
• First of all we break the problem down into smaller steps and then produce a Top
Down Design for each step.
• In this way sub-problems are produced which can be refined into manageable
steps.

42
Top Down Design for Real Life Problem
PROBLEM: To repair a puncture on a bike wheel.
ALGORITHM:
1. remove the tyre
2. repair the puncture
3. replace the tyre

43
Step 1: Refinement:
1. Remove the tyre
1.1 turn bike upside down
1.2 lever off one side of the tyre
1.3 remove the tube from inside the tyre

44
Step 2: Refinement:
2. Repair the puncture Refinement:
2.1 find the position of the hole in the tube
2.2 clean the area around the hole
2.3 apply glue and patch

45
Step 3: Refinement:
3. Replace the tyre Refinement:
3.1 push tube back inside tyre
3.2 replace tyre back onto wheel
3.3 blow up tyre
3.4 turn bike correct way up

46
Still more Refinement:
Sometimes refinements may be required to some of the sub-problems.
for example if we cannot find the hole in the tube, the following refinement can be
made to 2.1:-

47
Still more Refinement:
Step 2.1: Refinement
2.1 Find the position of the hole in the tube
2.1.1 WHILE hole cannot be found
2.1.2 Dip tube in water
2.1.3 END WHILE

48
Practice problems

49
Practice problem-3
Statement: Print all natural numbers till N
Algorithm
1. Start
2. Get value of N that must be >=1
3. Num is initialized to 1
4. Check if Num is Greater than N then Go to Step 8
5. Print Num
6. Increment Num by 1
7. Go to step 4
8. Stop
50
51
Practice problem-4
Statement: Print all positive even numbers upto N
Algorithm
1. Start
2. Get value of N that must be >=1
3. Num is initialized to 2
4. Check if Num is Greater than N then Go to Step 8
5. Print Num
6. Increment Num by 2
7. Go to step 4
8. Stop
52
53
Assignment Task -2

54
Exercises
• Write an algorithm and draw a flow chart to print all numbers between
1 and 1000 that are divisible by 7.
• Write an algorithm and draw a flow chart to print the SUM of numbers
from 1 to 1000
• Given an integer N, , traverse its digits ( d1,d2 ,...,dn ) and determine
how many digits evenly divide N(i.e.: count the number of times N
divided by each digit di has a remainder of 0 ). Print the number of
evenly divisible digits.

55
Practice problem-5
Statement: Sum of numbers from 1 to N
Algorithm
1. Start
2. Get value of N
3. Count is initialized to 1
4. Initialize sum to 0
5. Check if Count is Greater than N then Go to Step 9
6. Increment sum by Count sum=sum+Count
7. Increment Count by 1
8. Go to step 5
9. Output sum
10. Stop
56
57
Practice problem-6
Statement: XYZ company has 3000 employees. Divide the employees
into 3 groups based on their salary
The salaries are divided in four categories as under :
(i) Less than Rs. 20000
(ii) Rs. 20000 to Rs.100000
(iii) Above Rs.100000.
Draw a flow chart for finding the percentage of the employees in each
category

58
Algorithm
1. Start
2. Get Number of employees as Num
3. i is initialized to 1
4. Initialize Count1, Count2 and Count3 to 0
5. Check if I>Num then Go to Step 13
6. Else Get I th employee’s salary
7. Check if salary is < 20000 then increment count1 by 1 Go to step
8. Check if salary is >=20000 & <100000then increment count2 by 1 Go to step
9. Check if salary is >= 100000 then increment count3 by 1 Go to step
10. Increment I by 1
11. Go to step 5
12. Output Count1% as count1/Num)*100
13. Output Count2% as count2/Num)*100
14. Output Count3% as count3/Num)*100 59
Assignment Task -3

60
Exercises
• Write a guessing game where the user has to guess a secret number. After every
guess the program tells the user whether their number was too large or too small. At
the end the number of tries needed should be printed. It counts only as one try if
they input the same number multiple times consecutively.
• Chaitanya has “a” candles. When Chaitanya lights up a new candle, it first burns
for an hour and then it goes out. Chaitanya is smart, so he can make “b” went out
candles into a new candle. As a result, this new candle can be used like any other
new candle. Now Chaitanya wonders: for how many hours can his candles light up
the room if he acts optimally well? Help him find this number.
• Input Format
The single line contains two integers, a and b.
• Constraints
1 ≤ a ≤ 1000 2 ≤ b ≤ 1000
61
Jump control statement

62
Jump control statement
• Jump statement is used to transfer the control from one part of
program to another part.

• In Python, There are three types of Jump statements.


• Break
• Continue
• pass

63
BREAK statement
• The break statement immediately terminates a loop and control of the
program go the next body of the loop. When the break statement is
executed, the control flow of the program comes out of the loop and
starts executing the segment of code after the loop structure.

for a in "Iteration":
if a=="a":
break
print(a,end="_")
Output: I_t_e_r_

64
CONTINUE statement

• Continue statement is used to skip the remaining part of a loop and


start with next iteration. It is unlike a break statement.

for a in "Iteration":
if a=="a":
continue
print(a,end="_")

Output: I_t_e_r_t_i_o_n_

65
PASS statement
• Pass statement in Python programming is a null statement. pass
statement when executed by the interpreter it is completely ignored.
Nothing happens when pass is executed. pass is generally called as
placeholder..

for a in "Iteration":
if a=="a":
pass
print(a,end="_")

Output: I_t_e_r_a_t_i_o_n_
66
Tool demo
• Yed tool shall be used for giving demo

67
Pseudocode – Partial English and
Programming Language terms

68
Best Practices
Develop efficient computer solution to problems:
1. Use Modules
2. Use four logic structures
a. Sequential structure
• Executes instructions one after another in a sequence.
b. Decision structure
• Branches to execute one of two possible sets of instructions.
c. Loop structure
• Executes set of instruction many times.
d. Case structure
• Executes one set of instructions out of several sets.
3. Eliminate rewriting of identical process by using modules.
4. Use techniques to improve readability including four logic structure, proper naming
of variables, internal documentation and proper indentation.
69
70

You might also like