simulating the square() function

Hi all,

I have the following exercise to complete:

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;
}

keep_window_open();
}
Last edited on
Why does square have two parameters?
I didn't want to use variable x as my loop variable so I introduced 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.
Last edited on
I've updated my program accordingly. But I'm still having difficulty representing x*x by repeated addition.

# include "../../../std_lib_facilities.h"

int square(int x)
{
// insert code here.
return x;
}
int main ()
{
int i = 0;
for (i=0; i<100; ++i)
{
cout << i << '\t' << square(i) << '\n';
}

keep_window_open();
}
Well, that looks ok as an outline.

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.
Alrighty, thanks Chervil. I will try this.
I would also use a nested for loop

1
2
3
4
5
6
7
8
9
10
11
12
int square(int x)
{
	int result = 0;
	for(int i = 0; i < x; i++)
	{
		for(int j = 0; j < x; j++)
		{
			result++;
		}
	}
	return result;
}
I would also use a nested for loop
But that's horribly inefficient. Say you want to find square(40000), that would require 1,600,000,000 iterations of result++

However, if the instructions are followed, "start a variable result at 0 and add x to it x amount if times", the number of iterations is only 40,000.


Last edited on
Topic archived. No new replies allowed.