Help with a for loop?

Mar 26, 2017 at 8:00pm
I need help writing a for loop. For example, let's say the code has the user enter the number of times it needs something to loop, so how do I set up the code so that it loops depending on the users input?

FOR EXAMPLE: The program asked the user the number of test scores for the semester, so how do I write the for() loop to execute "Enter a test score" the number of times that the user entered as the number of tests? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <iostream>
using namespace std;
int main()
{
	int scores, stuID, testScore;
	char choice;

	cout << "Enter the number of scores for this semester: ";
	cin >> scores;
	
	do
	{
		cout << "=====================================================";
		cout << "Add a student (Y to continue, any other character to end): ";
		cin >> choice;
		cout << "Enter a student's ID: ";
		cin >> stuID;


		for ()
               {
			cout << "Enter a score: ";
			cin >> testScore;
                }


	} while (choice == 'Y' || choice == 'y');


	system("pause");
	return 0;
}
Last edited on Mar 26, 2017 at 8:03pm
Mar 26, 2017 at 8:26pm
Ok, so your for loop isn't structured right, not a big deal. If you are trying to enter in the number of scores first then enter in those actual scores it should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

#include <iostream>
using namespace std;
int main()
{
	int scores, stuID, testScore;
	char choice;
	//endl cuts the line off and can help with formatting
	cout << "Enter the number of scores for this semester: " << endl;
	cin >> scores;

	do
	{
		cout << "====================================================="<<endl;
		cout << "Enter a student's ID: ";
		cin >> stuID;


		for (int i=1;i<=scores;i++)//proper for loop structure
		{
			cout << "Enter a score: ";
			cin >> testScore;
		}
		cout << "Add a student (Y to continue, any other character to end): ";
		cin >> choice;//moved after the for loop so that the actions are performed above then asked to repeat

	} while (choice == 'Y' || choice == 'y');


	system("pause");
	return 0;
}
Mar 26, 2017 at 8:34pm
Thank you so so much! The int i=1 throws me off for some reason on these for loops.
Mar 26, 2017 at 8:37pm
No problem. Learning everything takes time
Topic archived. No new replies allowed.