Bong Meister Bong Meister - 2 months ago 8
C++ Question

passing dynamic array object to friend function doesn't accumulate counter

I passed a dynamic array object in the 'summary' function, but i was unable to get it to accumulate the counter for a, b & c.

sample output :

Grade A : *

Grade B :

Grade C :

(only the last one is recorded, doesn't accumulate), I'm using Codeblock, and it stops working if i use pointer.)

#include <iostream>
using namespace std;

class Marks
{
protected :
float marks[3];
char grade;
public:
void mark_entry()
{
for(int i=0; i<3; i++)
{
cout<<"Enter Marks : ";
cin>>marks[i];
}
}
void average()
{
float avg = (marks[0]+marks[1]+marks[2])/3;
set_grade(avg);
}
void set_grade(float average)
{
if(average >= 80 && average <= 100)
{
grade='A';
}
else if(average >= 50 && average < 80)
{
grade='B';
}
else if(average >= 0 && average < 50)
{
grade='C';
}
}
};
class Result : public Marks
{
public:
char getGrade()
{
return grade;
}
friend void summary(Result [], int);
};
void summary(Result arr[], int size)
{
int a=0, b=0, c=0;
cout<<"===================================="<<endl;
cout<<"\tSummary Results"<<endl;
cout<<"===================================="<<endl;
for(int i=0; i<size; i++)
{
switch(arr[i].grade) //switch(arr[i].getGrade)
{
case 'A' : a++;
break;
case 'B' : b++;
break;
case 'C' : c++;
break;
}
}
cout<<"Grade A : ";
for(int i=0; i<a; i++)
{
cout<<"*";
}
cout<<"\nGrade B : ";
for(int i=0; i<b; i++)
{
cout<<"*";
}
cout<<"\nGrade C : ";
for(int i=0; i<c; i++)
{
cout<<"*"<<endl;
}
}
int main()
{
int num;
cout<<"Enter number of students : ";
cin>>num;
Result *Stud1 = new Result[num];
for(int i=0; i<num; i++)
{
cin.ignore();
(Stud1+1)->mark_entry();
(Stud1+1)->average();

}
summary(Stud1, num);
delete[]Stud1;
}

qxz qxz
Answer

Your problem is in these two lines in int main():

(Stud1+1)->mark_entry();
(Stud1+1)->average();

At each loop iteration, you're accessing the same element: the second one (index 1). To access the ith element, just index into the array with brackets:

Stud1[i].mark_entry();
Stud1[i].average();

If you really want to add the index to the pointer like you were doing (although there is no reason to do that in this scenario), then replace (Stud1+1) with (Stud1+i).