Reputation: 293
I am trying to get a program to print out a star based on which number was entered by the used, e.g a number between 10-20 = 1 etc. My problem is I do not know how to get the print to function to work as at the moment it does not print anything out. Can anyone help.
Code:
void readExamMarks(int examMarks[], int sizeOfArray, int counter1, int counter2){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
if((x >=0) && (x <= 100)){
x = x/10;
switch(x){
case 1:
counter1++;
break;
case 2:
counter2++;
break;
}
examMarks[idx] = x;
}
else{
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
}
void printExamMarks(int examMarks[], int sizeOfArray){
for(int x = 0; x < sizeOfArray; x++){
cout << setw(5) << examMarks[x];
}
cout << endl;
}
void printHisto(int examMarks[], int sizeOfArray,int counter1, int counter2){
system("cls");
while(counter1 != 0){
cout << "*" << endl;
counter1--;
}
for( int x = 0; x < counter1; x++){
cout << setw(5) << "*" << endl;
}
}
int main()
{
int examMarks[20];
int counter1 = 0;
int counter2 = 0;
readExamMarks(examMarks, 5, counter1, counter2);
printHisto(examMarks, 5, counter1, counter2);
printExamMarks(examMarks,5);
system("PAUSE");
}
Upvotes: 1
Views: 135
Reputation: 17918
printHisto(examMarks, 5, counter1, counter2);
will not print anything reason is counter1 and counter2 are initialize with 0, and they are passed as it is to the printHisto(...), my guess is you intend readExamMarks(...) to modify your counter(1,2), if that is the case, pass them by ref http://www.cplusplus.com/doc/tutorial/functions2/
Upvotes: 0
Reputation: 87959
Your code is a bit strange, and I'm having some trouble following it. But I think the mistake you are making it that you are assuming that because you increment the variables counter1
and counter2
in readExamMarks
then is somehow going to affect the values of counter1
and counter2
in printHisto
. That's not true. You change the value in readExamMarks
but that has no effect on the vairable in main
, and so when you call printHisto
counter1
and counter2
are still zero.
What you should understand is that variables in different functions are different variables even if they have the same name. If you want readExamMarks
to change the variables in main
then you should use references.
void readExamMarks(int examMarks[], int sizeOfArray, int& counter1, int& counter2)
{
...
}
By using int&
instead of int
counter1
and counter2
are now references to the variables in main
, not copies of the variables in main.
Upvotes: 3