Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a variable result at 0 and add x to it x amount if times). Then run the program using that square().
I'm having trouble representing x*x with addition. Below is my code thus far. Disregard the #include directive and the keep_window_open() at the end. Those were from the book I'm reading.
Any help is greatly appreciated.
# include "../../../std_lib_facilities.h"
int square(int x, int j)
{
int n = 0;
for (n=0; n < j; ++n)
{
x = x + 1;
}
return x;
}
int main ()
{
int i = 0;
int j = 0;
for (i=0; i<100; ++i)
{
cout << i << '\t' << square(i, j) << '\n';
++j;
}
But neither main() nor square() require j. In main only i is needed in the loop. What square() does internally is of no concern to the the rest of the program, it simply needs to receive a single parameter x, and return a single result. If extra variables are required, keep them self-contained within the square function.
Now think about the function square(). You own opening post gives a description:
start a variable result at 0 and add x to it x amount if times
It actually suggests a name and initial value for one of the variables which will be required. Now you just need a loop, which of course will require another variable (call it n if you like) to count the iterations. At the end of the loop, simply return the result.