loops: countdown until matching digits
Mar 6, 2022 at 6:58am UTC
Goal:
Write a program that takes in an integer in the range 11-100 as input. The output is a countdown starting from the integer, and stopping when both output digits are identical. Note: End with a newline.
For coding simplicity, follow each output number by a space, even the last one.
Use a while loop. Compare the digits; do not write a large if-else for all possible same-digit numbers.
If the input is:
93
Output is:
93 92 91 90 89 88
current code output:
93
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
using namespace std;
int main() {
int input;
int left;
int right;
int sameDigit;
cin >> input;
if ((input < 11) && (input > 100)){
cout << "Input must be 11-100" ;
}
else {
right = input%10;
left = input/10;
sameDigit = (left == right);
while (sameDigit == true ){
cout << input << " " ;
}
if (sameDigit == false ){
cout << input << " " ;
input = input - 1;
}
}
cout << endl;
return 0;
}
Mar 6, 2022 at 8:01am UTC
if ((input < 11) && (input > 100)
How can a number be < 11 and > 100 at the same time ?
Mar 6, 2022 at 11:00am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main() {
int input {};
std::cin >> input;
if ((input < 11) || (input > 100))
return (std::cout << "Input must be 11-100\n" ), 1;
for (; (input % 10) != (input / 10); --input)
std::cout << input << ' ' ;
std::cout << input << '\n' ;
}
Mar 8, 2022 at 2:37am UTC
thanks @thmm !! I think that was one of my main issues!!
----
Here's the fixed program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <iostream>
using namespace std;
int main() {
int input;
int left;
int right;
int sameDigit = false ;
cin >> input;
while ((input >= 11) && (input <= 100))
{
right = input%10;
left = input/10;
if (left == right){
sameDigit = true ;
}
if (sameDigit == false ){
cout << input << " " ;
input = input - 1;
cin >> input;
}
if (sameDigit == true ){
cout << input << " " ;
break ;
}
}
if ((input < 11) || (input > 100))
{
cout << "Input must be 11-100" ;
}
cout << endl;
return 0;
}
Last edited on Mar 8, 2022 at 2:37am UTC
Topic archived. No new replies allowed.