I am new to c++ and writing code so I was hoping that one of you may be able to help me with this exercise I am trying:
The scenario is that there are 64 squares on a chess board and I need to write a loop that will count the number of grains of rice is 1 grain was added to the first square and then 2 to the second, then 4, then 8 and so forth, so a loop that runs 64 times, doubling a variable each time. So far I have:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int x;
int main(){
for(x =0; x < 63; x++){
cout << x << endl;
}
system("pause"); //this is included only to pause the command line
//to check the output
//return(0);
}
Getting the loop to output 1 on the first pass and then to double the value from their on, that is what I can;t figure out. Thanks in advance
Whats stopping me? I am confused as how to implement it.
If I add a new int variable to represent the rice and call it y, then add into the loop y = y*2 how do I get it to output 1 on the first loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int x;
int y;
int main(){
for(x =0; x < 63; x++){
cout << x << endl;
y = y *2;
cout << y <<endl;
}
system("pause"); //this is included only to pause the command line
//to check the output
//return(0);
}
sorry as coming across as a simpleton but if I assign the value of 1 to y as I declare it before the loop will the calculation not increase y to 2 before it is output to the screen?
To fix your "it has to start at 1": Put the cout BEFORE the new value assignment, then increase your upper loop bound by 1. That way, it will do 65 iterations, but it will only print 64. The final value will be wrong, but it's never outputted, so nobody will notice.
Genius Gamanic, it will now output and then perform the calculation, ha ha one day I will think like a computer (maybe)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int x;
int y=1;
int main(){
for(x =0; x < 63; x++){
cout << y <<endl;
y = y *2;
}
system("pause"); //this is included only to pause the command line
//to check the output
//return(0);
}
Athar what would you suggest as a suitable type of a sufficient size, am I right in thinking its all related to memory?
Shouldn't a regular (unsigned) int be sufficient on a 64bit system?
[edit]
If you notice the number's aren't correct for higher values (check with windows calculator, it can handle quite large numbers), try adding the word "long" before your int declaration.