Program 15

1)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 times).

2) Then run some versions of "the first program" using that square().

I think that to implement part 1 I need to use a for loop? Here is something I put together

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 #include<iostream>
#include<string>
#include<algorithm>
#include<cmath>

using namespace std;

int main()

{

int square(int x)

{

int x=0;                                // Starts a variable result at 0

return
  
for (int x=0;x==x;x+=x)                // adds x to it x times
++x; 



}


}

Last edited on
I haven`t had much time lately but here is the code with at leat (hopefully) a definition a square followed by a main function where I use this square that I just implemented:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>

using namespace std;



int square(int n)

{

int n=0; 

for (int n=0;n==n;n+=n)             
++n;

return n;

}


int main()

{




for (int i=0; i<100; ++i)

cout << i << '\t' << square(i) << '\n';

   
}                       


 



Anything right?
1
2
3
int square(int n)
{
    int n=0; 

n is already defined by the parameter of the function, you are trying to re-define a variable that already exists.

1
2
for (int n=0;n==n;n+=n)             
++n;

You once again try to re-define n in this for loop, same problem as before.

Also, n==n will always be true, so your for loop will loop infinitely.
Last edited on
Topic archived. No new replies allowed.