Squaring in a for statement.

I tried squaring an int and got a bit of code on a previous forum but my result is always 2048. This is a little drill in a book. There are 64 spaces on a chess broad and the inventor says to the Emperor, "I want 2 grains of rice for each space." 2 for the first, 4 for the second, etc. Could I get a bit of help with this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Iteration by squaring grains of rice 64 times.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}
int main() 
{  
int input;
const int spaces = 64;
int result;


while (cin >> input){
	for (int counter = input; counter > 0; counter--){
		result += input;
		}
	cout << "Result is " << result << " grains of rice." << endl;
	}
return 0;
}
Squaring involves multiplication. Where is any multiplication occurring in your code?

Also, result is not initialized to any value, so it may be anything.
Last edited on
"I want 2 grains of rice for each space." 2 for the first, 4 for the second, etc.

That is doubling, not squaring. i.e. multiplication by 2.
@Chervil

2^2=4?

Aceix.
I just copied the code from something similar on squaring. Sorry for my misinterpretation. The books says it calls for doubling I thought it was squaring. Is there anyway to do this in a for loop?
Is there anyway to do this in a for loop?

There is more than one way, choose whichever you prefer. For example add the value to itself to give the new value. Or multiply the value by 2 to give the new value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}
int main() 
{   const int spaces = 64;
    long long result = 1;

    for (int counter=1; counter<=64; counter++)
    {   result *= 2; 
	    cout << "Square " << counter << " = " << result << " grains of rice." << endl;
	}
    keep_window_open();
return 0;
}


Note that the result will overflow a 64 bit integer at square 62.
Topic archived. No new replies allowed.