Hi so im just a beginner in c++ programming and we have a task to do that we multiply 2 numbers without using * and using while/do while. can anyone help me with my problem?
also the output must be like:
5+5+5+5+5=25.
which means 5x5
Thanks!
#include <iostream>
#include <limits>
int main()
{
// <--- Define variables
int num1{}, multiplier{}, total{};
std::cout << "\n Enter number: ";
std::cin >> num1;
std::cout << "\n Enter multiplier: ";
std::cin >> multiplier;
while (multiplier-- > 0)
total += num1;
std::cout << "\n Your answer is: " << total << std::endl;
// The next line may not be needid. If you have to press enter to see the prompt it is not needed.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();
return 0;
}
Hi so im just a beginner in c++ programming and we have a task to do that we multiply 2 numbers without using * and using while/do while. can anyone help me with my problem?
also the output must be like:
5+5+5+5+5=25.
which means 5x5
Just to be sure, does that mean:
cannot use *
AND
must use while or do..while
a poor reader could see it as:
cannot use *
AND
cannot use while or do..while
Another: the output. Is it exactly:
5+5+5+5+5=25
rather than mere
25
PS. 5*5 is an "ambiguous" example, because operands are equal.
What are you allowed to do with 2*3?
Is it 2+2+2=6 or 3+3=6
What about 3*2? Same or the other answer than for 2*3?
There is a danger in "sample code" that one might fall into mechanically copying from it rather than learning from it. The more you have to think yourself, the better for you.
The course should have touched the necessary topics before giving you homework.
this is similar to the powers problem.
take 6*7 for example.
first, you have a choice here: you can loop 6 times, or you can loop 7 times.
that is, 6+6+6+6+6+6+6 = 42 AND
7+7+7+7+7+7 = 42 as well. so you can loop less times to do less work by checking the values.
but you can reduce it even more.
the bottom one is
7+7 = 14,
14+14+14 = 42.
so you can sub-divide the problem to do even less work.
this is silly, but its worth thinking about... I wouldn't expect you to write all that but its an example of how a simple and obvious problem can be done with less work if you wanted to code up the extra logic. Its not going to make a bit of difference for small numbers, but if you had 123456 * 987654 or something, it could be done a lot faster than the brute force loop. Here, you hace a choice of doing 10 times as many loops if you pick the second value instead of the first as the loop control.... (the first tweak I mentioned) and some log type reduction if you do the sub-division (probably doing 10-20% of the number of iterations (not in the mood to figure out how many you need to do precisely)).