Looping technique.

Hello I am not sure as to how to approach this problem,
The inventor of chess wanted his reward and he asked the emperor one grain of rice for the first square, 2 for the second , 4 for the third and so on...doubling for each of the 64 squares. How do i write a program to calculate how many squares are required to give the inventor at least 1000 grains of rice? and at least 1000,000,000?
how can i know the number of rice grains the inventor asked for?
Could someone explain to me the looping technique again.

Thanks.
You can use a for() loop with a couple variables and an if() statement to break out when you've exceeded the number of grain of rice you want.

Alternatively, you could use a while() loop, allowing you to incorporate the conditions into the looping structure.

Documentation on if, for, and while structures:
http://cplusplus.com/doc/tutorial/control/
Last edited on
You can do something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
long total_grains=0;
	const int total_cells_in_chess_board=64;
	for(int i=0; i<total_cells_in_chess_board;i++)
	{
		if(i==0)
			total_grains=1;
		else
			total_grains=2*total_grains;

		if(total_grains>=1000)
		{
			cout << "total cells required is " << i+1 << endl;
			break;
		}
			
	}
You need to do the math by hand and think about this before trying to code it. What is the formula for the amount of rice for one specific square, say square number i ?

rice (i) = ?

Now, total rice is just a sum right? So if you know how to compute rice(i) you just need to do it in a loop accumulating the total.

Depending on the problem you want to solve you will use different a LOOP CONTROL VARIABLE (LCV).

In your first question the total amount of rice is the LCV: while( total < someMax )
You will also need a counter in your loop to track the current square.

I'll let you think about the second one, it is easier and should be done in a for loop.

Last edited on
@anilpanicker: I was recently yelled at for posting a solution, you should think about this as well.

You also combined the two problems, when they should not be.
Last edited on
Topic archived. No new replies allowed.