There is a story of the inventor of chess. The king wanted to reward him with riches, but he only asked for the following. One grain of wheat for the first square, two on the second, four on the third, doubling the amount for each square until 64 squares are accounted for.
Design a program for calculating the total number of grains of wheat.
You will want to use iteration/looping. Do not forget to keep track of which square you are on and the number of grains of wheat that you currently have.
i suggest using an array (array[8][8]). Then using a for loop(or a while loop cause you're a hipster) and just have an int that squares every time it loops.
1 2 3 4 5 6 7 8 9 10 11 12 13
int array[8][8];
int ricetotal = 1;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
array[i][j] = ricetotal
ricetotal = ricetotal * 2
}
}
std::cout << "it will take " << ricetotal << " grains of rice to do this";
There's no need for an array. You know that there are 64 squares. The equation to find how much wheat a tile gives is quite simple: 2 ^ square_index. This equation assumes that you start your squares at an index of 0. Then simply loop from 0 to 63 and accumulate the value of all the squares.
#include<iostream>
usingnamespace std;
int main()
{
int n,i,grains=0;
cout<<"enter the square number to find out the grains of rice at it";
cin>>n;
for(i=1;i<=n;i++)
{
grains= grains+(grains*2);
}
cout<<"the number of grains is"<<grains;
return 0;
}