Hello
I have this problem:
--------------------------------------------------------------------------------
4. Write a program that reads in integers of 4 digits and then checks and displays how many 6s and 7s are there in each of them. Use essential while loop in your code. Check the following output:
Enter a number of 4 digits ( -1 to quit): 4743
Number of 6s = 0 Number of 7s=1
Enter a number of 4 digits ( -1 to quit): 3998
Number of 6s = 0 Number of 7s=0
Enter a number of 4 digits ( -1 to quit): 4766
Number of 6s = 2 Number of 7s=1
Enter a number of 4 digits ( -1 to quit): -1
Press any key to continue…….
--------------------------------------------------------------------------------
Its easy for me to write a loop and do everything.
All what I want is to know how can I count the 6's and the 7's in the number??
This is what I did :
-----------------------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
int main ()
{
int number;
cout<<"Enter a number of 4 digits (or -1 to quit): ";
cin>>number;
while (number != -1)
{
cout<<"Enter a number of 4 digits (or -1 to quit): ";
int number;
int temp;
int numSixes, numSevens; // Counts the number of occurrences of each
do
{
numSixes = numSevens = 0;
cout<<"Enter a number of 4 digits (or -1 to quit): ";
cin>>number;
for(int i=0; i<4; i++)
{
// Find the value of the placeholder at 10^i
temp = (int)(number / pow(10.0, i)) - 10*(int)(number / pow(10.0, i+1));
if(temp == 6)
numSixes++;
elseif(temp == 7)
numSevens++;
}
cout<<"Number of sixes: " << numSixes << ", number of sevens:" << numSevens << endl;
}while (number != -1);
This solution will work for any positive integer less than 10^x, where x is the exit condition of the for loop (4 in this case). So, in the above example, you could enter a number with 1, 2, 3 or 4 digits and it should work.
Challenge: change it so that it will work for a positive integer of any number of digits (up to the limit of an int, of course).
Hope that helps.
Oh by the way, I think a 'do-while' loop works better in this case (saves repeating the same lines of code).