-
detecting repeat numbers
Code:
#include <iostream>
using namespace std;
int main()
{
int number;
int repeat;
int array[5];
cout << "Enter five numbers.\n" << endl;
for (register int i = 0; i < 5; i++)
{
cout << "Enter number " << i + 1 << ": ";
cin >> number;
repeat = number;
array[i] = number;
if (i > 0)
{
for (register int j = 0; j < i; j++)
{
while (array[j] == number)
{
cout << "\nNumber repeated.\n"
<< "Please re-enter number " << i + 1 << ": ";
cin >> number;
}
}
array[i] = number;
}
}
cout << endl;
for (i = 0; i < 5; i++)
{
cout << "Number " << i + 1 << " = " << array[i];
cout << endl;
}
cout << endl;
return 0;
}
What's wrong with that code? It's not detecting repeat numbers. Well, it does kind of do what it's suppose to, but it has many flaws.
-
You don't need to specify a variable as 'register'. That's done automatically by most, if not all modern compilers.
Your repeat loop doesn't loop back to check your new number to see if its a repeat.
Code:
flag = 1;
while (flag) {
input number
increment counter by 1
use a for loop to check if that number's a repeat
if yes, set flag to 1, and decrement counter by 1
if no, set flag to 0
}
This isn't all-inclusive, but you get the gist of it.
-
you might want to make repeat an array and compare the two arrays, per se. this should check to see if the last number entered is a repeat, as it is now.
-
I wrote something like this a while back, but recently reformatted and it's gone now....Basically, I just had a loop to thru all of the array elements, and if it was equal to any of the elements of the array, except the current one being generated...if it were, it would generate a new number, and then rinse and repeat.
-
Hey, you're coding it difficult than it needs to be. You don't need to use keyword 'register' to declare int variable and you don't need to use another varible like 'repeat' to mirror the variable 'number'. See how I modified your prog. to make it work and easy to understand the flow of program.
Code:
#include <iostream>
using namespace std;
int main()
{
int number;
//int repeat;
int array[5];
cout << "Enter five numbers.\n" << endl;
//for (register int i = 0; i < 5; i++)
for (int i = 0; i < 5; i++)
{
cout << "Enter number " << (i + 1) << ": ";
cin >> number;
//repeat = number;
//array[i] = number;
//if (i > 0)
//{
//for (register int j = 0; j < i; j++)
for (int j = 0; j < i; j++)
{
while (array[j] == number)
{
cout << "\nNumber repeated.\n"
<< "Please re-enter number " << (i + 1) << ": ";
cin >> number;
}
}
array[i] = number;
//}
}
cout << endl;
for (i = 0; i < 5; i++)
{
cout << "Number " << (i + 1) << " = " << array[i];
cout << endl;
}
cout << endl;
return 0;
}