BCA C Programming Unit 1 Introduction To Algorithm
BCA C Programming Unit 1 Introduction To Algorithm
Introduction to
Algorithm
SELF LEARNING MATERIAL
SEM - I (102)
BCA
UNIT-1 INTRODUCTION TO ALGORITHM
TABLE OF CONTENTS
1.1 Introduction
1.2 Concept of Problem, Procedure and Algorithm
1.3 Algorithm Representation using Pseudo Code
1.4 Algorithm Representation using Flowchart
1.5 Proving Algorithm Correctness using Inductive Proof
and Loop Invariant
1.6 Tracing of Swapping Algorithm
1.7 Tracing of Counting Algorithm
1.8 Trace of Algorithms to Find Sum, Product, Min, Max of List
1.9 Summary
1.10 Case Study
1.11 Terminal Questions
1.12 Answers
1.13 Assignment
1.14 References
Learning Objectives
• To define the concept of Algorithm
• To understand differentways of representing Algorithm
• To create trace table of Algorithms
NOTES
1.1
Introduction
Algorithms are the backbone of modern computing, serving as step-by-step
instructions for solving problems efficiently and reliably. They are like a set
of carefully crafted recipes that guide computers to perform complex tasks,
from sorting data to searching for information. Understanding algorithms
helps to gain the ability to design solutions that can handle massive
amounts of data and execute computations at remarkable speeds. Whether
it’s finding the shortest path in a network or predicting stock market trends,
algorithms play a crucial role in shaping the technological landscape we
interact with every day.
Resource
Problem Solving Automation Data Processing
Management
1.2
Concept of Problem,
Procedure and Algorithm
Before starting with the concept of algorithms, it is important to understand the
concept of problem and procedure.
Problem:
A problem refers to a specific task or challenge that needs to be solved using
computational methods. Problems can vary in complexity and scope, ranging from
simple arithmetic calculations to more intricate issues like network optimization or
data analysis.
02
When approaching a problem, it is essential to identify the input, output, and
constraints associated with it.
NOTES
● The input represents the data or information provided to the algorithm, which
serves as the foundation for finding a solution.
● The output is the desired result or outcome that the algorithm should produce.
● Constraints outline any limitations or conditions that the algorithm needs to
adhere to while solving the problem.
Procedure:
A procedure refers to a sequence of well-defined steps or instructions that describe
how to solve a particular problem. It is a set of actions that need to be executed
in a specific order to accomplish a desired outcome. Procedures serve as the
building blocks of algorithms, allowing us to break down complex problems into
manageable and executable steps.
For example, let’s consider the problem of finding the maximum number in a given
list. A possible procedure to solve this problem could be a function called
“findMaximum” that takes in a list of numbers as input and returns the maximum
value. This procedure can be further divided into smaller steps such as initializing a
variable to store the maximum value, iterating through the list to compare each
element with the current maximum, and updating the maximum value if a larger
element is found.
03
NOTES How algorithm differ from procedure:
Algorithms differ from procedures in that they encompass a broader scope. While a
procedure is a specific set of instructions for accomplishing a particular task within
an algorithm, an algorithm refers to the overall methodology or strategy employed
to solve a problem. An algorithm may consist of multiple procedures or subroutines
working together to achieve the desired goal.
Activity
Suppose a company wants to automate their employee attendance tracking
system. Analyze what would be the problem, procedure, and algorithm in this
scenario.
1.3
Algorithm representation Using
Pseudo-code
These steps in pseudocode clearly describes the logic of the algorithm in natural
language.
05
NOTES CHECK YOUR PROGRESS
4. Pseudocode allows programmers to focus on the ___________ and
___________ of an algorithm
5. Pseudocode is not meant to be ___________ by a computer but serves as
a communication tool between the programmer and others involved in the
development process.
6. Pseudocode focuses on the syntax details of a specific programming
language.[True/False]
1.4
Algorithm Representation Using
Flow-charts
06
Shape used for Input/Output Symbol is Parallelogram
NOTES
● Connector Arrows: Arrows connect the various symbols in a flowchart,
indicating the flow and sequence of steps. Arrows typically point from one
symbol to another, following the logical progression of the algorithm.
For example, the flowchart for the pseudocode discussed in the last section
will look like as below:
Start
End
07
NOTES CHECK YOUR PROGRESS
7. Flowcharts are a static representation and cannot handle dynamic inputs or
changing conditions during execution. [True/False]
8. The arrows in a flowchart can be labeled with ________ to indicate the values
that determine the flow
9. Which symbol of the flowchart will be used for the following tasks.
a) Check if temperature is above or below a certain threshold.
b) Ask the user for their name
c) Perform a mathematical calculation
Activity
Design a flowchart that represent your regular daily routine. The flowchart should
depict the sequence of actions or activities you take from the moment you
wake up and go to bed. Brainstorm and try to incorporate all the decision points
involved in your day. As an example, if you have lab class on that particular day,
you attend the lab. Else you go for gym.
1.5
Proving Algorithm Correctness Using
Inductive Proofs and Loop Invariant
Inductive Proof
When designing and implementing algorithms,
it is important to ensure their correctness. One
STUDY NOTE
approach to establishing the correctness of an
algorithm is through the use of inductive proofs. Inductive proof of
algorithms is based
Inductive proofs are a mathematical technique on the principle of
used to demonstrate that an algorithm works mathematical induction
correctly for all possible inputs. By following a which is a powerful
logical step-by-step reasoning process, inductive reasoning technique in
proofs help verify that an algorithm consistently mathematics.
produces the desired output.
08
Inductive NOTES
Basis Step Inductive Step Conclusion
Hypothesis
1. Basis Step: The first step in an inductive proof is establishing the base case.
This involves showing that the algorithm works correctly for the smallest or
simplest input. It serves as the foundation for the subsequent steps.
2. Inductive Hypothesis: The next step is to assume that the algorithm works
correctly for a particular input of size k. This assumption is called the inductive
hypothesis.
3. Inductive Step: In this step, you prove that if the algorithm works correctly
for an input of size k, it will also work correctly for an input of size k+1. This
step typically involves demonstrating that the algorithm preserves the desired
properties or outcomes during each iteration or recursion.
4. Conclusion: By combining the basis step, the inductive hypothesis, and the
inductive step, you can conclude that the algorithm is correct for all possible
inputs.
Example:
Let’s consider the problem of summing the first n positive integers using the
algorithm. The pseudocode for the problem is given below:
1. Declare variables sum, N
2. OUTPUT ‘Enter the value of N’
3. INPUT N
4. Initialize sum=0
5. Initializei=0
6. Repeat step 7 and 8 till i<N
7. SET sum = sum + i
8. i=i+1
9. OUTPUT sum
Inductive Hypothesis: Assume the algorithm works correctly for an input of size k.
Inductive Step: If the algorithm works correctly for an input of size k, adding (k+1)
to the sum will give the correct sum of the first (k+1) positive integers.
Conclusion: Based on the basis step and the inductive step, we can conclude that
the algorithm correctly calculates the sum of the first n positive integers for any
value of n.
09
NOTES Loop invariant:
Another approach to proving the correctness of an algorithm is through the use of
loop invariants. Loop invariants are logical properties or conditions that hold true
before and after each iteration of a loop. By identifying and verifying loop invariants,
it is possible to demonstrate that an algorithm works correctly and maintains its
desired properties throughout the execution.
1. Initialization: The first step in using loop invariants is to establish the loop
invariant property. This involves demonstrating that the invariant holds true
before the loop starts, usually at the initialization of loop variables.
2. Maintenance: The next step is to prove that if the invariant holds true before an
iteration, it remains true after the iteration. This step ensures that the algorithm
maintains its desired properties during each iteration of the loop.
3. Termination: Finally, we prove that when the loop terminates, the invariant still
holds true. This step ensures that the algorithm produces the expected output
after completing all iterations of the loop.
Example:
Consider the same example used for the inductive proofs. The pseudocode for the
problem is given below:
1. Declare variables sum, N
2. OUTPUT ‘Enter the value of N’
3. INPUT N
4. Initialize sum = 0
5. Initialize i = 0
6. Repeat step 7 and 8 till i<N
7. SET sum = sum + i
8. i=i+1
9. OUTPUT sum
1.6
Tracing of Swapping Algorithm
The process of tracing typically involves examining the values of variables and data
structures at different points in the algorithm’s execution. By carefully observing
and tracking the changes in these values, programmers can gain a deeper
understanding of how the algorithm progresses and how data is transformed.
Benefits of Tracing:
● Debugging: Tracing allows programmers to identify and resolve errors or bugs
in their code by examining variable values and tracking their changes during
execution.
● Algorithm Analysis: Tracing helps in understanding the efficiency and
performance of algorithms by analysing the number of iterations, comparisons,
or operations performed.
11
NOTES ● Learning Tool: Tracing is an effective learning tool that helps students
comprehend how algorithms work, improve their problem-solving skills, and
gain insights into programming concepts.
● Optimization: Tracing aids in identifying areas of improvement within an
algorithm, allowing programmers to optimize code and enhance its efficiency.
Trace Tables:
Trace tables are a systematic and organized way to track the changes in variables
and their values during the execution of an algorithm. They provide a visual
representation of how the algorithm progresses.
Swapping algorithm:
Problem: Given two variables, ‘variable_1’ and ‘variable_2’, the goal is to swap their
values such that ‘variable_1’ holds the original value of ‘variable_2’ and ‘variable_2’
holds the original value of ‘variable_1’. The task is to design an algorithm that
accomplishes this swap efficiently and correctly.
Let’s trace the above algorithm to check if it gives correct output. Suppose user
enters the value variable_1 as 10 and variable_2 as 20.
Starting the trace table from Line number 5, after the execution of this line, the
variables hold the following values
12
Line number 8 set the value of variable_1 to variable_2
NOTES
Line Number variable_1 variable_2 temp_variable
5 10 20 0
6 10 20 10
7 20 20 10
At last, the program outputs the value of variable_1 as 20 and variable_2 as 10. The
value of the variables is swapped.
Activity
Write pseudocode for the following problem:
Problem: Given two variables, ‘variable_1’ and ‘variable_2’, the goal is to swap
their values such that ‘variable_1’ holds the original value of ‘variable_2’ and
‘variable_2’ holds the original value of ‘variable_1’ without using any other variable.
Trace the algorithm step-by-step and analyse if the algorithm written by you gives
the correct output. If not, debug your algorithm using trace table.
1.7
Tracing of Counting Algorithm
Consider the following problem of counting to understand tracing of algorithm in
a better way.
Problem: Consider a list of whole numbers given to you. Design an algorithm that
counts the occurrence of number ‘0’ in the list and display the count.
13
NOTES Let’s assume the list of numbers as [23, 45, 0, 12, 13, 0, 56, 78, 90, 0] and list[i]
denotes the value at the ith position in the list. The variable N denotes the total
number of elements in the list, which is equal to 10.
Let’s trace the above algorithm to check if it gives correct output. The given list is
[23, 45, 0, 12, 13, 0, 56, 78, 90, 0] where list[1]= 23, list[2]=45, list[3]=0, list[4]=12,
and so on.
After the execution of line number 3, the variables hold the following values:
i=1
count=0
The value of i becomes greater than 10 and after this the algorithm executes is line
number 7. It prints the value of variable count which hold the number of occurrence
of 0 in the given list. The algorithm prints value 3, which is true.
14
1.8 NOTES
Tracing Algorithm to Find Sum, Product,
Minimum and Maximum of List
Let’s trace the above algorithm to check if it gives correct output. The given list
is [67, 45, 90, 12, 43, 89, 56, 95, 10, 34] where list[1]= 67, list[2]=45, list[3]=90,
list[4]=12, and so on.
After the execution of line number 3, the variables hold the following values:
i=1
sum=0
15
NOTES The value of i becomes greater than 10 and after this the algorithm executes is line
number 7. It prints the value of variable sum which hold the sum of all the values in
the given list. The algorithm prints value 541.
Let’s trace the above algorithm to check if it gives correct output. The given list is
[2, 12, 5, 8, 9, 4, 2, 1, 3, 2] where list[1]= 2, list[2]=12, list[3]=5, list[4]=8, and so on.
After the execution of line number 3, the variables hold the following values:
i=1
product=0
After this the algorithm executes is line number 7. It prints the value of variable
product, which is 414720.
16
1.8.3 Find minimum of a list of numbers
NOTES
Problem: Consider a list of whole numbers [67, 45, 90, 12, 43, 89, 56, 95, 10, 34]
and list[i] denotes the value at the ith position in the list. The variable N denotes the
total number of elements in the list, which is equal to 10. Design an algorithm that
finds the minimum value of all the values present in the list
Let’s trace the above algorithm to check if it gives correct output. The given list
is [67, 45, 90, 12, 43, 89, 56, 95, 10, 34] where list[1]= 67, list[2]=45, list[3]=90,
list[4]=12, and so on.
After the execution of line number 3, the variables hold the following values:
i=2
min=67
The value of i becomes greater than 10 and after this the algorithm executes is
line number 7. It prints the value of variable min which hold the minimum of all the
values in the given list. The algorithm prints value 10.
17
NOTES 1.8.4 Find maximum of a list of numbers
Problem: Consider a list of whole numbers [67, 45, 90, 12, 43, 89, 56, 95, 10, 34]
and list[i] denotes the value at the ith position in the list. The variable N denotes the
total number of elements in the list, which is equal to 10. Design an algorithm that
finds the maximum value of all the values present in the list
Let’s trace the above algorithm to check if it gives correct output. The given list
is [67, 45, 90, 12, 43, 89, 56, 95, 10, 34] where list[1]= 67, list[2]=45, list[3]=90,
list[4]=12, and so on.
After the execution of line number 3, the variables hold the following values:
i=2
max=67
The value of i becomes greater than 10 and after this the algorithm executes is line
number 7. It prints the value of variable max which hold the maximum of all the
values in the given list. The algorithm prints value 95.
18
CHECK YOUR PROGRESS NOTES
17. Identify what will be the output of the algorithm ‘Finding product of a list of
number’ if the step ‘Initialize product to 1’ is changed to ‘Initialize product to
0’?
18. Why the loop count is 1 less in algorithm ‘Finding sum of a list of number’
than in ‘Finding minimum of a list of number’?
19. Is there a way to achieve the same output by initializing the value of min to
0 instead of list[1]? If so, what change should be made in the pseudocode
and why this approach works?
Activity
Consider the following scenario:
You are given a list of numbers representing the scores of students in a class.
Your task is to design an algorithm that calculates the average score of the
students in the class.
● The list of numbers represents the scores of 10 students in a class.
Write the pseudocode for the algorithm. Trace the algorithm and check if it gives
correct output.
1.9
Summary
1.10
Case Study
21
NOTES Through the strategic use of pseudocode, the Indian IT company successfully
developed and deployed an optimized data processing algorithm for the e-commerce
platform.The pseudocode provided a structured approach to designing the algorithm,
resulting in faster data processing, enhanced scalability, accurate insights, and
cost efficiency. The successful implementation of this pseudocode-based solution
showcased the company’s expertise in leveraging algorithmic approaches to drive
data-driven decision-making in the IT industry.
Questions:
1. Analyse the role of pseudocode in optimizing the data processing algorithm for
the e-commerce platform. How did the use of pseudocode contribute to the
efficiency and performance improvements?
2. Evaluate the importance of collaboration between the IT company’s team, data
scientists, and domain experts in designing the pseudocode algorithm. How
did this collaboration enhance the effectiveness of the algorithm?
3. Critically assess the significance of testing and validation in the implementation
of the pseudocode-based data processing algorithm. How did the testing
process ensure the algorithm’s accuracy, scalability, and performance?
1.11
Terminal Questions
22
MCQ QUESTIONS
NOTES
1. Which of the following best describes an algorithm?
a) A step-by-step procedure for solving a problem.
b) A visual representation of a program’s execution flow.
c) A programming language used to write code.
d) A graphical representation of data elements and their relationships.
2. Which of the following is a benefit of using pseudocode?
a) It allows for the execution of code.
b) It provides a visual representation of a program’s flow.
c) It is a programming language used to write code.
d) It helps in planning and understanding the logic of an algorithm.
3. When applying inductive proofs, which of the following is the correct order of
steps?
a) Base case, induction hypothesis, inductive step.
b) Induction hypothesis, base case, inductive step.
c) Inductive step, base case, induction hypothesis.
d) Base case, inductive step, induction hypothesis.
4. What is the purpose of tracing an algorithm?
a) To write code using a specific programming language.
b) To identify errors and bugs in the algorithm.
c) To create a visual representation of the algorithm.
d) To convert the algorithm into pseudocode.
5. Which of the following is a component of a trace table?
a) Pseudocode b) Flowchart
c) Input values d) Programming language
6. In a flowchart, what does a diamond-shaped symbol represent?
a) Start or end of the program b) Decision point or condition
c) Input or output operation d) Process or operation
7. In the context of loop invariants, which of the following statements is true?
a) A loop invariant is a condition that holds true before the loop starts.
b) A loop invariant is a condition that holds true after the loop terminates.
c) A loop invariant is a condition that holds true only during the execution of
the loop.
d) A loop invariant is a condition that is not affected by the loop iterations.
8. Which of the following is true about flowcharts?
a) They are written in a specific programming language.
b) They provide a step-by-step execution of the program.
c) They visually represent the flow of program control.
d) They are used for debugging and fixing errors.
23
NOTES 9. What is the purpose of a trace table in algorithm tracing?
a) To convert the algorithm into pseudocode.
b) To create a visual representation of the program flow.
c) To identify errors and bugs in the algorithm.
d) To store and track the values of variables during program execution.
10. A software developer is analysing the performance of a complex algorithm and
wants to understand how the variables change during its execution. Which of
the following tools would be most helpful for this purpose?
a) Trace table
b) Flowchart
c) Pseudocode
d) Loop invariant
11. Consider the following list of numbers: [2, 5, 3, 9, 7]. If we want to find the sum
of the numbers, which of the following conditions should be included in the
pseudocode?
a) Check if the number is divisible by 2.
b) Check if the number is odd.
c) Check if the number is negative.
d) No specific condition is required.
12. In a scenario where you want to prove that the sum of the first n natural numbers
is given by the formula n(n+1)/2, which of the following is an appropriate use of
inductive proofs?
a) Testing the formula for a few specific values of n.
b) Providing a counterexample for a specific value of n.
c) Assuming the formula is true for a particular value of n and proving it for
n+1.
d) Presenting a logical argument without any mathematical calculations.
13. Consider the following list of numbers: [8, 5, 3, 9, 6]. If we want to find the
minimum number in the list, which of the following conditions should be
included in the pseudocode?
a) Check if the number is odd.
b) Check if the number is negative.
c) Check if the number is less than the previous minimum.
d) No specific condition is required.
14. Suppose you are given a task to sort a list of numbers in ascending order.
Which of the following options correctly represents the steps involved in the
process?
a) Write the pseudocode, create a flowchart, design the algorithm, trace the
program.
b) Design the algorithm, create a flowchart, write the pseudocode, trace the
program.
24
c) Create a trace table, design the algorithm, write the pseudocode, create a
flowchart.
NOTES
d) Create a flowchart, write the pseudocode, design the algorithm, trace the
program.
15. Imagine you are given a scenario where you need to solve a Rubik’s Cube. You
have a specific set of instructions, including rotating specific layers of the cube
in a particular sequence to solve it. Is this a procedure or an algorithm?
a) Procedure
b) Algorithm
c) Neither Procedure nor Algorithm
d) Both Procedure and Algorithm
1.12
Terminal Answers
CHECK YOUR PROGRESS
1. True 10. Beginning, End
2. Subproblem 11. Inductive Hypothesis, Inductive
3. To be solved by student Step
4. Logic, Structure 12. False
5. Executed 13. Debugging
6. False 14. To be solved by student
7. True 15. Yes, it will change to 2
8. Conditions 16. Program will fall in infinite loop
9. To be solved by student 17. 0
18. Because I runs from 1 to 10 in ‘Finding sum of a list of numbers’ and from 2 to
10 in “Finding minimum of a list of numbers’
19. To be solved by student
25
NOTES ● Procedures help improve code organization and readability, as they
encapsulate a specific functionality and can be called from different parts
of the program.
● They facilitate code maintenance and debugging, as changes or fixes can
be made in one central location instead of scattering the modifications
throughout the codebase.
Algorithms:
● Algorithms provide a systematic approach to problem-solving and are
essential for designing efficient and effective software solutions.
● They outline the logic, steps, and operations required to solve a specific
problem or achieve a desired outcome.
● Algorithms help software developers analyse and understand the problem
at hand, enabling them to devise optimal solutions.
● They ensure that the software performs the desired tasks accurately,
efficiently, and within the given constraints.
● Algorithms can be implemented in various programming languages,
allowing for flexibility and portability across different software systems.
2. While flowcharts are indeed valuable tools for visualizing algorithms, they do
come with limitations and drawbacks in the software development process:
● Complexity: Flowcharts can become overly complex and convoluted for
intricate algorithms. As the algorithm grows in complexity, the flowchart
may become difficult to understand and maintain, defeating its purpose of
providing clarity.
● Ambiguity: Sometimes, flowchart symbols and their connections might
not be clear, leading to ambiguity in understanding the algorithm’s steps.
This can result in misinterpretations and errors during implementation.
● Limited Precision: Flowcharts may not capture all the nuances and fine
details of an algorithm, particularly when dealing with complex logical
conditions or data manipulation. The abstraction in flowcharts might lead to
missing out on critical implementation details.
3. Some benefits of using pseudocode over writing code in a specific programming
language include:
● Readability and Understandability: Pseudocode uses natural language
and simple programming constructs to describe the logic of an algorithm.
It is easier to read and understand, even for individuals who may not be
familiar with a particular programming language. Pseudocode focuses
on the algorithmic steps rather than syntactical details, making it more
accessible to a wider audience.
● Language Neutrality: Pseudocode is language-neutral, meaning it can
be understood and implemented in multiple programming languages. This
flexibility allows developers to focus on the algorithm’s logic and design
without getting tied to a specific programming language’s syntax or
constraints. It also promotes portability and ease of code migration across
different platforms or programming environments.
26
● Simplified Problem Solving: Pseudocode encourages a structured and
systematic approach to problem-solving. It allows developers to outline the
NOTES
algorithm’s logic, break it down into smaller steps, and plan the solution
before diving into the actual coding process. By providing a high-level
overview, pseudocode helps in identifying potential issues or inefficiencies
early on and facilitates better algorithm design.
● Collaboration and Communication: Pseudocode serves as a universal
language that promotes collaboration and communication among
developers, designers, and stakeholders. It enables effective discussions
and brainstorming sessions as it eliminates the distractions of language-
specific syntax and focuses on the algorithm’s core concepts. Pseudocode
acts as a bridge between technical and non-technical team members,
facilitating better understanding and alignment.
● Flexibility for Implementation: Pseudocode allows for flexibility in
choosing the most appropriate programming language or framework for
implementing the algorithm. Developers can select a language based on
factors such as performance requirements, existing codebase, or team
expertise. Pseudocode acts as a blueprint that can be translated into
different programming languages while maintaining the algorithm’s integrity
and logic.
27
NOTES Tracing provides developers with valuable information about the values of
variables and data structures at different stages of the algorithm’s execution.
By inspecting these values during tracing, developers can compare them
with expected or desired values. This helps in detecting discrepancies or
inconsistencies that indicate the presence of bugs. Tracing allows developers
to identify incorrect calculations, incorrect assignments, or unintended side
effects that can lead to errors.
Another significant advantage of tracing is its usefulness in debugging complex
algorithms or algorithms that involve multiple components or dependencies.
By tracing each component’s execution and their interactions, developers can
identify which component or module is responsible for the error. Tracing helps
to isolate the problematic section of code, making it easier to debug and fix
issues without having to analyse the entire codebase.
2. Loop invariants play a crucial role in analysing the time complexity of algorithms.
They provide valuable insights into the behaviour of loops and assist in
determining the upper and lower bounds of an algorithm’s time complexity. By
understanding how loop invariants relate to the number of loop iterations, we
can make informed assessments about the efficiency of an algorithm.
The importance of loop invariants in time complexity analysis can be illustrated
through an example. Consider an algorithm that calculates the sum of elements
in an array using a loop. The algorithm initializes a variable ‘sum’ to 0 and iterates
through each element, adding it to the ‘sum’ variable. The goal is to determine
the time complexity of this algorithm.
To analyse the time complexity, we can establish a loop invariant that represents
the sum of the elements processed so far:
Invariant: At the start of each iteration, the variable ‘sum’ contains the sum of
the elements from index 0 to index i-1.
Using this loop invariant, we can analyse the time complexity of the algorithm
as follows:
● Initialization: Before the first iteration, the ‘sum’ variable is initialized to 0.
Thus, the invariant holds true.
● Maintenance: Assuming the invariant is true before an iteration, we need to
show that it remains true after the iteration. During each iteration, the algorithm
adds the current element to the ‘sum’ variable. As a result, the ‘sum’ variable
correctly represents the sum of the processed elements up to index i. Hence,
the invariant is maintained.
● Termination: When the loop terminates, the ‘sum’ variable contains the sum
of all the elements in the array. The algorithm has processed each element
exactly once, and the invariant is satisfied.
Based on the loop invariant, we can observe that the number of iterations is
directly proportional to the size of the input array. Therefore, the time complexity
of this algorithm is O(n), where n represents the size of the array.
28
MCQ QUESTIONS
NOTES
1. a) A step-by-step procedure for solving a problem.
2. d) It helps in planning and understanding the logic of an algorithm.
3. a) Base case, induction hypothesis, inductive step.
4. b) To identify errors and bugs in the algorithm.
5. c) Input values
6. b) Decision point or condition
7. b) A loop invariant is a condition that holds true after the loop terminates.
8. c) They visually represent the flow of program control.
9. d) To store and track the values of variables during program execution.
10. a) Trace table
11. d) No specific condition is required.
12. c) Assuming the formula is true for a particular value of n and proving it for
n+1.
13. c) Check if the number is less than the previous minimum.
14. b) Design the algorithm, create a flowchart, write the pseudocode, trace the
program.
15. b) Algorithm
1.13
Assignment
29
NOTES 3. In a programming project, the development team is using a trace table to
track the execution of their program. Which of the following statements best
describes the importance of using a trace table?
a) The trace table helps to generate the final output of the program.
b) The trace table provides a visual representation of the program’s control
flow.
c) The trace table assists in identifying and fixing errors or bugs in the program.
d) The trace table is used to document the steps involved in the program’s
development process.
4. A team of developers is working on a collaborative programming project. They
decide to use a trace table to facilitate communication and understanding of
the program’s execution. Which of the following benefits does the trace table
provide in this context?
a) It helps in visually organizing the code into logical blocks.
b) It ensures that all team members follow the same coding conventions.
c) It facilitates communication about the program’s execution and variable
values.
d) It automatically generates pseudocode from the program’s source code.
5. In terms of complexity, how does a procedure compare to an algorithm?
a) Procedures are generally more complex than algorithms because they
involve detailed implementation steps.
b) Algorithms are generally more complex than procedures because they
require a deeper understanding of problem-solving techniques.
c) Procedures and algorithms can have varying levels of complexity depending
on the specific problem they address.
d) Procedures and algorithms have similar levels of complexity as they both
involve defining a series of steps to accomplish a task.
QUESTIONS
1. Consider the following pseudocode snippet:
● Declare variables x, y, i
● Initialize i to 1
● Initialize x to 5
● Initialize y to 0
● Repeat steps 5 to 7 till i<x+1
● SET y=y+i
● SET i=i+i
● OUTPUT y
Trace the execution of the above pseudocode and provide the values of variables
x, y, and i at each step.
30
2. Explain the concept of inductive proofs and their significance in mathematics.
Provide an example of an inductive proof and discuss the step-by-step process
NOTES
used to prove a statement using induction.
3. Design pseudocode and a flowchart to determine whether a given number is
prime. Explain the step-by-step process of the algorithm and discuss the logic
behind each decision. Justify your design choices.
4. You are designing a pseudocode algorithm for a calculator program. The program
should allow users to perform basic arithmetic operations such as addition,
subtraction, multiplication, and division. Write a pseudocode algorithm for this
scenario.
5. You are tasked with creating a flowchart for a simple grading system. The system
should accept the student’s score as input and display the corresponding grade
based on predefined score ranges. Draw a flowchart for this scenario.
1.14
References
Books:
● https://www.google.co.in/books/edition/Introduction_To_Algorithms/
NLngYyWFl_YC?hl=en&gbpv=1&dq=algorithms&printsec=frontcover
● https://www.google.co.in/books/edition/Data_Structures_Algorithms_using_C/
fCIEEAAAQBAJ?hl=en&gbpv=1&dq=algorithms&printsec=frontcover
Websites:
● https://wikidiff.com/algorithm/procedure
● https://everythingcomputerscience.com/discrete_mathematics/Proof_by_
Induction.html#:~:text=Steps%20for%20proving%20by%20induction%20
Description&text=The%20proof%20consists%20of%20two,statement%20
holds%20for%20n%20%2B%201.
● https://www.geeksforgeeks.org/loop-invariant-condition-examples-sorting-
algorithms/
● https://www.101computing.net/using-trace-tables/
31