I am attempting to implement square() without using the multiplication operator; that is, do x*x by repeated addition. For some reason, however, the number is only being added once, so I am getting x+x rather than x*x. Can anyone offer any suggestions as to what I am doing wrong? Many thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int number = 0;
int result = 0;
cout<<"What would you like to square? ";
cin>>number;
result = number;
for (int counter = number; counter <= 0; counter--);
{
result += number;
}
cout<<"\nThe answer is: " <<result;
for (int counter = number; counter <= 0; counter--)
should be for (int counter = number; counter > 0; counter--)
Also set result to 0, not number, or loop one less time.
for (int counter = number; counter > 0; counter--);
The semicolon at the end of this makes this repeat until counter is no longer > 0, then it executes the lines in brackets once and spits out the answer