Reputation: 1
My teacher gave us the a code where a user inputs a number up to 10 digits, and each digit is stored in an array. We need to format it in such a way that it outputs each digit that is repeated individually. I'm trying to accomplish this using a for loop, but I'm having some difficulty in understanding exactly how the loop interacts with the array (or at least, I think that's where my trouble is coming from). This is where I'm at so far... Anyone that can explain the interaction of the for loop and array between lines 44 and 50 will have my appreciation.
#include <iostream> // provides cin, cout, endl, fixed
using namespace std;
#define DIGITS 10 // number of Base 10 digits
int main()
{
// declaration section
int number, // number input by the user
digit, // digit of number being processed
digit_tally[DIGITS], // keeps track of digits seen
i; // general array-element counter
// Initialize digit tally to all zeroes, indicating that no repeated digits have been found
for (i = 0; i < DIGITS; i++)
{
digit_tally[i] = 0;
}
// input section
cout << "Enter a number (any negative number to exit): ";
cin >> number;
// processing section
while (number > 0)
{
digit = number % 10;
if (digit_tally[digit] == 0)
{
digit_tally[digit] = 1;
}
else if (digit_tally[digit] == 1)
{
cout << "Repeated digits: ";
for (digit_tally[digit] = 1; digit_tally[digit] <= 10; digit_tally[digit]++)
cout << number << " ";
}
number = number / 10;
cout << endl;
}
}
For reference, the output should look something like this:
Enter a number (any negative number to exit): 64246
Repeated digits: 4 6
Upvotes: 0
Views: 76
Reputation: 975
for (digit_tally[digit] = 1; digit_tally[digit] <= 10; digit_tally[digit]++)
cout << number << " ";
This takes the value at digit_tally[digit], sets it to 1, then runs the loop while it goes 1 through 10, and will just spit out the same number over and over.
If you want to loop through the array, you'd set it up like the first for loop (and it's important that you start from 0 and that you have < DIGITS, not <=.
Don't be confused, all loops can accomplish the same tasks with some minor tweaks.
for (i = 0; i < DIGITS; i++)
{
digit_tally[i] = 0;
}
is semantically the same as
i = 0
while (i < DIGITS)
{
digit_tally[i] = 0;
++i
}
Upvotes: 0
Reputation: 4025
As you have got the logic of storing the number of occurrences in the index. You can proceed with that approach and once you finish lopping through the entire number, have another loop that prints the index that has more than 1 occurrence.
while (number > 0)
{
digit = number % 10;
digit_tally[digit -1] += 1;
number = number / 10;
cout << endl;
}
for ( int i = 0; i < 10; ++i)
{
if (digit_tally[i] > 1)
{
std::cout << i + 1 << " ";
}
}
Upvotes: 1