121k views
0 votes
Bob and Alice are solving practice problems for CSE 2320. They look at this code: for(i = 1; i <= N; i = (i*2)+17 ) for(k = i+1; k <= i+N; k = k+1) // notice i in i+1 and i+N printf("B"); Alice says the loops are dependent. Bob says they are not dependent. Who is correct? ____________ What do you think? Are they dependent or not dependent? They are __________

2 Answers

0 votes

Answer:

Alice is correct

They are dependent

Step-by-step explanation:

The code snippet can be re-written as follows;

for(i = 1; i <= N; i = (i*2)+17 )

for(k = i+1; k <= i+N; k = k+1)

Which can also be re-written as;

for(i = 1; i <= N; i = (i*2)+17 ) {

for(k = i+1; k <= i+N; k = k+1){

}

}

In many programming languages, curly brackets are used for grouping blocks of codes. For a for loop, while loop, if statement and other related control structures, the lines of statement(s) inside their curly brackets are executed when they are encountered. In the case where any of these control statements is written without curly brackets, the next line of code (and that only) following it belongs to its block.

Consequential from the foregoing, at each of cycles of the outer for loop in the first code snippet above, the inner for loop will be executed. In other words, the inner for loop belongs to the block of the outer for loop though there is no curly bracket included. This also means that once a control statement has only a single line of code to be executed or to be a part of its block, curly brackets are not required. Therefore, the two versions of code snippets written above are identical and equivalent.

With the aforementioned, it is easy to say and see that the Alice is correct that the loops are dependent on each other.

User Jolinda
by
4.4k points
3 votes

Answer:

Alice is correct.

The loop are dependent.

Step-by-step explanation:

for(i = 1; i <= N; i = (i*2)+17 )

for(k = i+1; k <= i+N; k = k+1) // notice i in i+1 and i+N

printf("B")

This is a nested for-loop.

After the first for-loop opening, there is no block of statement to be executed rather a for-loop is called again. And the second for-loop uses the value of i from the first for-loop. The value of N is both called from outside the loop.

So, the second for-loop depend on the first for loop to get the value of i. For clarity purpose, code indentation or use of curly brace is advised.

User Webmonkey
by
4.0k points