0% found this document useful (0 votes)
7 views

Module2 ktuspecial.in

Uploaded by

keelubalan
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)
7 views

Module2 ktuspecial.in

Uploaded by

keelubalan
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/ 26

• KTU STUDY MATERIALS • SYLLABUS

• KTU LIVE NOTIFICATION • SOLVED QUESTION PAPERS

JOIN WITH US

WWW.KTUSPECIAL.IN KTUSPECIAL t.me/ktuspecial1


Algorithms, Flow chart and Pseudocode
2.1 Algorithms: The Building Blocks of Problem-Solving
An algorithm is a precise, step-by-step procedure for solving a problem or accomplishing
a task. It's a fundamental concept in computer science and engineering, serving as the
backbone for software development and problem-solving in various fields. An algorithm is a
finite sequence of well-defined, computational steps that transforms input into the desired
output. While often associated with mathematical computations, algorithms have a much
broader scope. They play crucial roles in various fields, including scientific research, medical
diagnostics and treatment, financial modeling and analysis, industrial production and supply
chain management and in communication systems.
In fact, algorithms saturate our daily lives, often operating behind the scenes. Any finite,
well-defined, and effective sequence of actions can be viewed as an algorithm. Even seemingly
simple tasks, like making a cup of tea or coffee, can be broken down into algorithmic steps.
Algorithm to make milk coffee
Step 1: Gather coffee powder, milk, sugar (optional), a coffee mug, and a spoon
Step 2: Heat water in a kettle
Step 3: Add 1 teaspoon of coffee powder and sugar
Step 4: Carefully pour the boiling water into the mug
Step 5: Stir well and Pour milk into the coffee mixture
Step 6: Stir the coffee and milk mixture gently to blend them
Step 7: Enjoy your milk coffee!
EXAMPLE 2.1 Develop an algorithm to find the sum of two numbers a and b
Algorithm
Step 1: Start
Step 2: Read values a and b
Step 3: Add a and b and assign the result to sum.
sum = a+b
Step 4: Display sum
Step 5: Stop
Algorithms can be expressed in various forms, mainly pseudocodes and flowcharts. The
choice of representation often depends on the intended audience and the complexity of the
algorithm.
Flowcharts: Visualizing Algorithms
While algorithms are powerful problem-solving tools, their textual descriptions can
sometimes be challenging to follow. This is where flowcharts come into play. A flowchart is a
visual representation of an algorithm, using standardized symbols to depict different types
of operations. A graphical representation of an algorithm using standardized shapes
connected by arrows gives a better understanding about the flow of control. Key components
of a flowchart are various shapes that represent various operations or decision points, flow
lines which are arrows that connect the shapes for indicating the sequence of steps, start and
end points: that clearly mark the beginning and end of the process etc.
Advantages of flowcharts:
▪ Visual clarity: They provide a clear, easy-to-understand overview of the process
▪ Improved communication: Facilitate better understanding among team members
▪ Identification of bottlenecks: Visual representation helps in spotting inefficiencies
▪ Documentation: They serve as excellent tools for process documentation
Various symbols used to construct flow chart and more examples are covered in detail
in Section 2.2. Commonly used symbols include terminator (oval-shaped), rectangle,
parallelogram and diamond. Rectangles in flowcharts represent processing steps or actions.
They indicate that some operation or computation is being performed. For example,
"Calculate total" would be shown in rectangles. Parallelograms are used to represent input or
output operations. They show when data is being entered into the program or when results
are being displayed or saved. Examples include "Enter customer name" or "Print invoice".
EXAMPLE 2.2: Develop the flow chart for finding sum of two numbers a and b

Start

Input two
numbers, a and b

Sum = a + b

Print Sum

Stop
Pseudocode
Pseudocode, on the other hand, is a text-based method for describing algorithms using
a combination of natural language and simplified programming constructs. It serves as an
intermediate step between human language and actual code, allowing developers to outline
the logic and structure of an algorithm without adhering to the strict syntax of a particular
programming language. Pseudocode typically includes common programming elements such
as loops, conditionals, and function calls, but expresses them in a more readable and
language- agnostic manner. This approach is particularly useful for planning and
communicating algorithm designs among team members, as it focuses on the core logic and
functionality without getting bogged down in implementation details. Pseudocode and more
examples are covered in detail in Section 2.3.
EXAMPLE 2.3: Develop the pseudocode for finding sum of two numbers a and b
PRINT "Enter first number: "
INPUT a
PRINT "Enter second number: "
INPUT b
sum = a + b
PRINT "Sum =: ", sum

2.1.1 Use of Algorithms


1. Problem-solving efficiency: Algorithms provide a structured approach to solving
complex problems, breaking them down into manageable steps.
2. Consistency and reliability: When properly designed, algorithms produce consistent
results for given inputs, ensuring reliability in various applications.
3. Optimization: Algorithms allow for the continuous improvement of processes,
leading to more efficient solutions over time.
4. Automation: By defining clear steps, algorithms enable the automation of tasks,
reducing human error and increasing productivity.
5. Abstraction: Algorithms provide a level of abstraction, allowing developers to focus
on high-level problem-solving rather than low-level implementation details.
6. Analysis and comparison: The formal nature of algorithms allows for theoretical
analysis and comparison of different approaches to solving a problem.

Figure 2. 1 Role of algorithm


An algorithm is a broader notion that encompasses any well-defined sequence of steps to
solve a problem, regardless of who or what executes these steps.

2.1.2 Steps Involved in Algorithm Development


Algorithms can be applied in various contexts, from simple everyday tasks to complex
scientific computations. Their versatility and power make them an essential tool in problem.
solving across numerous disciplines, extending far beyond the realm of computer science and
engineering.
The process of developing an algorithm is a structured approach that involves several
key stages. Let us see the various steps involved in algorithm development:

Figure 2. 2 Steps involved in algorithm development

• Problem Definition involves clearly stating and understanding the problem to be


solved. This crucial first step requires identifying the necessary inputs and expected
outputs, as well as defining any constraints or limitations that may affect the solution.
A thorough problem definition sets the foundation for all subsequent stages of the
problem-solving process.
• Model Development focuses on creating a simplified representation of the problem.
This stage involves identifying key variables and their relationships, as well as
establishing assumptions and boundaries. The model serves as an abstract framework
that captures the essential aspects of the problem, allowing for easier analysis and
solution development.
• Algorithm Design is the process of breaking down the problem into smaller,
manageable sub-problems and developing a step-by-step procedure to solve each.
These steps are then combined into a cohesive algorithm. During this stage, efficiency
is considered, and appropriate data structures are chosen to support the algorithm's
functionality.
• Verifying the algorithm is a critical step that involves proving the algorithm's
correctness mathematically or logically. This stage ensures that the algorithm covers
all possible input scenarios and produces the correct output for each case. Verification
helps to establish confidence in the algorithm's reliability and effectiveness.
• Implementation is the stage where the algorithm is translated into a programming
language. This process involves adhering to coding best practices and standards, as
well as optimizing the code for performance where necessary. The implementation
phase brings the theoretical algorithm into a practical, executable form.
• Complexity Analysis involves analyzing the time complexity (how runtime scales with
input size) and evaluating space complexity (memory usage) of the algorithm. This
stage helps identify potential bottlenecks or inefficiencies in the algorithm's
performance, providing insights for potential optimizations.
• Testing and Debugging encompass developing a comprehensive test suite covering
various scenarios, executing the program with different inputs to verify correct
behavior, and identifying and fixing any bugs or errors in the implementation. This
stage may also involve using profiling tools to analyze performance and resource
usage, ensuring the algorithm functions as intended.
• Documentation involves preparing detailed explanations of the algorithm's purpose,
design, and implementation. This includes providing usage instructions, outlining
limitations, and describing performance characteristics. Documentation also covers
any assumptions made during development and potential areas for future
improvement, serving as a valuable resource for users and future developers.
• Optimization and Refinement is the final stage where, based on testing and analysis
results, areas for improvement are identified. The algorithm is refined to enhance
efficiency or functionality, and the development process may be iterated as needed.
This stage ensures that the final solution is as effective and efficient as possible.
2.2 Flow Chart
As we have learnt, algorithm involves defining the step-by-step procedure for solving a
problem or accomplishing a task. But an algorithm could be too complex to understand and
too verbose. They may not be understood easily due to its textual description. A better
alternative can be a pictorial representation for the same. Such a pictorial representation of
various steps involved is called a flowchart. We can define flowchart as a diagrammatic
representation of the steps of an algorithm. Different shapes are used to denote different
types of operations while drawing a flow chart. These shapes are then connected by lines with
arrows to denote the flow or direction of the order in which steps should be performed. The
connecting lines are called flow lines.

2.2.1 Symbols used in creating flow chart


2.2.2 Types of flow chart
Flowcharts focus on the logical sequence of operations within a specific program or
algorithm. They represent the step-by-step flow of a single program or module. Flow charts
are primarily used by programmers and software developers to plan, design, and debug
individual programs or algorithms. They help in visualizing the logic and control flow of a
program before coding begins.
It includes start and end points, processing steps, decision points and branches,
input/output operations, loops and iterations. Based on the control structure, they can be
classified as sequential flowchart, branching flowchart (decision-based) and loop flowchart
(iterative).
1. Sequence Control Structure: This describes line-by-line execution, where statements are
carried out consecutively in the program's original order of appearance. For instance, they
could do a sequence of arithmetic operations, read/write operations, or variable assignments.
Eg: For adding two numbers, first get the input of two numbers (enclosed in parallelogram as
input), then addition operation, sum=a+b (enclosed in rectangle as process) and output the
value of sum (enclosed in parallelogram as output).
2. Decision Control Structure: The decision control structure has the ability to execute one
block of statements in place of another or even skip the execution of an entire block of
statements based on whether a condition is true or not. The decision-making process is
carried out by the use of a selection logic framework. Here a predicate, also called a condition,
is tested to see if it is True or False. A course of action is specified, if condition is evaluated to
be TRUE; if it is found to be FALSE, an alternative course of action is expressed. It should be
noted that a course of action may consist of one or more sequences of operations. Depending
on the processing requirements, a flowchart can have any number of decision boxes, and the
boxes can appear in any order based on the program logic chosen.
Eg: For finding if a number is even or odd, first step is entering the number (input in
parallelogram), next step is to find the remainder (process in rectangle). Then, decision box is
required to check if remainder is 0 or not. If remainder is 0, print the number is even. Else,
print the number is odd. This part (diamond shaped, decision making) is the decision-making
part in the flow chart. If YES, it follows a path. If NO, it takes another path and finally reach
STOP (oval-shaped terminator)
3. Loop Control Structure: This type of control structure permits a block of statement to be
executed repeatedly until a predetermined condition is satisfied.
This is an example for loop control structure - flowchart to calculate and print the product of
the first N natural numbers. It begins by inputting the value of N, which determines the upper
limit for the calculation. A variable, initialized to 1(Here variable, Product), is used to store the
product. A counter (here variable, Num) is set to 1 to iterate from 1 to N. In each iteration, the
product is multiplied by the current value of the counter. The counter is then incremented.
This process continues until the counter exceeds N. Once the loop ends, the final value stored
in the product variable, which represents the product of the first N numbers, is printed as the
output.

No
2.2.3 Considerations in flow charting
Five rules to follow while developing a flow chart are:-
1. Flow charts for programs should only use the standard symbols specified for various
operations.
2. The flow from left to right and from top to bottom should be shown in the program
logic.
3. Except decision symbol, every symbol used in a flowchart should only have one entry
point and one exit point. This can be called the 'single rule.
4. Symbols of the flow chart should convey the operations inside them without reference
specific programming language. Flow chart is independent of any programming
language.
5. Each decision-making branch needs to have clear labels.

2.2.4 Differences between algorithm and flowchart


Algorithms and flowcharts are fundamental tools in problem-solving and programming,
each offering unique advantages. An algorithm is a detailed, step-by-step textual description
of a solution, providing precise instructions in a language-agnostic manner. It excels in
conveying complex logic and mathematical operations but may be less intuitive for visual
learners. Flowcharts, on the other hand, use standardized symbols and shapes to create a
visual representation of the process flow. When it comes to debugging and process analysis,
flowcharts can make it easier to identify logical errors or process bottlenecks visually, while
algorithms might require closer reading to spot issues. Large, complex processes might be
more manageable in algorithmic form, as extensive flowcharts can become unwieldy. In terms
of practical application, algorithms typically translate more directly into code, while flowcharts
serve better as planning and communication tools. Flowcharts can also better represent
parallel processes or time-dependent steps visually, whereas algorithms may need additional
notation for such representations.

SL NO Algorithm Flow Chart


1 It is a set of instructions or step- by-step A flowchart is a graphical
procedure for solving a well-defined representation of the steps for
computational problem solving a problem

2 It is tougher to understand and difficult Easy to understand as well as to


to construct develop

3 There are no rules to follow for Developing flow chart requires some
developing an algorithm rules
4 It involves listing various steps in simple It involves pictorial representation of
language, using plain text various steps and involves graphical
representation or shapes
5 Debugging errors in algorithm is Debugging errors is easier in flow
challenging chart

6 Difficult to represent and understand Easy to represent and understand


branching and looping branching and looping

7 Algorithms may require more careful Flowcharts can be easily adjusted by


consideration while making changes to adding, removing, or rearranging
ensure the logic remains intact shapes
2.3 Pseudocode
Pseudocode can be described as a structured, informal high-level description of an
algorithm using a combination of natural language and basic programming constructs.
Pseudocode serves as a bridge between natural language and formal programming syntax.
It combines elements of everyday English with simplified programming structures to outline
an algorithm's logic. This hybrid approach incorporates the three fundamental programming
constructs sequential execution, conditional statements, and loops - but presents them in a
more accessible and flexible manner than full code. The result is a blueprint that's easy for
both programmers and non-programmers to understand, facilitating clear communication of
algorithmic ideas. Pseudocode is a valuable tool in algorithm development, bridging the gap
between abstract ideas and concrete implementation. Its use can lead to more efficient coding
processes, better algorithm designs, and improved collaboration among developers.
Its advantages are:

• More precise than natural language


• Easier to translate into actual code
• Helps in planning before coding
Its limitations are:

• Not standardized; styles may vary


• May still contain some ambiguity
Why pseudocodes?
1. Ease of understanding: Since the pseudocode is programming language independent,
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.
Rules for writing pseudocode
1. Use clear and concise statements. Each line should represent a single action of decision.
Avoid complex or ambiguous phrasing that could lead to misinterpretation.
2. Maintain consistent indentation to show the structure and nesting of your algorithm. This
helps in visualizing the flow and hierarchy of operations.
3. Standard keywords should be used for common operations. For example, use INPUT for
data entry, PRINT or OUTPUT for output, IF-THEN-ELSE for conditional statements, and
WHILE or FOR for loops.
4. Write one statement per line to improve readability. It makes it easier to follow the logical
flow of the algorithm.
5. Avoid language-specific syntax. Pseudocode should be generic enough to be implemented
in various programming languages.
6. Use descriptive variable names that indicate their purpose. This makes the code self-
explanatory and easier to understand.
7. Be consistent with your notation throughout the pseudocode. If you choose a certain way
to represent a construct, stick to it throughout your algorithm.
Advantages of Pseudocode
1. Improved Readability: Easier to understand than formal programming languages.
2. Quick Development: Allows rapid prototyping of algorithms.
3. Easy Modification: Simpler to change and refine than actual code.
4. Language Flexibility: Can be easily translated into various programming languages.
5. Focus on Logic: Encourages thinking about problem-solving rather than syntax.
6. Reduced Debugging Time: Helps identify logical errors before coding.
7. Documentation: Serves as clear, human-readable documentation of the algorithm.
8. Learning Tool: Useful for teaching and learning programming concepts.
9. Standardization: Promotes a consistent approach to algorithm design across
projects or teams.
EXAMPLE 2.6: Develop the pseudocode for finding area of a rectangle with length and
breadth b
PRINT "Enter the length of the rectangle: "
INPUT l
PRINT "Enter the breadth of the rectangle: "
INPUT b
SET area = l * b
PRINT "Area = ", area

2.3.1 The main constructs of pseudocode


Constructs in the context of pseudocode refer to the fundamental building blocks used to
structure and control the flow of a program or algorithm. They are the essential components
that form the skeleton of a pseudocode representation. We can think of them as the grammar
rules of programming. The main constructs are:

• Variables: For storing data


• Assignment: For assigning values to variables
• Input/Output: For interacting with the user
• Repetition: Loops (while, for)
• Selection: Decision-making (if, else, switch)

Construct Explanation Example


Variables Variables are used to store and manipulate DECLARE integer age
data in the algorithm DECLARE string name
DECLARE float price

Assignment Assignment is used to give a value to a name "biscuits"


variable. It's typically represented by an = or price = 29.99
sign

Input/Output Input is used to receive data from the user INPUT name
or an external source, while Output is used OUTPUT "Hello"
to display information to the user or send it OUTPUT name
to an external destination PRINT "Hi", name

Repetition (Iteration Loops are used to repeat a set of FOR i FROM 1 TO 5


or Loop) instructions multiple times. Common types PRINT i
include FOR, WHILE, and REPEAT-UNTIL ENDFOR

Selection - IF The IF statement is used for conditional IF age >= 18


execution. It executes a block of code only if PRINT "You are an
a specified condition is true adult" ENDIF

Selection - IF ELSE The IF-ELSE statement extends the IF IF score >= 60


statement by providing an alternative block PRINT "You passed"
of code to execute when the condition is ELSE
false. PRINT "You failed"
ENDIF
Selection - SWITCH The case structure is a decision- making SWITCH expression
CASE construct in pseudocode that allows for Case value1:
multiple execution paths based on the value // code for case
of an expression value1
Case value2:
Default:
// code if no match
found
ENDSWITCH
2.3.2 Sequencing
Sequencing is the most basic control structure in programming. It involves executing
statements one after another in the order they appear. Statements are executed in order from
top to bottom. Each statement is completed before the next one begins. The flow of control
is linear. Let us see the pseudocode for adding 2 numbers:
SET x 5 S1
SET y = 10 S2
SET sum = x+y .
PRINT sum .
Sn
The statement S1 is executed first, which is then followed by statement S2, so on and so forth,
Sn until all the instructions are executed. No instruction is skipped.

2.3.3 Selection (if-else structure, case structure)


Selection introduces decision-making capabilities into programs. It allows the program to
execute different sets of statements based on whether a condition is true or false. This
construct is essential for creating programs that can respond to different inputs or situations
Conditions are Boolean expressions that evaluate to True or False. There are mainly two types
of selection structures, if-else statements and switch-case structures.
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_statements
endif
If the test condition is evaluated to True, the statements denoted by true_statements are
executed. Otherwise, those statements are skipped.
EXAMPLE 2.7: Develop the pseudocode for checking if age>18 for the right to vote:
INPUT age
IF age >= 18
PRINT "You can vote"
ENDIF
A.2) if else structure
The general form is given below:
if (condition)
true_statements
else
false_ statements
endif
This structure contains 2 blocks of statements. If the test condition is met, the first block (true_
statements) is executed and the algorithm skips over the second block (false_ statements). If
the test condition is not met, the first block is skipped and only the second block is executed.
EXAMPLE 2.9: Develop the pseudocode for checking if pass of fail. If score>=50, student will
Pass. Or else, student will Fail.
INPUT score
IF score >= 50
PRINT "Pass"
ELSE
PRINT "Fail"
ENDIF
A.3) if else if else structure the if else if else structure, whose general form is given below:
if (condition1)
true_statement1
else if (condition2)
true_ statement2
else
false_ statement
endif
Here, if condition1 is met, true_ statement1 will be executed. Else condition2 is checked. If it
evaluates to True, true_ statement2 will be selected. Otherwise, false_ statement will be
executed.
EXAMPLE 2.10: Develop the pseudocode for checking if the number is positive or negative
number.
INPUT number
IF number > 0
PRINT “Positive number”
ELSE IF
PRINT “Negative number”
ELSEF
PRINT “Zero”
ENDIF
B) Switch Case (Case Structure)
This is similar to if else if else type and selects from multiple alternatives based on a single
expression. The SWITCH statement evaluates the variable in parentheses. Each CASE
represents a possible value for that variable. If the variable matches a CASE value, the code
block under that CASE is executed. BREAK statements are used to exit the switch block after
a case is matched and executed. DEFAULT case is optional and executes if none of the CASE
values match the variable.

SYNTAX:
SWITCH (variable)
CASE value1:
// code to execute if variable == value1
BREAK
CASE value2:
// code to execute if variable == value2
BREAK
CASE value3:
// code to execute if variable == value3
BREAK
DEFAULT:
// code to execute if variable doesn't match any case
ENDSWITCH
The figure shows the control flow of a switch- case structure in a flowchart begins with the
evaluation of a key expression or variable. This value is then compared against multiple
predefined cases. When a match is found, the flow follows the corresponding branch,
executing the associated actions or processes. If no match is found among the specified cases,
the flow may proceed to a default case, if one exists. After the execution of a matched case's
actions, the flow typically breaks out of the structure, bypassing all other cases. This differs
from nested if-else statements as it allows for more efficient and readable branching when
dealing with multiple possible values of a single variable.
EXAMPLE 2.11: Develop the pseudocode for print the direction name based on the value of a
character called dir.
INPUT dir
SWITCH (dir)
CASE “N”:
PRINT(“North”)
BREAK
CASE “S”:
PRINT(“South”)
BREAK
CASE “E”:
PRINT(“East”)
BREAK
CASE “W”:
PRINT(“West”)
BREAK
DEFAULT :
PRINT(“Invalid direction code”)
ENDSWITCH
2.3.4 Repetition or loop (for, while, repeat-until)
When a certain block of instructions is to be repeatedly executed, we use the repetition
or loop construct. This is essential for tasks that require iteration, such as processing lists of
data, performing calculations until a condition is met. Each execution of the block is called an
iteration or a pass. If the number of iterations (how many times the block is to be executed)
is known as definite iteration. Otherwise, it is called indefinite or conditional iteration. The
block that is repeatedly executed is called the loop body. They reduce code redundancy and
allow for efficient processing of data. Three types of loop FOR, WHILE and REPEAT-UNTIL.
A) FOR loop
The for loop implements definite iteration. There are three variants of the for loop. All for loop
constructs use a variable (call it the loop variable) as a counter that starts counting from a
specific value called begin and updates the loop variable after each iteration. The loop body
repeats execution until the loop variable value reaches end.

SYNTAX:
FOR variable = start_value TO end_value [step_value]
statement(s)
ENDFOR
Example: Pseudocode for finding the sum of first 10 numbers using FOR loop.
SET sum = 0
FOR i = 1 TO 10
sum = sum + i
ENDFOR
PRINT sum
B) Condition-Controlled Loops: This loop is executed based on a condition and needed when
the number of iterations is not known in advance.
❖ WHILE loops: A while loop is generally used to implement indefinite iteration. Test
the condition before executing the loop body. The loop body is executed repeatedly
as long as condition evaluates to True. When the condition is evaluated as False, the
loop body is exited. We use brackets or indentation to improve the readability of the
algorithms.
SYNTAX:
WHILE condition
statement(s)
ENDWHILE
Example: Pseudocode for finding the sum of first 10 numbers using WHILE loop.
SET sum=0
SET counter1
WHILE counter <= 10
SET sum = sum + counter
INCREMENT counter
ENDWHILE
PRINT "The sum of the first 10 numbers is:", sum
❖ REPEAT-UNTIL: A repeat-until loop is used for indefinite iteration and it is executing a
block of code repeatedly until a certain condition becomes true. It's similar to a while
loop, but the condition is checked at the end of the loop instead of the beginning.

SYNTAX:
REPEAT
statement(s)
UNTIL condition

Example: Pseudocode for finding sum of first 10 numbers using REPEAT- UNTIL loop.
SET sum = 0
SET count=1
REPEAT
SET sum = sum + count
INCREMENT count
UNTIL count > 10
PRINT "The sum of the first 10 numbers is:", sum

Feature REPEAT UNTIL WHILE Loop FOR Loop

Condition check After Before Before

Execution Continues if False Continues if True Iterates over sequence

Usage At least once Unknown iterations Known iterations


Q) Example to print first 10 numbers in all 3 loops:
1. FOR loop: While implementing FOR loop, loop variable i takes values from 1 to 10. Each
time value of i is to be printed. Inside the loop (each iteration), only thing to do is PRINT i.
Thus, it is executed 10 times (when i=1 to i=10). This is the most straightforward approach for
this task. The loop variable i starts at 1 and increments by 1 each iteration until it reaches 10.
FOR i = 1 TO 10
PRINT i
ENDFOR

2. WHILE loop: For implementation with WHILE, we initialise the loop variable value to 1 (as
the initial value) outside the loop. Inside the loop, value of i is printed and i value is
incremented by 1. Condition of loop is set as while (i<=10).
SET count = 0
WHILE count < 11
PRINT count
INCREMENT count
ENDWHILE

In this WHILE loop, we initialize i to 1 before the loop starts. The loop continues as long as
value of i is less than or equal to 10. We need to remember to increment i inside the loop to
avoid an infinite loop.
3. REPEAT - UNTIL loop: With the REPEAT - UNTIL loop, we also initialize i to 1 before the loop.
The loop body executes, printing and incrementing i, and then checks if i is greater than 10. If
it is, the loop terminates.
SET i = 1
REPEAT
PRINT i
INCREMENT i
UNTIL i > 10

From this example, it is very clear that, WHILE and REPEAT UNTIL loops check the
condition and continue the iterations, instead of the count value, which we check in FOR loop.
The FOR loop is most suitable for this task because we know exactly how many times,
we want the loop to run. The WHILE and REPEAT-UNTIL loops require manual initialization and
incrementation of the loop variable. The REPEAT-UNTIL loop will always execute at least once,
which is fine in this case but might not always be desirable. The condition is checked on

Difference between WHILE and REPEAT-UNTIL is that:

• WHILE loop checks the condition at the beginning of each iteration, while REPEAT -
UNTIL loop checks the condition at the end of each iteration. Therefore, WHILE is
called entry-controlled loop and REPEAT UNTIL loop is called exit-controlled loop.

• WHILE loops may execute zero times if the initial condition is false, while REPEAT-
UNTIL loops always execute at least once.

In 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 might also like