98.6k views
1 vote
Suppose that gamma is an array of 50 components of type int and j is an int variable. Which of the following for loops sets the index of gamma out of bounds?

A. for (int i = 0; i < 50; i++) {
gamma[j] = 0;
}
B. for (int i = 0; i <= j; i++) {
gamma[i] = 0;
}
C. for (int i = 0; i < j; i++) {
gamma[i] = 0;
}
D. for (int i = 0; i < 49; i++) {
gamma[i] = 0;
}

1 Answer

1 vote

Final answer:

The for loop that potentially sets the index of gamma out of bounds is scenario B, if the variable 'j' is greater than 49.

Step-by-step explanation:

To determine which of the given for loops sets the index of gamma out of bounds, let's examine each one:

  • A. for (int i = 0; i < 50; i++) {gamma[j] = 0;} - This loop will not set the index out of bounds as it iterates from 0 to 49. However, it may be problematic if the variable j is not within the range 0 to 49.
  • B. for (int i = 0; i <= j; i++) {gamma[i] = 0;} - This loop potentially sets the index out of bounds, if j is greater than 49.
  • C. for (int i = 0; i < j; i++) {gamma[i] = 0;} - Similar to B, this loop could cause an out of bounds error if j is greater than 49.
  • D. for (int i = 0; i < 49; i++) {gamma[i] = 0;} - This loop is safe as it only iterates up to the index 48.

Therefore, the loop that sets the index of gamma out of bounds is scenario B if j is greater than 49.

User Delirium Tremens
by
8.4k points