Hello. I'm learning programming on C++ and I need to solve this problem using nothing more than basic stuff: arrays, if/else and for's.
The problem:
Create a program that reads 10 int numbers.
After that, create a report with each different value and the numuber of times that the value appeared on the array.
So, after a lot of thinking, I got this:
#include <iostream>
using namespace std;
int main()
{
int val[10], valunico[10], valrepetido[10], valcompara[10];
for (int cont=0; cont<10; cont++){
valrepetido[cont]=1;
valunico[cont]=1;
valcompara[cont]=1;
}
for (int cont=0; cont<10; cont++){
cout << "Inform the " << cont+1 << "o int value: ";
cin >> val[cont];
}
for (int cont=0; cont<10; cont++){
for (int contcompara=0; contcompara<10; contcompara++){
if (val[cont]==val[contcompara]){
valrepetido[cont]++;
valcompara[cont]++;
}
else
valunico[cont]++;
}
}
for (int cont=0; cont<10; cont++){
if (valunico[cont]==10)
cout << val[cont] << " appeared 1 time." << endl;
else{
if (valrepetido[cont]>1){
for (int contcompara=0; contcompara<10; contcompara++){
if (valrepetido[cont]==valcompara[contcompara]){
valcompara[contcompara]-1;
}
}
cout << val[cont] << " appeared " << valrepetido[cont]-1 << " times." << endl;
}
}
}
}
The problem is, I can't find a way at the end to show each value just one time. Any idea on how to fix my code to do that? Thanks.
The "const" identifier is basically saying that this integer CANNOT be changed anywhere in the program, and if you try, the compiler will complain (unless you use const_cast or something). Its basically a better alternative to #define, and is used to get rid of "Magic Numbers" in your code. It also means you can just change that one variable and the rest of your code will change too (such as, if you suddenly wanted to input 20 numbers instead).
I'm still trying to understand the logic you used on the code. It's pretty dam good, but I don't think I will think like you did on the next time I need to solve this kind of situation.