118k views
1 vote
Assume the int variables i, lo, hi, and result have been declared and that lo and hi have been initialized. Write a for loop that adds the integers between lo and hi (inclusive), and stores the result in result. Your code should not change the values of lo and hi. Also, do not declare any additional variables -- use only i, lo, hi, and result.NOTE: just write the for loop header; do not write the loop body itself.

1 Answer

1 vote

Answer:

for (i = lo, result = 0; i <= hi; result += i, i++) {}

Step-by-step explanation:

A for loop header has three statements:

  1. i = 0, result = 0; This statement initializes i and result variables with 0. It is executed only once at the very start of the for loop.
  2. i <= hi; This statement is executed after the first statement and again after the execution of code in body of the loop.
  3. result += i, i++ This statement is executed after the execution of code in body of the loop but before the execution of second statement.

Therefore, the following sequence of events will occur:

  • The result variable is initialized with 0 at start.
  • Then, the condition is checked. If the value of i will be less than or equal to the value of hi, the third statement will be executed.
  • The third statement will add the value of i to the value of result and then increase the value of i by 1.
  • Then, again the condition in second statement will be checked.

This loop will be executed for as long as the condition remains true.

User GRVPrasad
by
6.8k points