Multiplication using repeated addition problem

This code works on everything expect when I input a 0 for the second number... when I enter a 0 for the second number I just get the value of the first number as the result rather than 0.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  cout << "Please enter the first number\n";
cin >> left;
cout << left << " * " << endl;
cout << "Please enter the second number\n";
cin >> right;
if (left == 0 || right == 0)
    {
    result = 0;
    }
else
  { 
  count = 1;
  while (count <= right)
  {
		result = result + left;
		count++;
   }
   }
cout << left << " * " << right << " = " << result << endl << endl;
cout << "Checking my math using the built-in operators\n\n";
awnser = left * right;
cout << left << " * " << right << " = " << awnser << endl;


I'm not sure what I'm missing!
Last edited on
So first of all in the while loop result assuming you didn't give it a value above it is equal to garbage so what you are doing is garbage = garbage + 1. So rewrite it to be
1
2
3
4
5
6
while (count <= right)
  {
                result = 0; 
		result = result + left;
		count2++;
   }


Furthermore, take note that I changed count to count2 as count is a function in c++ and might cause some confusion for the compiler. It shouldn't as the algorithm library isn't called, but better safe then sorry.

When I complied with those changes I got

Please enter the first number
5
5 *
Please enter the second number
0
5 * 0 = 0

Checking my math using the built-in operators

5 * 0 = 0
Thank you!
closed account (iAk3T05o)
Your computer knows 5 * 0 or 0 * 5 is 0 so there is no need for that code.
Topic archived. No new replies allowed.