So here is what I've got a problem with. I have created a function that generates a random number. I need to check the array for equal numbers (all between 1-20) and output the number that appears the most. My problem is that I'm getting odd outputs at both pulling out the repeating numbers, and at trying to output just one of the repeating numbers. My major problem is in the commonElement function.
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cmath>
using namespace std;
class myArray{
public:
myArray();
void setRandomNum();
void getPrint();
// void maxElements();
void commonElement();
private:
int n;
int A[20];
};
myArray::myArray(){//constructor
n=0;
}
void myArray::setRandomNum(){
for (int i=0;i<=20;i++){
n=rand()%20+1;
A[i]=n;
}
}
void myArray::getPrint(){
for (int i=0;i<=20;i++)
cout<<A[i]<<endl;
}
// void myArray::maxElements(){
// }
void myArray::commonElement(){
int c=0;
int newArray[20];
for (int a=0;a<20;a++)//set all values to zero
newArray[a]=0;
for (int i=0;i<20;i++){
for (int j=i+1;j<20;j++){//nested for loop to sort equal numbers
if (A[i]==A[j]){//compare numbers
newArray[c]=A[i];//assign equal numbers to new array
c++;
}
}
}
for (int i=0;i<20;i++){
for (int j=i+1;j<20;j++){
if (newArray[i]==newArray[j]&&newArray[j]!=0)
cout<<newArray[i]<<endl;}
}
}
int main(){
myArray one;
char option;//set menu
do {
cout << endl << endl << "Choose from:" << endl << endl;
cout << "1. Set Array" << endl;
cout << "2. Output Array" << endl;
cout << "3. Output Common number." << endl;
//cout << "4. Compare Second to First Word" << endl;
//cout << "5. Stop Program" << endl;
//cout << "6. " << endl;
//cout << "7. " << endl;
//cout << "8. " << endl;
cin >> option;
switch (option)
{
case '1':
cout<<"The Array is initialized";
one.setRandomNum();
break;
case '2':
cout<<"The Array Elements";
one.getPrint();
break;
case '3':
cout<<"The largest common elements are:"<<endl;
one.commonElement();
// break;
//case '4':
// cout<<newString.compareOddStrings(first, second);
// break;
//case '5':
//
// break;
//case '6':
//
// break;
//case '7':
//
// break;
//case '8':
//
// break;
default:
cout << "invalid input!!! Try it again." << endl;
}
} while (option != 5);
system ("pause");
return 0;
}