Comp Sci Doubting My Should I Add a Loop?

  • Thread starter Thread starter asz304
  • Start date Start date
  • Tags Tags
    Loop
AI Thread Summary
The discussion revolves around the need for a loop in a C++ program designed to input student names, letter grades, and marks. It highlights the importance of defining the size of the arrays correctly, as the variable 'number' should be a constant known at compile time. The code contains redundancies, with arrays declared both globally and within the main function. A suggested solution involves using a for loop to streamline the input process for each student, ensuring all data is collected efficiently. Overall, implementing a loop is recommended for better organization and functionality of the program.
asz304
Messages
107
Reaction score
0
I'm not sure how this works. If I need to put a loop before the first cout statement.

The Attempt at a Solution



Code:
include <iostream>
include <cmath>
using namespace std;

string name[number];
char letterGrade[number];
double mark[number];

int main(){

string name[number];
char letterGrade[number];
double mark[number];

  cout <<"Enter number of students";
  cin >> number;

  cout << " Enter the name ";
  cin >> name[number];

  cout << " Enter the mark ";
  cin >>  mark[number];

Is this right?
or should there be a loop before the first cout statement that holds till the third cin statement?
 
Physics news on Phys.org
if you just want to two numbers then you don't need anyones name first of all. Second, do you plan to input all of these numbers? If so, I would store the numbers first into an array, and then manipulate the arrays separately. running a loop the size of your class and inputting them would be an annoying way to carry through this.
 
1. Your three arrays all have number elements, so unless you're doing something fancy with dynamically-allocated arrays, number needs to be a constant that is known at compile time.

2. You have declared the three arrays twice each: once at the gobal level, and once inside main.

3. If you have a small number of student names and their letter grades and marks to enter, you can use a for loop that looks like this:
Code:
for (int i = 0; i < number; i++)
{
  cout << "Student name: ";
  cin >> name[i];
  // Prompt for letter grade in a similar way
  // Prompt for mark in a similar way
}
 

Similar threads

Replies
2
Views
3K
Replies
3
Views
1K
Replies
7
Views
2K
Replies
3
Views
2K
Replies
6
Views
3K
Replies
10
Views
3K
Back
Top