185k views
0 votes
Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10},

print:
7 9 11 10
10 11 9 7

Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.

#include

int main(void) {
const int NUM_VALS = 4;
int courseGrades[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;

/* Your solution goes here */
return 0;
}

User Bryce S
by
5.5k points

1 Answer

5 votes

Answer:

for(i = 0 ; i < NUM_VALS; ++i)

{

cout << courseGrades[i] << " ";

}

cout << endl;

for(i = NUM_VALS-1 ; i >=0 ; --i)

{

cout << courseGrades[i] << " ";

}

cout << endl;

Step-by-step explanation:

The first loop initializes i with 0, because we have to print the elements in order in which the appear in the array. We print each element, adding a space (" ") character at its end. After the loop ends, we add a new line using endl.

The second loop will print the values in a reverse order, so we initialize it from NUM_VALS-1, (since NUM_VALS = 4, and array indices are 0,1,2,3). We execute the loop till i >= 0, and we print the space character and new line in a similar way we executed in loop1.

User MalphasWats
by
6.0k points