Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
471 views
in Iteration and Recursion by (49.1k points)
closed by

Give an example for loop invariant.

1 Answer

+1 vote
by (54.8k points)
selected by
 
Best answer

The loop invariant is true in four crucial points in a loop. Using the loop invariant, we can construct the loop and reason about the properties of the variables at these points.

Example:

Design an iterative algorithm to compute an. Let us name the algorithm power(a, n).

For example,

power(10, 4) = 10000

power (5, 3) = 125

power (2, 5) = 32

Algorithm power(a, n) computes a by multiplying an cumulatively n times,

The specification and the loop invariant are shown as comments. power (a, n)

– – inputs: n is a positive integer

– – outputs: p = an

p, i : = 1, 0

while i ≠ n

– – loop invariant: p = ai

p, i : = p x a, i + 1

The step by step execution of power (2, 5) is shown in Table. Each row shows the values of the two variables p and i at the end of an iteration, and how they are calculated. We see that p = a is true at the start of the loop, and remains true in each row. Therefore, it is a loop invariant.

When the loop ends, p = ai is still true, but i = 5. Therefore, p = a5 . In general, when the loop ends,

p = an . Thus, we have verified that power(a, n) satisfies its specification.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

...