### Begginers excercises

Pages: 12
hello , i have started to do the beginners excercises , also if any1 could tell me if any of my codes are going wrong in any place it is much appreciated :)

here is what i came up with when doing the grading programme :

 1234567891011121314151617181920212223242526272829 int grade=0; cout << "Please type in grade from programming class i.e 0-100: "; cin >> grade; if (grade==100) { cout << " you got a perfect score "; } else if ((grade>=90) { cout << " you got a grade A "; } else if (grade>=80) { cout << " you got a grade B "; } else if (grade>=70) { cout << " you got a grade C "; } else if (grade>=60) { cout << " you got a grade D "; } else if (grade>=0) { cout << " you got a grade F" ; }

in regards to your question Moschops i think this code should surfice however i cant seem to get somthing that isnt a number to work but it works for unwanted numbers :
 12345 if ((grade <0) || (grade>100)) { cout << " you have typed in the wrong values please retype the values please : "; cin >> grade; }

a hint as to the direction of screening out non-numbers can be helpful
Last edited on
You've got an extra ( there.

To make it more advanced, what happens if someone enters a number greater than 100, or a negative number, or they enter something that isn't a number at all? Can you write code to handle that situation?
i also have done the beverages excercise the if else style :

 1234567891011121314151617181920212223242526272829303132 int beverage =0; cout << " here are your choices of beverages: " << endl; cout << " 1. water \n" << " 2. coca cola \n" << " 3. vimto \n" << " 4. Pespsi \n" << " 5. Ribena \n" ; cout<< "Please choose beverage: " << endl; cin>> beverage; if (beverage ==1) { cout << " here is your water "; } else if (beverage ==2) { cout << " here is your: coca cola " ; } else if (beverage ==3) { cout << " here is your Vimto "; } else if (beverage ==4) { cout << " here is your Pepsi " ; } else if (beverage ==5) { cout << " here is your ribena " ; } else if ((beverage>=6) || (beverage<=100)) { cout << " error choice is invalid here is your money back " ; }

i have also done it in a switch statement style :

 1234567891011121314151617181920 switch (beverage){ case 1: cout << " Water "; break; case 2: cout << " Coca Cola "; break; case 3: cout << " Vimto "; break; case 4: cout << " Pepsi "; break; case 5: cout << " Ribena "; break; default: cout << " Error choice invalid, here is your money back. "; break; }
Last edited on
here is the first part of while excercise :

 12345678910 while (user !=5) { cout << " enter any number other than 5 "; cin >> user; } if (user ==5) { cout << " u wasn't supposed to enter 5 "; }

the 2nd task :

 123456789101112131415 for (int limit=0; limit<10; limit++) { cout << " enter any number other than 5 "; cin >> user; if (user ==5) { cout << " u wasn't supposed to enter 5 ";break; } } if (user != 5) { cout << " you are patient you win :) "; }

here is the third task :

 123456789 for (limit=0; limit<10; limit++) { cout << " enter any number other than 0 + 1 after each iteration "; cin >> user; if (user==limit) { cout << " u wasn't supposed to enter " << limit;break; } }
Last edited on
I started doing them two days ago. I'm having real trouble with the tic-tac-toe exercise. Can't figure out how to know when the player is about to win and have the computer block him/her without listing every winning combination.
here is the 1st task of the Pancack excercise :

 1234567891011121314151617181920212223 const int PAN = 10; int Number_Eaten[PAN]; int main() { int max = 0; for (int i=0; i> Number_Eaten[i]; if (Number_Eaten[i]>max) { max = Number_Eaten[i]; } } cout << max; cin.get(); return 0; }

like this ? , i dont know why i didnt do that in the first place lol
Last edited on
You should use a loop instead of all these cin/cout in the last program
Where exactly are these beginner exercises?
Hi all,

Here are some things I have noticed:

Switch statements are much better than a long list of else if's, as long as the case expressions are constant ( which is the case here - the beverages program).

The grades program relies on the order of the else if statements, the program could be broken if this is messed up somehow - can you think of a better way to do it? Hint: You might need to do two tests to determine the grade ( although these can both be done in 1 line of code).

TheIdeasMan
Last edited on
Beginner Exercises:
http://www.cplusplus.com/forum/articles/12974/

The beverages program can be even shorter if a string array was used. Then there would be no need for any selection structures.

And for the grade program, I guess you can say it would be broken if the user enters a negative number. I have mine as a switch statement because I divide the inputted score by 10 (which leaves me an integer from 0 to 10).

This is my code for the guessing game:
 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 // This program is supposed to guess a number you picked. // #include #include #include using namespace std; int main(void) { int Guess = 50, Min = 0, Max = 100, Tries = 0, Response; cout << "Think of a number between 1 and 100.\n"; cout << "I'll guess it in 7 tries or less.\n"; cout << "Press ENTER when you're ready.\n"; cin.ignore(); cout << "Press 0 if correct, 1 if too high, 2 if too low.\n"; while (true) { Tries++; cout << "\nIs it " << Guess << "? "; cin >> Response; if (Response == 0) break; else { if (Response == 1) { Max = Guess - 1; Guess = (Max + Min) / 2; } else { Min = Guess + 1; Guess = (Max + Min) / 2; } } } cin.ignore(); //eat the '\n' cout << "\n\nI told you! I guessed it in " << Tries << " tries!"; cout << "\n\nPress ENTER to exit the program."; cin.ignore( numeric_limits::max(), '\n' ); return 0; }

And this is my code for the tic-tac-toe game:
 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191 //A poorly made tic tac toe game #include #include #include #include using namespace std; void ClearBoard(); void ShowBoard(); void PlayerMove(); void CompMove(); bool IsValidMove(int Move); bool IsGameOver(); char Board[3][4]; int main() { char PlayAgain; do { ClearBoard(); for (int Turn = 0; !IsGameOver(); Turn++) { ShowBoard(); if (Turn >= 9) { cout << "Cat's game. It's a tie."; break; } else if (Turn % 2) { CompMove(); } else { PlayerMove(); } } cout << "\n\nPlay again? (Y/N) "; cin >> PlayAgain; } while (PlayAgain == 'Y' || PlayAgain == 'y'); return 0; } void ClearBoard() { char NewBoard[][4] = {"123", "456", "789"}; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) Board[i][j] = NewBoard[i][j]; } void ShowBoard() { cout << string(25, '\n'); for (int i = 0; i < 3; i++) { cout << "\t"; for (int j = 0; j < 3; j++) { cout << ' ' << Board[i][j] << ' '; } cout << '\n' << endl; } cout << string(5, '\n'); } void PlayerMove() { int PMove; cout << "Player's move: "; cin >> PMove; PMove--; while (!IsValidMove(PMove)) { cout << "\nInvalid move. Try again."; cin.clear(); cin.sync(); cin.ignore(); ShowBoard(); cout << "Player's move: "; cin >> PMove; PMove--; } Board[PMove / 3][PMove % 3] = 'X'; } void CompMove() { int CMove = -1; for (int i = 0; i < 3; i++) { //Obviously not all 3 are the same, or else the game would be over //But just because it's not the same, does not mean it's a free spot if (Board[i][0] == Board[i][1] && Board[i][2] < 64) //check the rows CMove = 3 * i + 2; else if (Board[i][0] == Board[i][2] && Board[i][1] < 64) CMove = 3 * i + 1; else if (Board[i][1] == Board[i][2] && Board[i][0] < 64) CMove = 3 * i; else if (Board[0][i] == Board[1][i] && Board[2][i] < 64) //check the columns CMove = 3 * 2 + i; else if (Board[0][i] == Board[2][i] && Board[1][i] < 64) CMove = 3 * 1 + i; else if (Board[1][i] == Board[2][i] && Board[0][i] < 64) CMove = 3 * 0 + i; } //check the diagonals if (CMove < 0) { if (Board[0][0] == Board[2][2] && Board[1][1] < 64) CMove = 4; else if (Board[0][2] == Board[2][0] && Board[1][1] < 64) CMove = 4; else if (Board[1][1] == Board[2][2] && Board[0][0] < 64) CMove = 0; else if (Board[2][0] == Board[1][1] && Board[0][2] < 64) CMove = 2; else if (Board[0][2] == Board[1][1] && Board[2][0] < 64) CMove = 6; else if (Board[0][0] == Board[1][1] && Board[2][2] < 64) CMove = 8; } //occupy center if free if (CMove < 0 && Board[1][1] < 64) CMove = 4; if (CMove < 0) { int FreeTiles = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (Board[i][j] < 64) FreeTiles++; } } srand(time(NULL)); CMove = rand() % FreeTiles; while (!IsValidMove(CMove)) { if (CMove == 8) CMove = 0; else CMove++; } } Board[CMove / 3][CMove % 3] = 'O'; } bool IsValidMove(int Move) { return (Board[Move / 3][Move % 3] < 64); } bool IsGameOver() { if ((Board[1][1] == Board[0][0] && Board[1][1] == Board[2][2]) || (Board[1][1] == Board[0][2] && Board[1][1] == Board[2][0])) { if (Board[1][1] == 'X') cout << "Player wins!"; else cout << "Computer wins!"; return true; } else for (int i = 0; i < 3; i++) { if (Board[i][0] == Board[i][1] && Board[i][0] == Board[i][2]) { if (Board[i][0] == 'X') cout << "Player wins!"; else cout << "Computer wins!"; return true; } else if (Board[0][i] == Board[1][i] && Board[0][i] == Board[2][i]) { if (Board[0][i] == 'X') cout << "Player wins!"; else cout << "Computer wins!"; return true; } } return false; }

I haven't finished the dungeon crawl game yet. I think I will need to learn to create and use classes first.
Last edited on
I've spent the past two hours working on the dungeon crawler game, but there is a bug that I can't figure out.

The program doesn't respond to player control correctly. For example, I tell it to go right, but it goes up. I tell it to up, and it goes to the lower right. But sometimes it works correctly.

I have no idea which part of my code is responsible for it. Below is all of the code for the program. The lines relevant to player input is 120 to 151.

EDIT: I figured it out... I didn't initialize the a and b variables in the function that controls the player. That meant it worked fine when I was moving diagonally, because I was setting both their values since I was moving in two axes. But when I was moving in a single axis, I was only setting one variable and ignoring the other one, which means it had random garbage and led to unpredictable movement.

 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223 //WIP: Dungeon Crawler Game #include #include #include #include #define HEIGHT 10 #define WIDTH 10 using namespace std; class MapObject { public: int x, y; char icon; MapObject(int type); void MoveRandom(); bool MovePlayer(int PMove); }; void NewMap(); void DisplayMap(); bool IsGameOver(); bool IsValid(int x, int y); int IsOccupied(int x, int y); int Map[HEIGHT][WIDTH]; int main() { int PMove; char PlayAgain; do { //Set up for a new game srand(time(NULL)); NewMap(); //Create the player and other 'sprites' vector MySprites; MySprites.push_back(MapObject(80)); //80 is the ascii code for 'P' MySprites.push_back(MapObject(88)); //88 is the ascii code for 'X' for (int i = rand() % 3 + 2; i > 0; i--) { MySprites.push_back(MapObject(84)); //84 is the ascii code for 'T' } for (int i = rand() % 3 + 2; i > 0; i--) { MySprites.push_back(MapObject(69)); //69 is the ascii code for 'E' } vector::size_type VecSize = MySprites.size(); DisplayMap(); //Loop until the game is over do { std::cout << std::string(4, '\n'); //Loop until we get some valid input do { std::cout << std::endl << "Enter a number to move (check your numpad): "; cin >> PMove; } while (!MySprites[0].MovePlayer(PMove)); //Move the enemies for (int i = 1; i < VecSize; i++) { MySprites[i].MoveRandom(); } DisplayMap(); } while (!IsGameOver()); cout << "Play again? (Y/N) "; cin >> PlayAgain; } while (PlayAgain == 'Y' || PlayAgain == 'y'); return 0; } //Constructor for map object class MapObject::MapObject(int type) { icon = type; do { x = rand() % WIDTH; y = rand() % HEIGHT; } while (IsOccupied(x, y)); Map[y][x] += type - 42; } //Map object function to move to a random adjacent spot void MapObject::MoveRandom() { //return if not enemy object if (icon != 69) return; //count and store available spots int GoodSpots = 0, PosX[8], PosY[8]; for (int i = y - 1; i < y + 2; i++) for (int j = x - 1; j < x + 2; j++) if (IsValid(j, i)) if (IsOccupied(j, i) < 2) { PosX[GoodSpots] = j; PosY[GoodSpots] = i; GoodSpots++; } //pick one of the available spots //and 'move' to it int MyPos = rand() % GoodSpots; Map[PosY[MyPos]][PosX[MyPos]] += 69 - 42; Map[y][x] -= 69 - 42; x = PosX[MyPos]; y = PosY[MyPos]; } //Function that handles the player input //Only returns true if the player can move to the indicated spot bool MapObject::MovePlayer(int PMove) { int a, b; //return if not player... if (icon != 80) return false; //check for valid input if (PMove < 1 || PMove > 9 || PMove == 5) return false; //change the input to coordinates if (PMove > 6) b = y - 1; else if (PMove < 4) b = y + 1; if (PMove % 3 == 0) a = x + 1; else if (PMove % 3 == 1) a = x - 1; if (!IsValid(a, b)) return false; Map[b][a] += 80 - 42; Map[y][x] -= 80 - 42; x = a; y = b; return true; } //Clears the 'map', resetting it to default void NewMap() { for (int i = 0; i < HEIGHT; i++) for (int j = 0; j < WIDTH; j++) Map[i][j] = 42; } //Displays the 'map' on the screen void DisplayMap() { char ch; std::cout << std::string(50, '\n'); for (int i = 0; i < HEIGHT; i++) { std::cout << "\t"; for (int j = 0; j < WIDTH; j++) { ch = Map[i][j]; std::cout << " " << ch << " "; } std::cout << std::endl; } } //Checks if the game is over //Outputs appropriate messages bool IsGameOver() { for (int i = 0; i < HEIGHT; i++) for (int j = 0; j < WIDTH; j++) if (Map[i][j] > 100) { if (Map[i][j] == 80 + 88 - 42) std::cout << "\n\nYou won! "; else if (Map[i][j] == 80 + 84 - 42) std::cout << "\n\nWatch out for those traps! "; else std::cout << "\n\nYou were eaten! "; return true; } return false; } //Check if the coordinates are within the bounds of the map bool IsValid(int x, int y) { if (x >= WIDTH || x < 0 || y >= HEIGHT || y < 0) return false; else return true; } //Check if the coordinates are occupied //returns an int indicating occupied by what int IsOccupied(int x, int y) { switch (Map[y][x]) { case 80: //'P' for player return 1; case 69: //'E' for enemy return 2; case 84: //'T' for trap return 3; case 88: //'X' for goal return 4; default: return 0; } }
Last edited on
 And for the grade program, I guess you can say it would be broken if the user enters a negative number. I have mine as a switch statement because I divide the inputted score by 10 (which leaves me an integer from 0 to 10).

Dividing by 10 might seem aggod idea, but what if things change in the future?

Imagine the school wants to give addittional grades like A+,A-, B+, B-, C+,C-.
Dividing by 20 now, and the code is tarting to be messy.

So, see if you can work out a better way given my clue in an earlier post.

 Hint: You might need to do two tests to determine the grade ( although these can both be done in 1 line of code).

TheIdeasMan
here is the 2nd task for the pancake excercise i had to find the min value as well as max :

 123456789101112131415161718192021222324 int Number_Eaten[PAN]; int main() { int max = Number_Eaten[PAN]; int min = Number_Eaten[PAN]; for (int i=0; i> Number_Eaten[i]; if (Number_Eaten[i] > max) { max = Number_Eaten[i]; } else if (Number_Eaten[i] < min) { min = Number_Eaten[i]; } } cout << max << endl; cout << min;

the min algorith seems sound to me however i cannot get it to work
any pointers as to what is going wrong would be appreciated :)
i have done the first task for the bracket search excercise if u see anything
that i can improve upon let me know :)

 123456789101112131415161718192021222324252627282930313233 int main() { int guess=0; int user =0; srand( time(NULL) ); guess = rand() % 100 + 1; while(user != guess) { cout << " Guess the number from 1 - 100 : "; cin >> user; if (user>guess) { cout << " high "; } else if (user

for the second task here is the source code :

 12345678910111213141516171819202122232425262728293031 int main() { int guess=0; int user =0; int count =0; srand( time(NULL) ); guess = rand() % 100 + 1; while(user != guess) { cout << " Guess the number from 1 - 100 : "; cin >> user; if (user>guess) { cout << " high "; } else if (user
Last edited on
For your pancake problem, I'm assuming that you have a #define PAN 10 somewhere.

What you did first was to declare an array called Number_Eaten that contains 10 elements. This means the array has elements Number_Eaten[0], Number_Eaten[1], ... , Number_Eaten[9].

Then in your main function, you set max and min to Number_Eaten[10] which doesn't exist.
yh i picked up on that but i cant seem to set it to start from the begining of an array , you see what i did was set an element of array i.e
 12 const int PAN = 10; int Number_Eaten[PAN];

than with the loop after each iteration the user enters a number of pancakes they have eaten which is stored in the array Number_Eaten[PAN]

i have also tried placing the max and min like this :
 12 int max = Number_Eaten[0]; int min = Number_Eaten[0];

but no luck

here is full code any advice is helpfull and fg109 thnx for yor reply:

 12345678910111213141516171819202122232425 const int PAN = 10; int Number_Eaten[PAN]; int main() { int max = Number_Eaten[0]; int min = Number_Eaten[0]; for (int i=0; i> Number_Eaten[i]; if (Number_Eaten[i]>max) { max = Number_Eaten[i]; } else if (Number_Eaten[i]
Last edited on
When you assign values for max and min, you haven't input any values into your array yet. I'm not sure whether Number_Eaten[0] is 0 or some random garbage at that point. Either way, it will mess up your program.

What you can do is ask for and take input for Person1 outside of the loop, then initialize your max/min variables to Person1, and enter the loop afterwards.

You could also just try initializing max to 0 and min to 99999, and change the if-else-if to two ifs instead. But depending on what values are input, that might not work so well.
yup it is working now here is the code :

 12345678910111213141516171819202122232425262728 const int PAN = 10; int Number_Eaten[PAN]; int main() { cout << "How many pancakes you eat today "; cin >> Number_Eaten[0]; int max = Number_Eaten[0]; int min = Number_Eaten[0]; for (int i=1; i> Number_Eaten[i]; if (Number_Eaten[i]>max) { max = Number_Eaten[i]; } else if (Number_Eaten[i]
Last edited on
Since you've taken the 1st person out of the loop, you should start the loop with i = 1.
since i forgot to add peoples names in i did that just now :
 12345678910111213141516171819202122232425262728293031323334353637 const int PAN = 10; string Names[PAN]; int Number_Eaten[PAN]; int main() { cout << " enter name : "; cin >> Names[0]; cout << "How many pancakes you eat today "; cin >> Number_Eaten[0]; int max = Number_Eaten[0]; int min = Number_Eaten[0]; string name_max = Names[0]; string name_min = Names[0]; for (int i=1; i> Names[i]; cout << "How many pancakes you eat today "; cin >> Number_Eaten[i]; if (Number_Eaten[i]>max) { max = Number_Eaten[i]; name_max = Names[i]; } else if (Number_Eaten[i]
Pages: 12