KEMBAR78
UCEST105 Module 2 Short Notes | PDF | Algorithms | Control Flow
0% found this document useful (0 votes)
22 views33 pages

UCEST105 Module 2 Short Notes

The document explains algorithms as sequences of well-defined steps to solve problems, highlighting their key characteristics such as clarity and finiteness. It introduces pseudocode as a flexible representation of algorithms that resembles programming language, emphasizing its readability and lack of strict syntax. Additionally, it covers main constructs of pseudocode, including sequencing, selection, and repetition, along with examples for better understanding.

Uploaded by

savysaju
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)
22 views33 pages

UCEST105 Module 2 Short Notes

The document explains algorithms as sequences of well-defined steps to solve problems, highlighting their key characteristics such as clarity and finiteness. It introduces pseudocode as a flexible representation of algorithms that resembles programming language, emphasizing its readability and lack of strict syntax. Additionally, it covers main constructs of pseudocode, including sequencing, selection, and repetition, along with examples for better understanding.

Uploaded by

savysaju
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/ 33

ALGORITHM AND PSEUDOCODE REPRESENTATION:- Meaning And Definition of Pseudocode,

Reasons for using pseudocode , Main Constructs of Pseudocode

What is an Algorithm?

An algorithm is a sequence of well-defined steps or rules used to solve a specific problem or perform
a task. It outlines the logic to follow in order to achieve a desired outcome.

Key Characteristics of an Algorithm:

1. Well-defined steps: Each step must be very clear

2. Finite: The algorithm must eventually complete after a certain number of steps.

3. Input and Output: It takes some input and produces an output.

4. Effective: It should solve the problem efficiently.

Example: Adding Two Numbers (Algorithm)

To add two numbers, we can describe the algorithm like this:

1. Start.

2. Input the first number.

3. Input the second number.

4. Add the two numbers together.

5. Output the result.

6. End.

This is the basic logic for adding two numbers, represented as an algorithm.

What is Pseudocode?

Pseudocode is a way of representing an algorithm using plain, easy-to-understand language. It


doesn’t adhere to any specific programming language but is structured in a way that resembles
programming. This helps you focus on the logic rather than syntax, making it easy to convert into
real code later.

Pseudocode is an intermediate state between algorithm and a program.


Key Features of Pseudocode:

1. No strict syntax: It is written in plain language, making it flexible and easy to understand.

2. Readable: Even non-programmers with basic understanding can follow pseudocode.

3. Serves as a blueprint: It helps plan out the algorithm before actual coding.

Example: Adding Two Numbers (Pseudocode)

Here’s how the algorithm for adding two numbers can be expressed in pseudocode:

BEGIN

READ number1

READ number2

sum = number1 + number2

PRINT sum

END

This pseudocode outlines the steps to take two inputs, add them, and display the result in an easy-
to-understand format. Once the pseudocode is ready, it can easily be translated into a programming
language.

Difference Between Algorithm and Pseudocode (Using the Example):

 Algorithm: Describes the steps to solve a problem using plain language (like “input the
numbers, add them, and show the result”).

 Pseudocode: Translates those steps into a structured format that resembles code, but
without language-specific syntax.

Algorithm is the logical plan, while pseudocode is a representation of that plan in a format closer to
programming.
Difference between Algorithm and Pseudocode

Feature Algorithm Pseudocode


An Algorithm provides a solution to Pseudocode describes the steps of an
Purpose a specific problem through a algorithm in a format that resembles
structured series of steps. programming languages.
Incorporates reserved keywords like IF,
Uses simple, everyday English
Language ELSE, FOR, WHILE, etc., to structure the
words for clarity.
logic.
Consists of "fake" code, as the term
Consists of a sequence of logical
Nature "pseudo" implies, blending coding
steps leading to a solution.
structure with plain language.
Writing algorithms follows no strict Specific rules govern how pseudocode is
Rules
rules; creativity is encouraged. written, ensuring clarity and consistency.

Main Constructs of Pseudocode

Pseudocode utilizes three primary constructs to represent the control flow of algorithms:

1. Sequencing
o Description: This construct refers to executing tasks in a linear, step-by-step
manner, where each operation follows the previous one.
o Example:

BEGIN
Input number1
Input number2
sum = number1 + number2
Print sum
END

2. Selection
This construct allows for decision-making within the algorithm. It can be further
divided into:
o IF-ELSE Structure:
 Description: Executes different code blocks based on whether a
condition is true or false.
 Example:

IF condition THEN
Perform action A
ELSE
Perform action B
ENDIF

o CASE Structure:
 Description: A generalized form of the IF-ELSE structure, allowing
multiple conditions to be evaluated based on the value of a variable.
 Example:

CASE variable OF
value1: Perform action for value1
value2: Perform action for value2
OTHERWISE: Perform default action
ENDCASE

3. Repetition

This construct enables the execution of a block of code multiple times. It includes:

o FOR Loop:
 Description: Iterates a specified number of times, often using a
counter variable.
 Example:

FOR i = 1 TO 10 DO
Print i
ENDFOR

o WHILE Loop:
 Description: Continues to execute as long as a specified condition is
true, with the condition checked before each iteration.
 Example:

WHILE condition DO
Perform action
ENDWHILE

o REPEAT-UNTIL Loop:
 Description: Executes a block of code until a specified condition
becomes true, with the condition checked after each iteration.
 Example:

REPEAT
Perform action
UNTIL condition
Pseudocode to evaluate the expression d = a + b * c

BEGIN

READ a

READ b

READ c

CALCULATE d = a + (b * c)

PRINT d

END

2. Pseudocode to calculate Simple Interest using the formula:

Where:

𝑃 - P is the Principal amount,

𝑅 - R is the Rate of interest,

𝑇 - T is the Time (in years).

Pseudocode:

BEGIN

READ P

READ T

READ R

CALCULATE SI = (P * T* R) / 100

PRINT SI

END
Here are some pseudocode questions focused on sequential order, where steps are executed one
after another:

1. Find the sum of two numbers

 Write pseudocode to input two numbers and calculate their sum.

2. Convert Celsius to Fahrenheit

 Write pseudocode to input a temperature in Celsius and convert it to Fahrenheit using the
formula

3. Calculate the area of a circle

 Write pseudocode to input the radius of a circle and calculate its area using the formula

4. Calculate simple interest

 Write pseudocode to input the principal amount, rate of interest, and time, then calculate
the simple interest using the formula

5. Find the average of three numbers

 Write pseudocode to input three numbers and calculate their average.

6. Calculate the perimeter of a rectangle

 Write pseudocode to input the length and width of a rectangle and calculate its perimeter
using the formula

7. Convert hours into minutes

 Write pseudocode to input a number of hours and convert it into minutes.

8. Calculate the square of a number

 Write pseudocode to input a number and calculate its square.

9. Calculate the total cost of items

 Write pseudocode to input the price and quantity of items purchased, then calculate the
total cost.

10. Find the product of two numbers

 Write pseudocode to input two numbers and calculate their product.

Note:

These questions are designed to help students practice writing pseudocode that executes tasks in
sequential order. Each task involves straightforward input, calculation, and output without decision-
making or looping.
The main Constructs of Pseudocode (Contn..)
ii) Selection

What is Selection (Decision-Making)?


Selection, or decision-making, is the process in programming where the program chooses
what to do based on certain conditions. It allows a program to make choices and run different
sets of instructions depending on whether a condition is true or false.

Types of Selection Statements

a. IF-THEN-ELSE Statement

The IF-THEN-ELSE statement is the simplest form of decision-making. It checks if a


condition is true or false and runs different blocks of code based on the result.

 IF: If the condition is true, the program executes a block of code.


 ELSE: If the condition is false, the program runs an alternative block of code.

Structure:

IF condition THEN

Statement – x

Statement – y

ELSE

Statement – p

Statement – q

ENDIF

Example:
If we want to check if someone is old enough to vote, we use an IF-THEN-ELSE statement.

IF age >= 18 THEN


PRINT "You can vote!"
ELSE
PRINT "You cannot vote yet."
ENDIF
b. Nested IF-THEN-ELSE Statements

Sometimes, we need to check multiple conditions. A nested IF-THEN-ELSE statement lets


you check more than one condition by putting one IF statement inside another.

Example:

If we want to assign a grade based on a score, we use nested IF statements.

IF condition1 THEN

Statement – x

Statement – y

ELSE IF condition2 THEN

Statement – p

Statement – q

ELSE IF condition2 THEN

Statement – r

Statement – s

ELSE

Statement – t

Statement – u

ENDIF
Example:

IF score >= 90 THEN

PRINT "A Grade"

ELSE IF score >= 80 THEN

PRINT "B Grade"

ELSE IF score >= 70 THEN

PRINT "C Grade"

ELSE IF score >= 60 THEN

PRINT "D Grade"

ELSE IF score >= 50 THEN

PRINT "PASS"

ELSE

PRINT "FAIL"

ENDIF

Here, the program first checks if the score is 90 or above (for an A grade). If not, it checks if
the score is 80 or above (for a B grade) … so on…. If neither condition is true, the program
prints "FAIL"

c. CASE

A CASE construct indicates a multiway branch based on conditions that are mutually
exclusive. Four keywords, CASE, OF, OTHERWISE, and ENDCASE, and conditions are
used to indicate the various alternatives.

The general form is:

CASE expression OF

condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERWISE: default sequence

ENDCASE
Example :

CASE Vehicle OF

"Car" : PRINT "You chose a Car."

"Bike” :PRINT "You chose a Bike."

"Bus" : PRINT "You chose a Bus."

"Truck": PRINT "You chose a Truck."

OTHERWISE: PRINT "Unknown vehicle."

ENDCASE

Examples as per the Syllabus :

1. Determine the Larger of Two Numbers

ALGORITHM

1. Start
2. Get the first value number1
3. Get the second value number2
4. Compare number1 and number2
o If number1 is greater, display number1 as the larger value
o If number2 is greater, display number2 as the larger value
o If they are the same, display that both are equal
5. End

BEGIN
READ number1
READ number2
IF number1 > number2 THEN
PRINT "The larger number is: " number1
ELSE IF number2 > number1 THEN
PRINT "The larger number is: " number2
ELSE
PRINT "Both numbers are equal."
ENDIF
END

2. Determine the Smallest of Three Numbers


BEGIN
READ number1
READ number2
READ number3
IF number1 <= number2 AND number1 <= number3 THEN
PRINT "The smallest number is: " number1
ELSE IF number2 <= number1 AND number2 <= number3 THEN
PRINT "The smallest number is: " number2
ELSE
PRINT "The smallest number is: " number3
ENDIF
END

3. Determine the Grade Earned by a Student Based on KTU Grade Scale


(Using IF-ELSE)
BEGIN
READ score
IF score >= 90 THEN
PRINT "Grade: S"
ELSE IF score >= 85 THEN
PRINT "Grade: A+"
ELSE IF score >= 75 THEN
PRINT "Grade: A"
ELSE IF score >= 65 THEN
PRINT "Grade: B+"
ELSE IF score >= 55 THEN
PRINT "Grade: B"
ELSE IF score >= 45 THEN
PRINT "Grade: C"
ELSE IF score >= 40 THEN
PRINT "Grade: P"
ELSE
PRINT "Grade: F"
ENDIF
END

4. Determine the Grade Earned by a Student Based on KTU Grade Scale


(Using CASE)
BEGIN
READ score
CASE score OF
score >= 90: PRINT "Grade: S"
score >= 85: PRINT "Grade: A+"
score >= 75: PRINT "Grade: A"
score >= 65: PRINT "Grade: B+"
score >= 55: PRINT "Grade: B"
score >= 45: PRINT "Grade: C"
score >= 40: PRINT "Grade: P"
OTHERWISE : PRINT "Grade: F"
ENDCASE
END
Main Constructs of Pseudocode:

iii) Repetition/Iteration Control Structures - Loops

Loops in Pseudocode
Loops are a crucial part of programming that allow for the repetition of a set of instructions
multiple times. In pseudocode, there are three common types of loops:

1. FOR Loops
2. WHILE Loops
3. REPEAT UNTIL Loops

1. FOR Loops

A FOR loop is used when the number of iterations is known beforehand. It is typically used
to iterate over a range of values or loop through elements of a collection.

General Structure:
FOR variable FROM start_value TO end_value
statement(s)
END FOR

Example:

FOR i FROM 1 TO 5
PRINT i
END FOR

This loop will output:

1
2
3
4
5

In this example, the loop runs from i = 1 to i = 5, printing each value of i.


2. WHILE Loops

A WHILE loop repeats a block of code as long as a specified condition remains true. It is
often used when the number of iterations is not known in advance.

General Structure:
WHILE condition
statement(s)
END WHILE

Example:

count = 0
WHILE count < 5
PRINT count
count = count + 1
END WHILE

This loop will output:

0
1
2
3
4

The loop continues executing as long as the condition count < 5 is true. Once count reaches
5, the loop stops.

3. REPEAT UNTIL Loops

The REPEAT UNTIL loop is a variant of the WHILE loop. It always executes the code
block at least once and then continues until the condition becomes true.

General Structure:

REPEAT
statement(s)
UNTIL condition

Example:

count = 0
REPEAT
PRINT "TECHTALKZ"
count = count + 1
UNTIL count >= 5
This loop will output:

TECHTALKZ
TECHTALKZ
TECHTALKZ
TECHTALKZ
TECHTALKZ

The REPEAT UNTIL loop ensures that the block of code is executed at least once, even if
the condition is false initially.

Summary:

 FOR loops are ideal for cases where the number of iterations is known.
 WHILE loops are useful when the condition controls the number of iterations.
 REPEAT UNTIL loops ensure the block of code executes at least once and continue
until the condition becomes true.
ALGORITHM & PSEUDOCODE EXAMPLES

1. Print Numbers from 50 to 1 in Descending Order

Algorithm

1. Start
2. Initialize a variable num and set it to 50.
3. Repeat the following steps while num is greater than or equal to 1:
o Print the value of num.
o Decrease the value of num by 1.
4. End

Pseudocode
BEGIN
SET num = 50
WHILE num >= 1
PRINT num
num = num - 1
END WHILE
END

This pseudocode uses a while loop to iterate from 50 down to 1, printing each number in the
process.

2. Find the Factorial of a Number

Algorithm

1. Start
2. Input the number n.
3. Initialize a variable fact and set it to 1.
4. For each integer i from 1 to n, do the following:
o Multiply fact by i.
5. After the loop ends, fact will hold the factorial of n.
6. Print the value of fact.
7. End

Pseudocode
BEGIN
INPUT n
SET fact = 1
FOR i FROM 1 TO n
fact = fact * i
END FOR
PRINT fact
END
3. Find the Sum of n Numbers Input by the User (Using all the three loop
variants)

Algorithm

1. Start
2. Input the value of n (the number of values to sum).
3. Initialize a variable sum and set it to 0.
4. Initialize a counter variable i and set it to 1.
5. Repeat the following steps while i is less than or equal to n:
 Input a number from the user.
 Add the number to sum.
 Increment the counter i by 1.
6. After the loop ends, print the value of sum.
7. End

Pseudocode Using a for Loop


BEGIN
INPUT n
SET sum = 0
FOR i FROM 1 TO n
INPUT num
sum = sum + num
END FOR
PRINT sum
END

Pseudocode Using a while Loop


BEGIN
INPUT n
SET sum = 0
SET i = 1
WHILE i <= n
INPUT num
sum = sum + num
i = i + 1
END WHILE
PRINT sum
END

Pseudocode Using a REPEAT UNTIL Loop


BEGIN
INPUT n
SET sum = 0
SET i = 1
REPEAT
INPUT num
sum = sum + num
i = i + 1
UNTIL i <= n
PRINT sum
END

4. Find the Largest of n Numbers Input by the User

Algorithm
1. Start
2. Input the value of n (the number of values to compare).
3. Initialize a variable max to a very small number (0)
4. Repeat the following steps from 1 to n:
o Input a number from the user.
o If the number is greater than max, update max to this number.
5. Print the value of max.
6. End

Pseudocode
BEGIN
INPUT n
SET max = 0
FOR i FROM 1 TO n
INPUT num
IF num > max THEN
max = num
END IF
END FOR
PRINT max
END

SIMILAR QUESTIONS

1. Check Whether a Given Number is Even or Odd

Algorithm:

1. Start
2. Input the number n.
3. If n % 2 == 0 (i.e., remainder when n is divided by 2 is zero), then:
o Print "n is even."
4. Else:
o Print "n is odd."
5. End
Pseudocode:

BEGIN
INPUT n
IF n % 2 == 0 THEN
PRINT "n is even"
ELSE
PRINT "n is odd"
END IF
END

2. Print Even Numbers Up to n

Algorithm:

1. Start
2. Input the value of n.
3. Initialize a variable i and set it to 2.
4. While i <= n, repeat the following steps:
o Print i.
o Increment i by 2.
5. End

Pseudocode:

BEGIN
INPUT n
SET i = 2
WHILE i <= n DO
PRINT i
i = i + 2
END WHILE
END

3. Generate Fibonacci Series Up to n Terms

Algorithm:

1. Start
2. Input the number n.
3. Initialize a = 0, b = 1, and a counter i = 1.
4. While i <= n, repeat the following steps:
o Print a.
o Set temp = a.
o Set a = b.
o Set b = temp + b.
o Increment i by 1.
5. End
Pseudocode:

BEGIN
INPUT n
SET a = 0, b = 1, i = 1
WHILE i <= n DO
PRINT a
temp = a
a = b
b = temp + b
i = i + 1
END WHILE
END

4. Check Whether a Number is Prime

Algorithm:

1. Start
2. Input the number n.
3. If n <= 1, print "n is not prime."
4. Initialize i = 2.
5. While i <= sqrt(n), check:
o If n % i == 0, print "n is not prime" and stop.
o Increment i by 1.
6. If no divisors are found, print "n is prime."
7. End

Pseudocode:

BEGIN
INPUT n
IF n <= 1 THEN
PRINT "n is not prime"
ELSE
SET i = 2
WHILE i <= sqrt(n) DO
IF n % i == 0 THEN
PRINT "n is not prime"
EXIT
END IF
i = i + 1
END WHILE
PRINT "n is prime"
END IF
END
Sample University-Style Questions:

 Write the algorithm and pseudocode to find the sum of the first n natural numbers.
 Write the algorithm and pseudocode to reverse a given number.
 Write the algorithm and pseudocode to check whether a given number is a palindrome.
 Write the algorithm and pseudocode to find the greatest common divisor (GCD) of two
numbers using the Euclidean algorithm.
 Write the algorithm and pseudocode to check whether a given year is a leap year or not.
 Write the algorithm and pseudocode to find the sum of the digits of a given number.
 Write the algorithm and pseudocode to generate the first n prime numbers.
 Write the algorithm and pseudocode to check whether a given string is a palindrome.
 Write the algorithm and pseudocode to calculate the power of a number (i.e., a^b).
What are the Basic Symbols of a Flowchart?
A flowchart is a graphical representation of a process, algorithm, or workflow using various
symbols to depict different actions or decisions. Flowcharts are widely used in planning,
designing, and analyzing programs and processes.

Below are the key symbols used in creating a flowchart:

Symbol Symbol Name Purpose

Start/Stop (Oval) Indicate Start / End of the process

Represent action or process / operation


Process (Rectangle)
step

Input/ Output
inputs and outputs information
(Parallelogram)

Stands for decision statements in a


Decision (Diamond) program, where answer is usually Yes or
No.

Shows relationships between different


Flow / Arrow
elements. Indicates flow between steps
In the context of loops, the hexagon
(preparation symbol) in a flowchart is used
to indicate initialization or any setup steps
Preparation (Hexagon) required before the loop begins. This is
typically where you initialize variables,
counters, or other prerequisites that will be
used within the loop.
Predefined Process (Subroutine) block
Predefined Process represents a set of instructions that are
(Subroutine) defined separately but can be reused in the
main process

On-page Connector Connects two parts of a flowchart on the


(Reference) same page.

Off-page Connector Connects two parts of a flowchart in


(Reference) different pages.
1. Draw a flowchart to add two numbers

2. Draw a flowchart to evaluate an expression, d=a+b*c,


3. Draw a flowchart to find the simple interest

4. Determine the smallest of three numbers


5. Determine the largest of 3 numbers

6. Determine the grade earned by a student based on KTU grade scale


Display “Hello World” 10 times
Using FOR Loop

Using WHILE Loop


Print 1 to 50 in ascending order

Print 1 to 50 in descending order


Find and Print the factorial of a given number

Find & Print the largest of n numbers


Find & Print the Sum of n numbers
MODULE CALL / SUBROUTINE CALL

In a flowchart, a module or subroutine call is typically represented by a rectangle with double-struck


(parallel) vertical sides or a rectangle with a single horizontal bar at the top and bottom. This shape
indicates that a separate subroutine or module will be executed when the flow reaches this point.

Symbol Shape: A rectangle with double-struck vertical sides (can also be referred to as the
subroutine symbol).

Label: Inside the symbol, you write the name of the module being called, such as Module A or
Subroutine X.

This symbol is used to indicate a function call or module call, where the control is transferred to a
separate, reusable set of instructions before returning to the main flow.

Example

The following example uses the Call Shape to execute a function called 'Greeting'.

When the program executes, the first shape will call the Greeting Function. After it outputs "Hello!",
it will return and the Main Function and it will output "Goodbye!".
Q. Draw a flowchart to calculate the area of a circle using a module called area.

Additional Questions

Q. Draw a flowchart to check whether the number n is even or odd.


Q. Draw a flowchart to check whether the number n is prime or not.

Q. Draw a flowchart to calculate the sum of the first n natural numbers.

Hint: Sn = n(n+1)/2

Q. Draw a flowchart to find the GCD (Greatest Common Divisor) of two numbers

Q. Draw a flowchart to convert temperature from Celsius to Fahrenheit.

Q. Draw a flowchart to calculate the average of n numbers.

Q. Draw a flowchart to determine if a year is a leap year. (A year is a leap year if it is exactly
divisible by 4, A year is not a leap year if it is exactly divisible by 100 but not by 400,
A year is a leap year if it is exactly divisible by 400 )

You might also like