Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+18 votes
public static int looper(int n) {
  int result = 0;
  int a = 0;
  for (int i = 1; i <= n; i++) {
    a++;
  }
  while (a > 0) {
    result++;
    a--;
  }
  return result;
}

Evaluate looper(2):
Evaluate looper(100):

asked in CSC211_Winter2018 by (8 points)
edited by

2 Answers

+7 votes

If you look closely at this program, you'll notice that the for loop and the while loop are quite similar to each other. They're both incrementing a value, and they both depend on a pre-existing, nonzero value to repeat for...

Consider this:

  • Try tracing your variables (n, a, and result) throughout the program.
  • Pay attention to how one variable changes in relation to another.
  • Moreover, try to discern what each loop is doing to its variables. What stands out to you?
answered by (462 points)
+5 votes

looper(2); will end up returning the integer 2.
looper(100); will end up returning the integer 100.

answered by (8 points)
...