Saturday, July 16, 2011

C++ code disassemble 1

Feel like starting a little series when I post basic C++ code and I disassemble it to easily understand. Enjoy.

The Guessing Game
I will be explaining how this code works. It is a basic number guessing game.
Code:


#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;


int main()
{
srand(time(0));
int x, y = (rand() % 10) + 1;


do
{


cout << "Guess a number between 1 and 10." << endl;
cin >> x;


if (x == y)
cout << "You are right!" << endl;
else if (x>y)
cout << "Too high! Guess again." << endl;
else if (x<y)
cout << "Too low! Guess again." << endl;


}


while (x!=y)


;system("PAUSE");
  return 0;
;}


Now this is a poorly coded game but that isn't the point. Also to note this code will only work on Windows machines because of the system("PAUSE") code. Now time to disassemble the code!



#include <iostream>
#include <cmath>
#include <cstdlib>              Get the required libraries. 
#include <ctime>                

using namespace std;       Declare you are using namespace std.

int main()                           States main is an integer.
{
srand(time(0));                              \
int x, y = (rand() % 10) + 1;            -> Create a randomly generated number to guess.                                          
                                                              
do

{

cout << "Guess a number between 1 and 10." << endl;     Output the following.
cin >> x;                                                                                    Let the user input a guessing number.

if (x == y)                                                                                  Compare x and y.
cout << "You are right!" << endl;                                           Output the following.
else if (x>y)                                                                               If x > y do the following.
cout << "Too high! Guess again." << endl;                          Output the following.
else if (x<y)                                                                               If x< y do the following.
cout << "Too low! Guess again." << endl;                            Output the following.

}  Closing bracket for do statement.

while (x!=y)      While x doesn't equal y pause.

;system("PAUSE");    Pause code.
  return 0;                      Return 0.
;} Closing bracket for do while statement.


Hope you can use this code as a review. Thanks for reading!

No comments:

Post a Comment