Page 1 of 1

inneficient c++ code

Posted: Tue Nov 01, 2005 7:00 pm
by Charles256
any idea how on earth i make this more efficient?

Code: Select all

char names[5][25];
	double grade1[4];
	double grade2[4];
	double grade3[4];
	double grade4[4];
	double grade5[4];
	
	for(int i=0;i<5;i++)
	{
		cout << "Please enter the name of student " << i+1 << ":";
		cin >> names[i];
		cout << endl;
	}

	for (int k=0;k<5;k++)
	{
		cout << " Please enter " << names[i] << " grades.";
		for (int o=0;o<4;o++)
		{
			cout << "Please enter grade " << o+1 << ":";
			if (k==0)
			{
				cin >> grade1[o];
			}
			if (k==1)
			{
				cin >> grade2[o];
			}
			if (k==2)
			{
				cin >> grade3[o];
			}
			if (k==3)
			{
				cin >> grade4[o];
			}
			if (k==4)
			{
				cin >> grade5[o];
			}
		}
	}

Posted: Wed Nov 02, 2005 12:54 am
by GameMusic

Code: Select all

#define STUDENTS 5
   #define GRADES 4

   char names[STUDENTS][25];
   double grades[STUDENTS][GRADES];

   for(int i=0;i<STUDENTS;i++)
   {
      cout << "Please enter the name of student " << i+1 << ":";
      cin >> names[i];
      cout << endl;
   }

   for (int k=0;k<STUDENTS;k++)
   {
      cout << " Please enter " << names[k] << " grades.";
      for (int o=0;o<GRADES;o++)
      {
         cout << "Please enter grade " << o+1 << ":";
         cin >> grades[k][o];
      }
   }

Posted: Wed Nov 02, 2005 6:34 am
by timvw
If you ask the grades in the same loop as you ask the names, you can save a bit of looping time too ;)
But i don't know if you want to change to the flow ;)

Posted: Wed Nov 02, 2005 7:10 am
by programmermatt
Might consider creating a vector of a struct of something like this:

Code: Select all

struct StudentGrades{
     char *studentName;
     vector<int> grades;
};
vector<StudentGrades> students;
Then you can interact with the variable 'students' for all your needs. (Allowing nearly unlimited records)

Posted: Wed Nov 02, 2005 8:02 am
by Charles256
yeah, after some moer thinking it turns out I did it the best way possible. My instructions were prtty specific and as a result my hands were kinda tied.