220k views
2 votes
9.1.3: Printing vector elements with a for loop. Write a for loop to print all NUM_VALS elements of vector courseGrades, following each with a space (including the last). Print forwards, then backwards. End with newline. Ex: If courseGrades

User Pyano
by
9.4k points

1 Answer

3 votes

Answer:

The program to this question as follows:

Program:

#include <iostream> //defining header file

#include <vector> //defining header file

using namespace std;

int main() //defining main method

{

//defining integer variable NUM_VALS and i.

int NUM_VALS = 4,i;//assign value in NUM_VALS variable

vector<int> courseGrades(NUM_VALS); //defining vector array

cout<<"Input values: "; //print message

for(i=0;i<NUM_VALS;i++) //loop for input value

{

//input value in verctor array

cin>>courseGrades[i]; //input from user-end

}

for (i = 0; i < NUM_VALS; i++) //loop to print value

{

cout<<courseGrades[i]<< " ";//print value

}

cout << endl;//for new line

for (i = NUM_VALS-1;i >= 0;i--)//loop to print value in reverse order

{

//print value in reverse order

cout << courseGrades[i] << " "; //print value

}

cout << endl; //for new line

return 0;

}

Output:

Input values: 2

3

5

6

2 3 5 6

6 5 3 2

Step-by-step explanation:

In the above-given code two integer variable "NUM_VALS and i" is declared, in which variable "NUM_VALS" assigns a value, that is 4, in the next step, a vector array "courseGrades" is defined, in which we take input from the user end.

  • In the next step two for loop is declared, in the first loop we simply print the value of the "courseGrades".
  • The second loop is also used to print the "courseGrades" value but, in the reverse order.
User ElvisLives
by
7.9k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.