0% found this document useful (0 votes)
4 views34 pages

Module 1 Complete2025

The document outlines concepts related to problem-solving, distinguishing between well-defined and ill-defined problems, and detailing various problem-solving strategies such as trial and error, algorithms, heuristics, and working backward. It emphasizes the importance of understanding multiple strategies for adaptability, efficiency, and improved outcomes. Additionally, it describes the steps involved in problem-solving, including understanding the problem, formulating a model, developing an algorithm, coding, testing, and evaluating the solution.

Uploaded by

midhunxydo
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)
4 views34 pages

Module 1 Complete2025

The document outlines concepts related to problem-solving, distinguishing between well-defined and ill-defined problems, and detailing various problem-solving strategies such as trial and error, algorithms, heuristics, and working backward. It emphasizes the importance of understanding multiple strategies for adaptability, efficiency, and improved outcomes. Additionally, it describes the steps involved in problem-solving, including understanding the problem, formulating a model, developing an algorithm, coding, testing, and evaluating the solution.

Uploaded by

midhunxydo
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

25CSESP 105: ALGORITHMIC THINKING WITH PYTHON

MODULE 1

Q1. Define Problem: (Part A)

A problem arises when the solution is not immediately clear. It can be understood through four key
conditions:

 Initial situation – the current or starting state.

 Goal – the intended solution or desired outcome.

 Resources – the tools, knowledge, or methods available to move from the starting state toward the
goal.

 Commitment – the willingness to apply one’s skills, knowledge, and effort to achieve the desired
result.

Q2. Define Well-defined .(Part A)

Well-defined problems are those that have clear and specific goals, well-defined initial conditions, a
known set of operations or steps to solve them, and a limited number of solutions. These problems can
often be solved using algorithms or straightforward methods. An example would be a math problem or
a jigsaw puzzle, where the path to the solution and the solution itself are clear.

[Link] an Ill-defined problems.(Part A)

Ill-defined problems, on the other hand, lack clear goals, initial conditions, and defined methods for
solving them. These problems may have multiple or ambiguous solutions and require creative or critical
thinking. They are often complex, unique, and have uncertain outcomes. An example would be solving
real-world political or social issues, where the problem itself may not be clearly defined, and there is no
single correct answer.
Q4. (Part A)

Q5. State any three Well-defined Problems, Justify your answer. (Part A)
Well-Defined Problems :-These problems have clear goals, a defined path to a solution,
and specific criteria for determining when the problem is solved. Let’s explore three
examples:

1. Mathematical Equation:Problem: Solve the equation 2x+3=7.

Why it’s Well-Defined: The problem has a clear goal (find the value of x), a specific method
(solve for x using algebraic rules), and a definite solution (x=2).

2. Crossword Puzzle:

Problem: Complete a standard crossword puzzle.


Why it’s Well-Defined: The crossword has a clear objective (fill in all the squares with the correct
words), a specific set of rules, and a single correct solution.

3. Recipe Execution:

Problem: Bake a chocolate cake using a provided recipe.


Why it’s Well-Defined: The goal (bake a chocolate cake) is clear, the process is outlined step-by-step in
the recipe, and success is measurable by the outcome (a baked cake that meets the description).
Q6. State any three Ill-defined Problems, Justify your answer. (Part A)
These problems are ambiguous, lack clear criteria for solutions, and often have multiple possible
solutions. Here are three examples:

1. Designing a Sustainable City:

Problem: How can we design a sustainable city for the future?


Why it’s Ill-Defined: The problem is broad, with no single clear solution. Various factors like
environmental impact, social equity, and economic viability must be balanced, and different
stakeholders may have conflicting priorities.

[Link] a Novel:

Problem: Write a compelling novel that appeals to a broad audience.


Why it’s Ill-Defined: The goal is subjective (what is "compelling"?), the process can vary widely, and
success is difficult to measure. Different readers may have different interpretations of what makes the
novel appealing.

3. Resolving Workplace Conflict:

Problem: Resolve a conflict between two team members in the workplace.


Why it’s Ill-Defined: The problem is complex with no clear solution. It involves interpersonal dynamics,
emotions, and communication styles, and what works in one situation might not work in another.
Multiple solutions may exist, and the "right" one depends on various factors.

Q7. Define Problem Solving. (Part A)


Problem solving is the process of transforming the description of a problem into the solution by using
our knowledge and by relying on our ability to select and use appropriate problem-solving strategies
and tools to implement.

Q8. Define Problem-Solving Strategies (Part- A)


A problem-solving strategy is a plan used to find solutions or tackle [Link] strategy includes
specific steps to follow. These approaches provide guidelines to help you solve business problems or
industry issues effectively. To solve problems successfully, you need to identify the problem, choose the
right approach and follow a plan tailored to the specific issue.

Q9. List and explain various Commonly used problem-solving strategies ( Part -B)
1. Trial and Error: Trying different solutions until one works.
2. Algorithm: A step-by-step procedure for solving a problem.
3. Heuristic: A shortcut strategy that is not guaranteed to be optimal but works under
certain conditions.
4. Working Backward :Begin solving a problem by focusing on the end result:
1. Trial and Error Problem-Solving Strategy :( Part-A)

One of the most common problem-solving strategies is trial and [Link] method, often utilized in
simple situations, involves experimenting with different approaches until a satisfactory outcome is
[Link] trial-and-error problem-solving strategy involves attempting different solutions and
learning from mistakes until a successful outcome is [Link] is a fundamental method that relies on
experimentation and iteration, rather than systematic or analytical approaches.

Steps:

1. Identify the problem – Start by clearly defining the issue.


2. Try a solution – Attempt a possible solution.
3. Evaluate the outcome – Check if the solution worked.
4. Repeat – If the solution failed, try a different one.

Although trial and error is not typically one of the most time-efficient strategies, it is a commonly used
one.

Advantages of Trial-and-Error:- (Part- A)

 Simplicity: Easy to understand and apply.


 Practicality: Can be used in situations with a limited set of options.
 No Need for Extensive Planning: Allows for immediate action.
Disadvantages of Trial-and-Error:- (Part- A)

 Time-Consuming: May take a while to find the correct solution.


 Inefficiency: Not the most efficient approach if multiple solutions exist.
 Uncertainty: No guarantee of finding a solution quickly.

Example :-PROBLEM: HOW TO CROSS THE RIVER?


A farmer with a fox, a goose, and a sack of corn needs to cross a river. The farmer has a boat, but there
is room for only the farmer and one of his three items. Unfortunately, both the fox and the goose are
hungry. The fox cannot be left alone with the goose, or the fox will eat the goose. Likewise, the goose
cannot be left alone with the sack of corn, or the goose will eat the corn. How does the farmer get
everything across the river?
2. Explain Algorithmic Problem-Solving Strategy: (Part- A)
A common type of strategy is an algorithm. An algorithm is a problem-solving formula that provides
step-by-step instructions to achieve a desired [Link] algorithm is a step-by-step, logical procedure
that guarantees a solution to a [Link] is systematic and follows a defined sequence of operations,
ensuring consistency and accuracy in finding the correct solution. An algorithm can be implemented in
any programming language, and it should always produce the same output for the same input.

An algorithm is a systematic, step-by-step procedure designed to guarantee a solution to a problem. By


following a defined sequence of logical operations, it ensures consistent and accurate results.

Example 1: Algorithm for Baking a Cake (Part- A)

[Link] ingredients
[Link] Oven
[Link] Ingredients
[Link] baking Pan
[Link] Batter
[Link]
[Link] for Doneness.
[Link] and Serve

This algorithm (the recipe) provides a systematic method for achieving the desired result: a perfectly
baked cake.

Example 2 - Sorting N numbers using Bubble sort [Link] you want to sort a list of numbers in
ascending order, you can use an algorithm that compares each pair of numbers and swaps them if they
are out of order.

Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them if
they are in the wrong order.
Steps for the given array:
Start with the first two numbers (6 and 3). Since 6 > 3, swap them:
Compare 6 and 0. Swap since 6 > 0
Compare 6 and 5. Swap since 6 > 5
Compare 6 and 1. Swap since 6 > 1:
This completes one pass, and the largest number (6) is now at the end.
The algorithm repeats the above steps for the remaining array until it is fully sorted:
Final sorted array:

3. Heuristic Problem-Solving Strategy (Part- A)

A heuristic is another type of problem-solving strategy.A heuristic is a practical approach to problem-


solving based on experience and intuition. It does not guarantee a perfect solution but provides a good
enough solution quickly, often through rules of thumb or educated guesses. It’s a shortcut: you make a
reasonably good decision without exhaustive [Link] use mental shortcuts and prior experience
rather than an optimal algorithm.

When driving in a city with frequent traffic congestion, you might use a heuristic approach to find the
fastest route to your destination.

1. Rule of Thumb: You know from experience that certain streets are typically less congested during
rush hour.

2. Current Conditions: You use a traffic app to check current traffic conditions, looking for red or yellow
indicators on major roads.

3. Alternative Routes: You consider side streets and shortcuts you have used before that tend to be less
busy.

4. Decision: Based on the app and your knowledge, you decide to avoid the main highway (which shows
heavy congestion) and take a series of back roads that usually have lighter traffic.

While this heuristic approach does not guarantee that you will find the absolute fastest route, it
combines your experience and real-time data to make an informed, efficient decision, likely saving you
time compared to blindly following the main routes.

[Link] Backwards-Solving Strategy (Part- A) - Begin solving a problem by focusing on the end result:.

Working Backwards is a problem-solving strategy in which you start with the end goal and work
backward to figure out the steps needed to get there. In other words, instead of starting from the
beginning and moving forward, you start from the end and move backward. This strategy is commonly
used in math problems that ask you to find a starting value or figure out what happened before a given
situation.
Working Backwards - Examples

Example 1: Sarah had some pens. She bought 34 pens. She then threw away 29 pens as they were spoilt.
In the end, she had 64 pens. How many pens did Sarah have at first?

Always remember when we work backwards, everything will be reversed,e.g., instead of adding, we
[Link] will start drawing the model from the end by drawing a box and label it "End". Put the end
amount 64 in the [Link] an arrow pointing to the left, and draw another box. On top of the arrow,
write +29 because Sarah threw away 29 pens. Instead of subtracting, we need to add.
In the box, write 93 (64 + 29 = 93).

Draw another arrow pointing to the left, and draw another box. On top of the arrow, write –34 because
Sarah bought 34 pens. Instead of adding, we need to subtract.
In the box, write 59 (93 – 34 = 59). Label the box "At First" or "Before".

Sarah had 59 pens at first.

Q10. Importance of Understanding Multiple Problem-solving Strategies? (Part- A)


1. Adaptability:Different problems may require different approaches. Having multiple strategies allows
you to adapt to various situations, whether it's a well-defined problem) or an ill-defined problem .

2. Efficiency:-Some strategies might be more efficient for certain problems. By understanding and
applying the right strategy, you can save time and effort, solving problems more quickly and effectively.
3. Improved Outcomes:With multiple problem-solving strategies, you can evaluate which approach
works best for a specific problem. This helps in making more informed, effective decisions, rather than
relying on one habitual method.
4. Skill Development: Exposure to diverse strategies encourages creative thinking. When you know
various ways to approach a problem, you can combine methods or think outside the box to develop
unique solutions.

Q11. Explain Computer as a Model of Computation (Part-A)

A computer can be seen as a simple model of computation where a problem is solved by taking input,
processing it, and giving an [Link] simple problems, one round of input–process–output is enough.
However, for complex problems, the computer may need to repeat this cycle multiple times, using the
output of one stage as the input for the next. These repeated steps generate intermediate results that
gradually build toward the final solution.

In this context, problem solving means finding a way to take the given information (input), apply logical
steps and computations to it (process), and produce the required answer (output). The main focus is
learning how to break down complex tasks into smaller, manageable steps that a computer can handle.
Problem solving is a step-by-step method of looking at a situation, understanding the information, and
finding the right solutions. To solve a problem, we usually follow some clear steps, similar to the input–
process–output system:

Input – Collect all the information about the problem.

Process – Think about the information, analyze it, and plan possible solutions.

Output – Choose the best solution and put it into action.


Q12. List and explain Steps Involved in Problem Solving (Part-B)
[Link] the Problem
Clearly identify what the problem is and what the desired outcome should be.

[Link] a Model
Create a simplified representation or plan that captures the key parts of the problem.

[Link] an Algorithm
Design step-by-step instructions or a method to solve the problem.

[Link] the Program


Translate the algorithm into a programming language or executable instructions.

[Link] the Program


Run the program with different inputs to ensure it works correctly and fixes errors if any.

[Link] the Solution


Review the solution’s effectiveness and efficiency, making improvements as necessary.

[Link] the Problem:-Effective problem-solving means first understanding the problem


clearly. You need to know what the problem is, why it exists, and what limits or rules you must follow.
To do this, you can talk to the people involved, ask questions, or use surveys to gather information. If
the problem is large, it helps to break it into smaller, easier parts so you can handle it step by step.
Example:-
EXAMPLE: Find the area of a rectangle

Here, the problem is simple:

What do we need to find? The area of a rectangle.


What inputs are needed? The length and width of the rectangle.
What is the relationship? The area of a rectangle is calculated by multiplying its length and width.
Input: Length = 5 units, Width = 4 units.
Output: Area = Length × Width = 20 square units.

[Link] a Model:-Once you understand the problem, the next step is to think of possible
solutions. You can use methods like brainstorming, brain-writing, or mind mapping to come up with
ideas. After collecting ideas, turn them into a clear model that explains how the solution will work.
This model can be made using techniques like mathematical modeling or simulation. The important
thing is that the model should correctly represent your ideas so it can be turned into a real solution later.

For Example: Find the Area of Rectangle.


Once the problem is understood, we create a mathematical or logical model to describe the
solution. In this case, the formula for the area of a rectangle is:Area = Length × Width .

This formula represents the model we will use to solve the problem.

[Link] an Algorithm:-

After finding possible solutions, the next step is to write them as algorithms, which are step-by-step
instructions to solve the problem. You don’t use all the solutions, so you need to compare them and
pick the best [Link] choice depends on factors like how much memory it uses, how fast it works,
and how simple the code is.

Example: Algorithm to compute area of Rectangle.

[Link].

[Link] the Length of the rectangle.

[Link] the Breadth (width) of the rectangle.

[Link] the area using the formula: Area = Length × Breadth.

5. Print the Area.

[Link].

[Link] the Program:-The interesting part of the process! Coding! After the best algorithm is
determined, you implement it as an executable program. The program or the code is a set of
instructions that is more or less, a concrete representation of the algorithm in some programming
language While coding, always follow the incremental paradigm – start with the essential functionalities
and gradually add more and more to it.
Example:-Python program to Compute area of Rectangle:
[Link] the Program:-After coding, the program must be tested to check if it works correctly.
Testing means running the program with different inputs to see if it gives the right output. If the result is
wrong, that error is called a bug. Since testing with every possible input is not possible, a smaller set of
sample inputs (called a test suite) is used. Automated tools can also help create these test cases. If errors
are found, debugging is done to fix them. Testing and debugging are repeated until the program works
properly.

Test cases for : Area of rectangle problem.

1. Test with normal positive numbers


Input: length = 5, breadth = 10
Expected output: 50

[Link] with zero as one side


Input: length = 0, breadth = 10
Expected output: 0

[Link] with both sides zero


Input: length = 0, breadth = 0
Expected output: 0

[Link] with decimal (floating point) values


Input: length = 5.5, breadth = 3.2
Expected output: 17.6

[Link] the Solution:-The final step is to evaluate the solution and check if it meets the goals of
the problem. To do this, set clear criteria like efficiency, feasibility, and scalability. Also, think about
possible risks when using the program. Gather feedback from stakeholders to see how well the program
works and make improvements if needed. After changes, test the updated program carefully again to
ensure it works correctly.
Q13. A case study for Problem solving Process - The Discriminant calculator(Part-B)
1. Understand the problem: Here we formally define the problem by specifying the inputs and output.

Input: The three coefficients a, b and c of the quadratic equation

Output: The discriminant value D for the quadratic equation


2. Formulate a model for the solution: Develop a mathematical model for the solution, that is
identify the mathematical expression for the quadratic equation discriminant D.

3. Develop an algorithm: A possible algorithm (in pseudo-code) for our discriminant problem is
given below:

1 Start

2 READ a, b, c

3 D=b*b-4*a*c

4 PRINT D

5 Stop

4. Code the program: Part(A)


Code the above algorithm in python

5. Test the program:-


Test the program: You create a test suite similar to the one shown in Table 2. Each row denotes a set of
inputs (a, b, and c) and the expected output (D) with which the actual output is to be compared.
[Link] the Solution:
 The evaluation of the solution considers key factors including its efficiency, how reliably it performs,
and its ability to scale.

 Assessment of the solution involves examining its efficiency, ensuring consistent reliability, and
determining its scalability for larger inputs or use cases.

 The solution is judged by criteria like operational efficiency, dependable performance, and
scalability to handle varying workloads or sizes [Link] solution is assessed based on criteria
such as efficiency, reliability, and scalability.

Q14. Define Algorithm: Part(A)


• An algorithm describes a systematic way of solving a problem.
• It is a step-by-step procedure that produces an output when given the necessary inputs.
• An algorithm uses pure English phrases or sentences to describe the solution to a problem.
[Link] and explain Characteristics of Algorithm( Part -A)
An algorithm must possess following characteristics:
1. Precision — the steps are precisely stated or defined.
2. Uniqueness — results of each step are uniquely defined and only depend on the input and the result
of the preceding steps.
3. Finiteness — the algorithm always stops after a finite number of steps.
4. Input — the algorithm receives some input.
5. Output — the algorithm produces some output.
[Link] an algorithm to evaluate an expression given below : S=x + y :Part(A)
Or
Write an Algorithm to add two numbers
Step 1: Start

Step 2: Read x, y
Step 3: Add x, y to s
Step 4: Display s
Step 5: Stop
Q17. Algorithm to find the average of 3 numbers : Part(A)
Step 1: Start
Step 2: Read three numbers a , b, c.
Step 3: Calculate Sum by adding a ,b ,c
Step 4: Calculate the average of three numbers , avg by dividing sum by three
Step 5: Print avg
Step 6: Stop
Q18. Write an Algorithm to evaluate an expression : d= a + b*c : Part(A)

1 .Start
2. Read the values of (a, b c).
3 .Find the product of b and c
4 .Store the product in a temporary variable *temp*.
[Link] the sum of a and temp
6 .Store the sum in d.
7 .Print the value of d.
8 .Stop.

Q19. Define PseudoCode : (Part -A)

Pseudocode is a simple way to describe an algorithm using plain language mixed with programming-
like statements. It is not a real program, but it shows the steps of a solution clearly. Pseudocode uses
math expressions and logical steps to explain ideas more clearly than plain language. It can include
programming concepts without following the strict rules of any language. Since it is not executable, its
purpose is to help us understand the flow of an algorithm. Good pseudocode should always be written
in a clear and structured way.

Q20. List and explain the reasons for using Pseudocode:( Part -A)

1. Ease of understanding: Since the pseudocode is programming language independent, novice


developers can also understand it very easily.
2. Focus on logic: A pseudocode allows you to focus on the algorithm's logic without bothering about
the syntax of a specific programming language.
3. More legible: Combining programming constructs with English phrases makes pseudocode more
legible and conveys the logic precisely.
4. Consistent: As the constructs used in pseudocode are standardized, it is useful in sharing ideas
among developers from various domains.
5. Easy translation to a program: Using programming constructs makes mapping the pseudocode to a
program straightforward.
6. Identification of flaws: A pseudocode helps identify flaws in the solution logic before
implementation.

Q21. Guidelines for writing Pseudocode: (Part -A)

This is a set of simple rules for writing pseudocode clearly:

 Write one statement per line: Each step of the algorithm should be on a new line for clarity.

 Capitalize initial keyword: Start control words like IF, ELSE, WHILE, FOR in uppercase to make them
stand out.

 Indent to hierarchy: Use indentation to show which steps belong inside loops, conditions, or other
blocks.

 End multiline structure: Close blocks with words like ENDIF, ENDWHILE, or ENDFOR so the flow is easy
to follow.

 Keep statements language independent: Do not use exact programming language syntax, just general
instructions.

Q22. List and explain Common Keyword used in pseudocodes: (Part -B )

The following gives common keywords used in pseudo codes.

1. THIS keyword is used to represent a comment.


2. BEGIN_END: Begin is the first statement and end is the last statement.
3. START_STOP: START is the first statement, STOP is the last statement.
4. INPUT, GET, READ: The keyword is used to inputting data.
5. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
6. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
7. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
8. IF, ELSE, ENDIF: used to make decision.
9. WHILE, ENDWHILE: used for iterative statements.
[Link], ENDFOR: Another iterative incremented/decremented tested automatically.

Q23. Write the Advantages and Disadvantages of Pseudocodes : (Part _B)

Advantages:

 Pseudo is independent of any language; it can be used by most programmers.

 It is easy to translate pseudo code into a programming language.

 It can be easily modified as compared to flowchart.

 Converting a pseudo code to programming language is very easy as compared with


converting a flowchart to programming language.

Disadvantages:
 It does not provide visual representation of the program’s logic.

 There are no accepted standards for writing pseudo codes.

 It cannot be compiled nor executed.

For a beginner, It is more difficult to follow the logic or write pseudo code as compared to
flowchart.

Q24. Write Pseudocode code for the expression d=a+b*c : (Part-A)

1 . BEGIN
2 . READ (a,b,c)
3 . COMPUTE d=a+b∗c
4 . PRINT(d)
5 . END
[Link] Pseudocode code for adding two numbers : (Part-A)

[Link] and explain main Constructs of Pseudocode : (Part-B)

Constructs are the building blocks used to express the logic and flow of a computer program or algorithm.
There are three programming constructs that allow for linear control flow. These are also known as single entry –
single exit constructs.

[Link] 2. Selection and 3. Repetition(loop)


1. Sequence Construct:-
• This is the most elementary construct where the instructions of the algorithm are executed in the order
listed. It is the logical equivalent of a straight line.
• The logic flow of Pseudocode is from top to bottom.

• Consider the code below: Pseudocode for expression: d=a+b*c


START
READ (a,b,c)
COMPUTE d=a+b*c
PRINT(d)
STOP
The statement 1 is executed first, which is then followed by statement 2, so on and so forth, Statement n until
all the instructions are executed. No instruction is skipped and every instruction is executed only once.

2. Decision or Selection Constructs :-


• A selection structure consists of a test condition together with one or more blocks of statements.
• The result of the test determines which of these blocks is executed.
• There are mainly two types of Selection Structure:-
A. IF structure:-
• There are three variations of the if-structure:
A.1 IF structure:
• The general form of this structure is:
IF (condition)
true _instructions
ENDIF
If the test condition is evaluated to True, the statements denoted by true_ instructions are executed. Otherwise,
those statements are skipped. Example for IF is given below:
[Link] a Pseudocode to check the given input value a is positive .

Example2: Write a Pseudocode to -Find the biggest of Two numbers:

A.2 IF ELSE structure: The general form is given below:

IF (condition)
true_instructions
ELSE
false_instructions
ENDIF
This structure contains two blocks of statements. If the test condition is met, the first block (denoted by
true_instructions) is executed and the algorithm skips over the second block (denoted by false_instructions). If
the test condition is not met, the first block is skipped and only the second block is executed.

Example: Write a Pseudo-code to check the given input value is positive or negative.

A3. IF ELSE IF Structure :-When a selection is to be made out of a set of more than two possibilities,
you need to use the IF ELSE IF structure, whose general form is given below.

IF (condition1)
true_instructions1
ELSE IF (condition2)
true_instruction2
ELSE false_instructions
ENDIF
Here, if condition is met, TRUE_INSTRUCTIONS1 will be executed. Else condition2 is checked.
If it evaluates to TRUE, TRUE_INSTRUCTIONS2 will be selected. Otherwise
FALSE_INSTRUCTIONS will be [Link] is no limit to the number of else if statements,
but in the end, there has to be an else statement. The conditions are tested one by one
starting from the top, proceeding downwards. Once a condition is evaluated to be True, the
corresponding block is executed, and the rest of the structure is skipped. If none of the
conditions are met, the final else part is executed.

Example: : Write a Pseudo-code to, Find the biggest of three numbers:

START
READ a, b, c
IF a>b AND a>c THEN
Big=a
ELSE IF b>a AND b>c THEN
Big=b
ELSE Big=c
ENDIF
PRINT(Big)
B. Case Structure

The case structure is a refined alternative to if else if else structure. The pseudo-code representation of
the case structure is given below.

The general form of this structure is:

caseof (expression)

case value₁:
BLOCK₁

case value₂:
BLOCK₂

...

default:
DEFAULT_BLOCK

endcase

The case structure works like this: First, the value of expression (you can also have a single variable in the place
of expression) is compared with value₁. If there is a match, the first block of statements denoted as BLOCK₁ will be
executed. Typically, each block will have a break at the end which causes the case structure to be exited.
If there is no match, the value of the expression (or of the variable) is compared with value₂. If
there is a match here, BLOCK₂ is executed and the structure is exited at the corresponding break statement. This
process continues until either a match for the expression value is found or until the end of the cases is
encountered.

The DEFAULT_BLOCK will be executed when the expression does not match any of the cases.
If the break statement is omitted from the block for the matching case, then the execution continues into
subsequent blocks even if there is no match in the subsequent blocks, until either a break is encountered or the
end of the case structure is reached.

Example: The pseudocode Print Direction(dir) prints the direction name based on the value of a character called dir.
1. START
2. READ dir
3. CASEOF(dir)
4. CASE ’N’ :
5. PRINT(“NORTH”)
6. BREAK
7. CASE ’S’ :
8. PRINT(“SOUTH”)
9. BREAK
10. CASE ’E’ :
11. PRINT(“EAST”)
12. BREAK
13. CASE ’W’ :
14. PRINT(“WEST”)
15. BREAK
16. DEFAULT:
17. PRINT(“Invalid direction code”)
18. ENDCASE
[Link] or loop Constructs:-
A loop is used when we want to repeat a block of instructions. Each repetition is called an iteration or a pass.

 If we know how many times the block will repeat, it is called definite iteration.
 If we do not know the exact number of times and the loop runs until a condition is met, it is called
indefinite (or conditional) iteration.
 The repeated part of the loop is called the loop body.
There are three main types of loops used in pseudocode.

1. WHILE
2. REPEAT UNTIL
3. FOR
1 . WHILE loop: -
WHILE loop is generally used to implement indefinite iteration. The general form of the while loop is as follows:

WHILE (condition)
True instructions
ENDWHILE

Here, the loop body (TRUE_INSTRUCTIONS) is executed repeatedly as long as the condition
evaluates to TRUE. When the condition is evaluated as FALSE, the loop body is bypassed.
Example: Algorithm(pseudocode) using while Constructs:
Display Numbers 1 to 50

[Link].
2 SET I = 1
3. WHILE I<= 50
4. DO PRINT(I)
5. SET I =I + 1
6. END WHILE
[Link]

2. REPEAT UNTIL loop:


The repeat-until loop is used when we do not know how many times the block will repeat. The loop body keeps
running until the condition becomes True. As long as the condition is False, the loop continues.

Pseudocode form:

REPEAT

instructions

UNTIL (condition)
Example: Algorithm(pseudocode) using while Constructs:
Counting down from 50.
[Link].
2 SET I = 50
3. REPEAT
4. PRINT(I)
5. SET I=I-1
6. UNTIL I<1
7. END WHILE
[Link] (CONT DOWN COMPLETE)
[Link]

Difference between while and repeat-until loop constructs:(Part A)

There are two major differences between while and repeat-until loop constructs:

1. In the while loop, the pseudocode continues to execute as long as the resultant of the condition is
True; in the repeat-until loop, the looping process stops when the resultant of the condition becomes
True.

[Link] the while loop, the condition is tested at the beginning; in the repeat-until loop, the condition is
tested at the end. For this reason, the while loop is known as an entry controlled loop and the repeat-
until loop is known as an exit controlled loop.
You should note that when the condition is tested at the end, the instructions in the loop are executed at
least once.

3. FOR LOOP:
The FOR loop is used when we know exactly how many times we want to repeat a block, so it is called definite
iteration.

 It uses a loop variable (counter) that starts from a given value (begin).
 After each repetition, the loop variable is updated automatically.
 The loop continues until the variable reaches the end value.
The first type of FOR loop can be written like this in pseudocode:

FOR variable = begin TO end

instructions

ENDFOR
In this loop, the loop variable (var) starts with the value begin.

 The condition var <= end is checked.

 If the condition is True, the loop body runs.

 After each run, the value of var increases by 1.

 The condition is checked again with the new value of var.

 This keeps repeating until var becomes greater than end.

 When the condition is False, the loop stops.

Example: To print the numbers from 1 to 50 in ascending order

[Link]
2. FOR I=1 TO 50
3 .PRINT I
4. ENDFOR
[Link]
Variant2: In the second for loop variant, whose pseudocode syntax is given below,

Pseudocode form:

FOR var = begin DOWNTO end


instructions
ENDFOR

The second type of FOR loop counts downward instead of upward.

 The loop variable starts from begin.


 After each iteration, the variable is decreased by 1.
 The loop continues as long as var >= end.
 Once the variable becomes less than end, the loop stops.
 For this loop to work, begin must be greater than or equal to end.
Example: To find the factorial of a number n.

FACTORIAL
START
READ(n)
fact = 1
FOR var = n DOWNTO 1
fact = fact * var
ENDFOR
PRINT(fact)
STOP

Varient 3:-

It is possible to change the loop variable by more than 1 after each iteration. The amount by which the
loop variable increases or decreases is called the step. In pseudocode, the step value is written using
the keyword BY.

FOR VAR = INITIAL_VALUE TO FINAL_VALUE BY STEP

LOOP_INSTRUCTIONS

ENDFOR
Example: To print the odd numbers to 50 .
[Link]
2. FOR I=1 TO 50 BY 2
3 PRINT I
4. ENDFOR
[Link]

Loop examples:
[Link] Flowchart .List and explain various symblos used (Part -A )
A flowchart is a diagrammatic representation of an algorithm that depicts how control flows in it. Flowcharts are
composed of various blocks interconnected by flow-lines. Each block in a flowchart represents some stage of
processing in the algorithm. Different types of blocks are defined to represent the various programming
constructs of the algorithm.
[Link] find the simple interest : Write the Algorithm and Draw the flow chart

[Link] Display the larger of two numbers

[Link] determine the smallest of three numbers: (Part-B)


Q31. To determine the entry-ticket fare in a zoo based on age as follows: (Part-B)
Q32. To print the colour based on a code value as follows: (Part-B)
Q33.. To print the numbers from 1 to 50 in descending order. (Part-B)

Q34. To find the factorial of a number. (Part-B)


Q35. To determine the largest of n numbers: (Part-B)

Q36. To determine the average age of students in a class. The user will stop giving the input by giving the age as 0. (Part-B)
[Link] determine the average age of students in a class. The user will stop giving the input by giving the age as
0. Redo the problem with REPEAT UNTIL loop construct. (Part-B)
KTU December 2024 – University Exam Questions

Q38. You are asked to solve a jigsaw puzzle without a reference picture. How will you solve it using trial
and error method?

Solving a jigsaw puzzle without a reference picture is more challenging, but it can be accomplished through a
systematic trial and error method that relies on the shapes, colors, and patterns of the pieces.

To solve a jigsaw puzzle without a reference picture using the trial and error method, the approach involves
systematic experimentation and logical deduction:

 Start by sorting all pieces and separate edge and corner pieces.
 Assemble the border (edges) first by matching pieces that have flat sides.
 Group the remaining pieces by shape and connector types (e.g., tabs and blanks).
 Try fitting pieces together based on shape compatibility, such as fitting a tab into a blank slot.
 Assemble small clusters of pieces that fit well together by trial and error.
 Connect small clusters logically to the border or to each other by testing all possible fits.
 If pieces don’t fit, try a different orientation or a different nearby piece.
 Keep trying combinations, rotating pieces if needed, and expanding connected regions.
 Take breaks when stuck, then retry from a fresh perspective.
 Continue until all pieces logically fit with no contradictions.
This method relies on repeatedly trying to fit pieces, observing which fit and which do not, and gradually building
larger and correct sections until the puzzle is complete, even without any visual reference to the completed image.
It’s a process of trial, error, and discovery using piece shape and fit alone.
[Link] are a software engineer working on a security application for a company that handles sensitive
user data. The application has a 4-digit numeric password system for authentication. However, due to a
system error, a user has forgotten their password. Write an algorithm for recovering the 4-digit numeric
password

 Start with the guess "0000".


 Check if the guess matches the password:
o If yes, stop and return the guess.
o If no, add 1 to the guess.
 Repeat step 2 with the new guess.
 Keep guessing numbers ("0001", "0002", "0003", ...) until "9999".
 When the correct password is found, print it and stop.
This repeats guessing passwords from 0000 to 9999 until the right one is found.

[Link] how backtracking strategy can be applied to solve Sudoku problem?


Backtracking is a systematic trial-and-error strategy to solve the Sudoku puzzle by trying to fill empty cells one by
one and reverting steps if conflicts arise. Here's how backtracking works in Sudoku:
 Find an empty cell in the 9x9 grid.
 Try placing digits from 1 to 9 in that cell one by one.
 After placing a digit, check if it violates Sudoku rules (duplicate number in the same row, column, or 3x3
sub-box).
 If no rule is violated, move on to the next empty cell and repeat.
 If all digits (1 to 9) cause conflicts in a cell, backtrack:
o Remove the digit placed in the previous cell.
o Try a different digit in that previous cell.
 Continue this process recursively until all cells are filled correctly or until it is determined that no solution
exists.
Backtracking explores potential solutions depth-first, and if it reaches a dead end, it reverses (backs up) to try
alternate choices. This guarantees finding a solution if one exists.

[Link] college is located in a metropolitan city and you are new to that city. You would like to go out
for dinner with your friends. Explain how heuristics approach can be used to find the best restaurant for
dinner.

Heuristics can be used to find the best restaurant for dinner in a metropolitan city by applying simple rules or
shortcuts to make quick decisions without exhaustive analysis. Here's how a heuristic approach might work:

1. Set Criteria: Identify the key factors that matter most, such as distance from college, cuisine preference,
price range, ratings, and ambiance.

2. Filter Options: Quickly eliminate restaurants that don't meet essential criteria (e.g., too far away or outside
budget).

3. Rank Based on Key Factors: Use a simplified scoring system where restaurants get points based on
positive attributes like higher ratings, closer distance, and preferred cuisine.

4. Prioritize Convenience: Choose restaurants that are easy to reach or nearby to save travel time.

5. Use Social Proof: Give preference to restaurants with good online reviews or recommendations from friends.

6. Make a Quick Choice: From the top candidates, select the one that best balances all the prioritized criteria
without trying to analyze every option deeply.

This heuristic approach helps quickly narrow down and select a good restaurant without needing to compare every
possible option in detail, saving time and effort while still making a reasonable choice.

[Link] are a software developer working on a data analysis tool for a logistics company. The company has a
list of delivery times, where each entry represents the time taken (in minutes) for a particular delivery. The team
needs to identify delivery times that are divisible by 6 (as they are considered optimal delivery durations) but not
divisible by 4 (as they tend to involve more complexity in scheduling). Write an algorithm to print the delivery
times that are divisible by 6 but not divisible by 4 from a given set of delivery times.

[Link].
[Link] the list of numbers.
3. For each number in the list:
If the number is divisible by 6 but not by 4, print the number.
[Link].

[Link] are developing a feature for a business analytics tool that processes a list of sales figures for a company.
As part of the analytics, the tool must identify the highest and lowest sales figures from the provided data. Write
the pseudocode to determine the largest and smallest numbers in a given list of N numbers, ensuring the
solution is efficient for real-world applications.

Algorithm FindMinMax(sales_list):
1. Set max_val = first number in sales_list
2. Set min_val = first number in sales_list
3. For each number in sales_list starting from the second:
a. If number > max_val, set max_val = number
b. If number < min_val, set min_val = number
4. Return max_val and min_val
This method checks each number once and updates the maximum and minimum values as it goes.

[Link] the pseudocode to calculate the factorial of a given number using a for loop.
Algorithm CalculateFactorial(n):
1. Set fact = 1
2. For i = 1 to n:
fact = fact * i
3. Print fact

KTU MAY 2025– University Exam Questions

[Link] the most suitable problem-solving strategies for the following use cases. Justify your answer:
i) You are solving a complex Sudoku puzzle and are unsure how to proceed as you approach the final few cells.
ii) You are tasked with planning a family trip that involves selecting a destination, booking flights, and finding
accommodation within a budget.

Here are the most suitable problem-solving strategies for the use cases:

i) Complex Sudoku Puzzle (near final cells):

Strategy: Backtracking
Justification: Backtracking is ideal for puzzles like Sudoku where you need to try different possibilities for the
remaining cells. It works by placing a number in a cell, then recursively trying to solve the rest of the puzzle. If a
conflict arises later, it backtracks to try a different number. This systematic trial and error guarantees finding a
solution if one exists.

ii) Planning a Family Trip (selecting destination, flights, accommodation within budget):

Strategy: Heuristic Approach


Justification: Planning a trip involves multiple factors such as preferences, budgets, and availability. A heuristic
approach lets you quickly narrow down choices by applying simple rules (e.g., choose destinations within budget,
prioritize convenient flights, filter accommodations by rating). It helps make reasonable decisions efficiently
without exhaustively comparing every option.
Q46. You visit a shop to buy a new mobile. In connection with the festive season,the shop offers a 10% discount
on all mobiles. In addition, the shop also gives a flat exchange price of 1000 for old mobiles. Draw a flowchart to
input the original price of the mobile and print its selling price. Note that all customersmay not have an old mobile
for exchange.
1. Start

2. Input original price (OP)

3. Input whether the customer has an old mobile for exchange (Yes/No)

4. Calculate discount price = OP * 0.9 (10% discount)

5. If customer has old mobile:

o Selling price = discount price - 1000


Else:

o Selling price = discount price

6. Print selling price

7. End

[Link] pseudo code to determine the average age of students in a class. The user will stop giving the
input by giving the age as 0
Start
Set sum = 0
Set count = 0
Loop:
Input age
If age == 0:
Exit loop
Add age to sum
Increment count by 1
Repeat Loop
If count > 0:
average = sum / count
Print average
Else:
Print "No ages entered"
End

[Link] the three sides of a triangle are input, write an algorithm/pseudo code to check whether the triangle
is isosceles, equilateral, or scalene.
Start
Input side1, side2, side3
If (side1 == side2) AND (side2 == side3)
Print "Equilateral triangle"
Else If (side1 == side2) OR (side2 == side3) OR (side1 == side3)
Print "Isosceles triangle"
Else
Print "Scalene triangle"
End

[Link] is the difference between algorithms and heuristics in problem-solving?Provide an example


where heuristics lead to a faster solution than an algorithm
The main difference between algorithms and heuristics in problem-solving is that algorithms provide a guaranteed,
step-by-step procedure that leads to the correct solution, while heuristics use practical, experience-based shortcuts
or rules of thumb that produce faster, but not always guaranteed, approximate solutions.

Algorithms are comprehensive and methodical but can be time-consuming and computationally intensive.
Heuristics save time and mental effort but may sometimes lead to incorrect or sub optimal solutions.

An example where heuristics lead to a faster solution than an algorithm is the "travelling salesman problem" (TSP).
The algorithmic approach requires checking every possible route to find the shortest path—this guarantees the
optimal solution but is very slow due to the huge number of possibilities.
A heuristic, such as choosing the nearest neighbor city at each step, can quickly produce a good (though not
guaranteed optimal) route, making the solution process much faster.

[Link] an algorithem to convert the time input in minutes to hours and minutes. For example, 85
minutes is 1 hour 25 minutes.

Algorithm: Convert Minutes to Hours and Minutes

1. Start.
2. Read the input number of minutes (total_minutes).
3. Calculate the number of hours by dividing total_minutes by 60:
hours = total_minutes ÷ 60 (integer division).
4. Calculate the remaining minutes by finding the remainder of total_minutes divided by 60:
minutes = total_minutes mod 60.
5. Display the result in the format: "X minutes is H hour(s) and M minute(s)."
6. Stop.
This algorithm uses simple division and modulus operations to separate the total minutes into hours and the
leftover minutes. For example, if total_minutes = 85, then:

 hours = 85 ÷ 60 = 1
 minutes = 85 mod 60 = 25
So, 85 minutes is 1 hour and 25 minutes.

[Link] Algorithm to implement a grading system based on the following conditions.

• Marks ≥ 90: Grade A


• Marks 80–89: Grade B
• Marks 70–79: Grade C
• Marks 60-70: Grade D
• Marks 50-69: Grade E
• Marks < 50 : Grade F
• If the difference between the marks and the next multiple of 10 is
less that 3, then convert it to next grade.
• If the marks are below 50, no need to convert even if the difference
is less than 3

1. Start

2. Input marks

3. If marks < 50, then


3.1 Set grade = "F"

4. Else
4.1 Calculate difference = 10 - (marks mod 10)
4.2 If difference < 3, then
4.2.1 marks = marks + difference // Round up to next multiple of 10
4.3 If marks >= 90, then grade = "A"
4.4 Else if marks >= 80, then grade = "B"
4.5 Else if marks >= 70, then grade = "C"
4.6 Else if marks >= 60, then grade = "D"
4.7 Else if marks >= 50, then grade = "E"

5. Output grade

6. Stop

END
*********************************************************************

You might also like