Write a C++ program for the following. Do not try to generalize this program int
ID: 3882777 • Letter: W
Question
Write a C++ program for the following. Do not try to generalize this program into an equation. The goal is to practice iterations. There is an old story that the emperor wanted to thank the inventor of the game of chess and asked the inventor to name his reward. The inventor asked for 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. That may sound modest, but there wasn't that much rice in the empire! Write a program to calculate the number of squares that are required to give the inventor a stated number of grains of rice that is provided as the input. For example, the program should calculate the number of squares that are required to earn at least 1000 grains of rice, at least 1, 000, 000 grains, at least 1, 000, 000, 000 grains, etc. You'll need a loop, of course, and probably an int to keep track of which square you are at, an int to keep the number of grains on the current square, and an int to keep track of grains of all previous squares. We suggest that you print the value of all your variables for each iteration of the loop so that you can see what's going on. Demonstrate that the program works using sample inputs from the user.Explanation / Answer
Here is the progarm
feel free to make comments with your querys
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int i,square,grains,total_grains;
int user_input;
cout<<"Enter the number of grains ";
cin>>user_input;
square=1; // set the square to first
total_grains=0; // set total grains to zero
for(i=0;i<64;i++) // check until 64 times max
{
grains=pow(2,i); // will return 2^i ,ie when i=2 2^2 = 4 it uses <math.h>
total_grains+=grains; // ie total_grains = total_grains + grains
cout<<" The number of Square : "<<square; // print
cout<<" Number of grains : "<<grains;
cout<<" Total number of grains : "<<total_grains;
if(total_grains>=user_input) // check for user input is satisfied or not
{
cout<<" The minimum number of squesrs requered is : "<<square;
cout<<" Number of grains at current square is : "<<grains;
cout<<" Total number of grains : "<<total_grains;
break; // break the for loop
}
square++;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.