I’m trying to make a cpp program that asks the user for two number inputs. Then print from 1 to the first number the user entered or until the first multiple of the second number. Print "Multiple of X(second number)" if the number is a multiple of the second input. using Do while loop.
This is what I managed to do so far.
int main()
{
std::cout << "enter two numbers: ";
int first = 0;
int second = 0;
std::cin >> first >> second;
if(second != 0 && first%second == 0)
std::cout << first << " is a multiple of " << second << '\n' ;
else
{
int n = 0;
int maxval = second*2 > first ? first : second*2;
do
std::cout << ++n << '\n';
while(n < maxval);
}
}
I’m hoping someone can help me fix the code or point out what’s wrong/missing in it.
Input should be any two numbers
then output should print numbers from 1 until the first number OR until the first multiple of the second number if it comes before the first number.
Example:
Enter two numbers: 10
7
1
2
3
4
5
6
Multiple of 7
>Solution :
You should use break when you get to the target number.
#include <iostream>
int main() {
std::cout << "enter two numbers: ";
int first = 0;
int second = 0;
std::cin >> first >> second;
if (second != 0 && first % second == 0)
std::cout << first << " is a multiple of " << second << '\n';
else {
int n = 0;
int maxval = second * 2 > first ? first : second * 2;
do {
if (++n % second == 0) {
std::cout << "Multiple of " << second << '\n';
break;
} else {
std::cout << n << '\n';
}
} while (n < maxval);
}
}
https://cplayground.com/?p=marmoset-tiger-vicuna