inneficient c++ code

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

inneficient c++ code

Post 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];
			}
		}
	}
GameMusic
Forum Newbie
Posts: 24
Joined: Fri Oct 28, 2005 8:33 pm

Post 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];
      }
   }
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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 ;)
programmermatt
Forum Commoner
Posts: 65
Joined: Tue Mar 15, 2005 5:03 pm
Contact:

Post 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)
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post 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.
Post Reply