The first week of programming

I don’t have much experience in programming. I took two courses in 2008/9 but I don’t have much memory of that.
After our first lecture we were handed a sheet with different exercises that we should have finished this week, our group of friends pretty much aced them in one sitting.

This is on of our exercises.

”Program 26
– Write a program that simulates the guessing game
– The magic number to be guessed should be random at every run of the program
– Let the player input an integer value between 1 and 100
– If the number is lower than the magic number, output that to the player
– If the number is higher than the magic number, output that to the player
– If the number is correct, end the game and congratulate the player
– Let the player guess until they guess the correct magic number
– When the player guesses right, the number of tries should be outputted as well”

The most challenging part of this was a way to generate a random number. When we finally found a way and completed the code we found out that the teachers had included a part of a code that generated a random number.

Anyway this is how I solved this problem

#include
#include

int main(int argc, char* argv[])
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution dis(0, 100);

int magic = dis(gen);
int answer = 0;
int tries = 1;

for (;; tries++){
std::cin >> answer;
if (answer > magic){
std::cout << ”The number is to high! Take a new guess ” << std::endl;
}
else if (answer < magic){
std::cout << ”The number is to small! Take a new guess ” << std::endl;
}
else{
break;
}
}
std::cout << ”You won! It took you ” << tries << ” number of turns” << std::endl;

std::cin.ignore(1024, ‘n’);
std::cin.get();
return 0;
}

It was a fun first week and I hope to learn a lot more in the coming weeks.

About Joakim Ädel

2014  Programming