Hello, I'm stuck with how to properly advance my loops to test for the conditions provided for an assignment I'm working on. The conditions for this four digit number are: (1) all four digits are different, (2) the digit in the thousands place is three time the digit in the tens place, (3) the number is odd, and (4) the sum of the number is 27. Your program should use a loop (or loops) to solve this problem. I have figured out the number is: 9837 and I have begun coding the required loops to test for the conditions, but I'm pretty lost with how to advance from extracting the number to testing each individual digit for the required conditions I listed above.
#include <iostream>
usingnamespace std;
int main()
{
int streetAddress;
cout << "\nBatman, this is Pappa Bear, we are computing the address now....." << endl;
for (int i = 1001; i <= 9999; i +=2)
{
int ones, tens, hundreds, thousands;
for (i = i; i > 10; i = (i % 10)) {
//Confused as to the proper syntax to assign each extracted digit to an int variable (ones, tens, etc.,)
}
// Also am not sure how to test if each individual integer is different
thousands = tens * 3;
27 = ones + tens + hundreds + thousands;
cout << "the Riddler is at " << streetAddress << " 7th Ave. Go get'em!" << endl;
}
return 0;
}
Firstly, you are breaking out of the loop on the first iteration. Whether the if-clause is true or not, the next line will print 'steetAddress' (which is garbage on the first iteration), and then break out of the loop.
Second, why are you subtracting 34 and 37 to get the tens and hundreds place? What you need to do is assign i to another variable. Then continuously get the last digit of it and diving it by 10; You also need to check that the thousands digit is <= 9.
#include <iostream>
usingnamespace std;
int main()
{
int streetAddress;
cout << "\nBatman, this is Pappa Bear, we are computing the address now....." << endl;
for (int i = 1001; i <= 9999; i +=2)
{
int ones, tens, hundreds, thousands;
int number = i; // save 'i' in 'number' so we can parse it
ones = number % 10; number /= 10; // last digit is ones, divide by 10
tens = number % 10; number /= 10; // last digit is tens, etc...
hundreds = number % 10; number /= 10; // last digit is hundreds, etc..
thousands = tens * 3;
if ( thousands <= 9 && (27 == thousands + hundreds + tens + ones) )
{
streetAddress = i;
}
}
cout << "the Riddler is at " << streetAddress << " 7th Ave. Go get'em!\n";
return 0;
}
Omg thank you so much I was so confused about how to parse the 'i' so I could extract multiple digits from it and evaluate them all with the modulus operator.