If I enter an amount of 5 players (5 elements in the score[] array) in the scanf("%d", &numPlayers) the for loop cycles the players all the way up to player 5 (element 4 of score[]), and then jumps to the winMsg function. The score of that element is a large value, even though I set all the score[] element's to 0 in the first for loop. If I enter 6 or more elements, the second for loop never executes. Program runs no problem with 4 or less elements in score[]. I am using gedit and terminal in Ubuntu. Any ideas? Fairly new to programming. I appreciate any help.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int rollDie(){
return (rand()%6 + 1);
}
void winMsg(int winRoll, int player, int winScore){
printf("Congratulations Player %d! Your winning roll was a %d, putting your score at %d!\n\nGame Over\n\n", player + 1, winRoll, winScore);
return;
}
int main(){
srand(time(NULL));
int numPlayers = 0;
int roll = 0;
int i = 0;
int score[numPlayers];
char choice[2];
printf("Welcome to the \"Roll to Win\" game. Each roll adds to the current player's score, according to the die's number. A roll of 1 will cause the player to recieve no points that round, and then be skipped to the next player. First player to reach 100 or over wins! Please enter number of players: \n\n");
scanf("%d", &numPlayers);
printf("\n");
while (numPlayers >= 100 || numPlayers <= 0){
printf("Please enter a number of players less than 100, greater than 0.\n\n");
scanf("%d", &numPlayers);
printf("\n");
}
for (i = 0; i < numPlayers; ++i){
score[i] = 0;
printf("Set Player %d score to %d.\n", i + 1, score[i]);
}
printf("Starting with Player 1.\n\n");
for (i = 0; i < numPlayers; ++i){
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
}
else{
do{
score[i] += roll;
if (score[i] >= 100){
winMsg(roll, i, score[i]);
exit(0);
}
printf("Player %d rolled a %d, continue rolling (enter r to roll, or sr to stop rolling)? Current score: %d.\n\n", i + 1, roll, score[i]);
scanf("%s", choice);
printf("\n");
while ((strcmp ("r",choice) != 0) & (strcmp ("sr",choice) != 0)){
printf("Please enter a correct selection (enter r to roll, or sr to stop rolling).\n\n");
scanf("%s", choice);
printf("\n");
}
if (strcmp ("sr",choice) == 0){
printf("Player %d decided to stop rolling. Continuing to next player.\n\n", i + 1);
break;
}
roll = rollDie();
if (roll == 1){
printf("Player %d rolled a 1. Skipping turn. Current score: %d.\n\n", i + 1, score[i]);
break;
}
} while (strcmp (choice,"r") == 0);
}
if (i == numPlayers - 1){
i = -1;
}
}
}
Notice, that you set the size when initializing array before it is known, therefore you end up with garbage.
Doing int score[numPlayers]; and later scanf("%d", &numPlayers); will not do what you think it does.
it is not standard C++ to have a static array size which is not a constant,if you want that behavior you should use std::vector.
Even if this is working for you, then you should first ask for the number of players and then create the array. i.e
scanf("%d", &numPlayers);//first
....
int score[numPlayers];//then
Related
I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}
The code shuts down after executing the while loop and does not execute the last 2 printf statements. I don't know whats wrong.. after the loop goes around for the chosen times the program just closes.
#include <stdio.h>
int main()
{
int numberofq;
int questionansc;
int questionansic;
int counter;
int answer;
numberofq = 0;
questionansc = 0;
questionansic = 0;
counter = 0;
answer = 0;
while(numberofq <1 || numberofq >5)
{
printf("Hello enter the amount of questions you want between 1 and 5 \n");
scanf("%d", &numberofq);
} // End While
//Program runs until the counter is less than users wanted question number.
while (counter < numberofq)
{
//Question 1
printf("Question 1. what is 2+2? \n");
scanf("%d" , &answer);
//if users answer is equal to 4.
if (answer == 4)
{
printf("You entered %d, you are correct\n", answer);
questionansc = questionansc +1;
} //End If
//If the answer is not equal to 4.
else
{
printf("You entered %d, you are wrong correct answer is 4 \n", answer);
questionansic = questionansic +1;
} // End Else
counter = counter +1;
//End Question 1.
} //End While
printf("You got %d questions correct \n" , questionansc);
printf("You got %d questions wrong" , questionansic);
flushall();
return 0;
} // End Main`
It actually prints them and then exits, but it exits so quickly you don't have a chance to see this.
You can pause execution using system("pause") on Windows, but that's considered bad practice. You could use getch() or something, but you could also simply invoke the program from an existing CMD/Terminal and in this way the output will stay there after the program is done.
My professor gave me a asignment to write a 16 matches Nim game.
One part of a task is to make PC to make moves as well. So, I tried to solve the problem by using SRAND but PC picked the same row and the same amount of sticks. What is more, PC also takes emty rows wich and hits the wall when he takes the zero massive.
So, thats is what I hve already done. Any thoughts?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define row 4
int main()
{
int theChecker = 1, sticks[row] = {1,3,5,7}, stickSum, i, choiceRow, choiceStick, pcRow, pcStick;
char answer;
do
{
printf("\n\n\t ************ \n");
printf("\t *THE NIM GAME* \n");
printf("\t ************ \n\n");
stickSum = sticks[0] + sticks[1] + sticks[2] + sticks[3];
while(stickSum > 0)
{
printf("\nStick log:\n");
for(i = 0; i < row; i++)
printf("Row %d: %d\n", i+1, sticks[i]);
printf("\n");
if(theChecker == 1)
{
printf("Choose a row: ");
scanf("%d", &choiceRow);
printf("Choose a sick: ");
scanf("%d", &choiceStick);
while((choiceRow <= 0) || (choiceRow > 4) || (sticks[choiceRow - 1] < choiceStick) || (choiceStick == 0))
{
printf("\n\t !!!ERROR!!!\n\tInvalid row or stick\n\nCheck stick log above\n\n");
printf("Choose a row: ");
scanf("%d", &choiceRow);
printf("Choose a sick: ");
scanf("%d", &choiceStick);
}
sticks[choiceRow-1] -= choiceStick;
stickSum -= choiceStick;
}
else //pc move starts-------------------------------------------
{
while(((pcRow <= 0) || (pcRow > 4)) && sticks[choiceRow - 1] == 0)
{
time_t seconds;
seconds = 0;
time(&seconds);
srand((unsigned int)seconds);
pcRow = rand() % 4;
}
printf("PC ROW: %d\n", pcRow);
while((sticks[pcRow - 1] < pcStick) || (pcStick == 0))
{
time_t seconds2;
seconds2 = 0;
time(&seconds2);
srand((unsigned int)seconds2);
pcStick = rand() % 16;
}
printf("PC STICK: %d\n\n", pcStick);
sticks[pcRow-1] -= pcStick;
stickSum -= pcStick;
}
if((theChecker == 1) && (stickSum == 0))
printf("\n\n!!!GAME OVER!!! You took the last stick!!!\n\n");
else if((theChecker == 2) && (stickSum == 0))
printf("\n\n!!!CONGRATS!!! You won!!!\n\n");
theChecker++;
if(theChecker == 3)
theChecker -= 2;
}
printf("\nPress r to restart the game or any key to end the game: ");
scanf("%c", &answer);
printf("\n");
}
while(answer == 'r');
return 0;`enter code here`
}
Don't call srand() more than once, it's used to initialize the random seed, which you are always initializing to the same value, the internal state gets reset over and over, always producing the same pseudo-random values.
I say that you always pass the same seed, because time() has seconds resolution, and in once second, the whole game was played and terminated.
You just need a call to srand() at the beginning of the program to prevent the program from choosing the same values across runs of the program, not in the same run.
I am working on this currency project, it is supposed to output how many ways there is to makeup change,
For example when I input 2 dollars the program should output 293 ways.
I got the program to work but couldn't get the program to print the proper result
for example I want the program to print out
There are [the number of ways] ways to make up [user input]
but my program doesn't printout the last part [user input]
output of the code below is [when entered 2]
There are 293 ways to make up // The user input is missing
#include <iostream>
#include <cmath>
using namespace std;
int currency[11] = { 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5 };
int f20(int n, int j)
{
int i = 0, t;
if (n == 0) return 1;
else
{
if (n<5) return 0;
}
for (t = 0; t<11; t++)
if (n >= currency[t] && j >= currency[t])
i += f20(n - currency[t], currency[t]);
return i;
}
int main(void){
int counter;
float usernum;
do{
cout << "Enter Total amount:";
cin >> usernum;
usernum = usernum * 100;
for (counter = 0; counter<11; counter++)
if (currency[counter] <= usernum)
{
printf("There are %d ways to make up \n\n", f20(usernum, currency[counter]), usernum); break;
}
} while (usernum != 0);
return 0;
}
The problem is in your if statement. currency[0] equals 10000. If usernum = 2 at first then usernum*100 = 200. Now, is 10000 < 200? No, so it evaluate to false, and you answer is not displayed. Rethink you condition.
Well don't you think it should be -
printf("There are %d ways to make up %d \n\n", f20(usernum, currency[counter]), usernum); break;
instead of -
printf("There are %d ways to make up \n\n", f20(usernum, currency[counter]), usernum); break;
You missed a %d
Thanks everyone for the help, i took ooga's advice and got rid of printf and inserted cout instead and fixed the problem.
cout << "There are " << f20(usernum, currency[counter]) << " ways to make up : " << usernum / 100 << "\n\n"; break;
I am so confused. I am trying to create a tic tac toe game using windows c++ visual. So far I was doing good until I kept getting errors. I tried looking for help but none of the answers seemed right. This is my practice problem.
Implement displayBoard to display Tic Tac Toe board.
Prompt User for a box on the board to select, i.e. a number between 1 and 9 with 1 being the upper left corner.
use cin.get(box) to get the box number and isdigit to verify it is a
number;
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
If the box is available put the appropriate X or O in there and switch players, i.e. X becomes O and vice versa.
If the box is NOT available warn the user and get another box until they select a valid open box.
After all spots have been select Display "Game Over!";
Write a main function to use the TicTacToe class and test all of the above functionality.
.
#include<iostream>
using namespace std;
class TicTacToe {
public:
void displayBoard();
void getMove();
void playGame();
private:
char board[9];
char player; // Switch after each move.
};
int main ()
{
TicTacToe ttt;
// you need to do the following in a loop 9 times
ttt.playGame();
}
void TicTacToe::playGame()
{
getMove();
// Your implementation here...
}
void TicTacToe::displayBoard()
{
// Your implementation here...
}
void TicTacToe::getMove()
{
cout << "Enter Box: ";
char c;
cin.get(c);
if (c > '9' || c < '0')
// Error message here.
int number = c - '0';
cout << "your number is " << number;
// Your implementation here...
}
you need a statement to go after the if
even if its just a ;
but maybe you want
if (c > '9' || c < '0')
cout << "Not a Number!";
Ok, so the issue here is the "if" statement. The problem is that you haven't closed the if statement. So what the compiler sees is
cout << "Enter box: ";
char c;
cin.get(c);
if(c > '9' || c < '0')
{
//Compiler thinks that it should only convert the character
//to a number if you got the *wrong* number
int number = c - '0';
}
//the integer number when out of scope in the if statement. So now it doesn't exist
//which means you will get a "variable not declared" error
cout << "your number is " << number;
When you create an if statement and you don't put braces around the block of code it should execute, then the next line after the if statement becomes the conditional statement. What you need to do is close the if statement. simply adding a semicolon is sufficient:
if (c > '9' || c < '0');
but it means you don't handle the error, which is pretty bad, so at least put an error message in the if statement to tell the user that they've made a mistake.
//Play Tic Tac Toe game between user and computer
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<time.h>
using namespace std;
char BLANK='B';
/***************** Display the Matrix **********************************************/
//Display the matrix
void display(char matrix[3][3])
{
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
cout<<matrix[i][j]<<"\t";
cout<<endl;
}
}
/************** Chance of WIN Function *****************************************************/
//Funtion to detect the chance of either for user or systemĵ
int chance_of_win(char matrix[3][3],int i, int j,char choice){
int result=0;//This variale is used to return the required position
char other_choice;//This variable is used for other choice of the variable choice
if(choice=='o')
other_choice='x';
else
other_choice='o';
int count1=0;//This variable is used to check the count upto 2
//Diagonal Intelligent
if(i==j){
for(int k=0;k<3;k++){
if(matrix[k][k]==choice)
count1++;
if(count1==2){ // That means user is going to win and system has to stop that
for(int k=0;k<3;k++){
if(matrix[k][k]!=choice && matrix[k][k]!=other_choice){
int temp=k;
temp=temp*10;
result=temp+k;
return result;
}
}
}
}//for looop ends here
}//If Structure ends here
count1=0; //Reinitilize the count to zero
//Reverse Diagonal intelligent
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]==choice){
count1++;
}
if(count1==2){ // That means user/system is going to win reverse diagnally
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]!=choice && matrix[m][n]!=other_choice){
int temp=m;
temp=temp*10;
result=temp+n;
return result;
}
}
}//End of If structure
}//End for loop
count1=0; //Reinitilize the count to zero
//Row Intelligent
for(int k=0;k<3;k++){
if(matrix[i][k]==choice)
count1++;
if(count1==2){ // That means user/system is going to win
for(int k=0;k<3;k++){
if(matrix[i][k]!=choice && matrix[i][k]!=other_choice){
int temp=i;
temp=temp*10;//for the ith coordiante
result=temp+k;//for the jth cordinate
return result;//Return the required attribute of i and j
}
}
}
}//for looop ends here
count1=0; //Reinitilize the count to zero
//Column Intelligent
for(int k=0;k<3;k++){
if(matrix[k][j]==choice)
count1++;
if(count1==2){ // That means user is going to win and system has to stop that
for(int k=0;k<3;k++){
if(matrix[k][j]!=choice && matrix[k][j]!=other_choice){
int temp=k;
temp=temp*10;//for the ith coordinate
result=temp+j;//for the jth coordinate
return result;//Return the required attribute of i and j
}
}
}
}//for looop ends here
return result;
}//function ends here
/******************* Check Win Bool Function ******************************************************/
//This function is used to check the win of the system/user
bool checkwin(char matrix[3][3],int i, int j,char choice){
bool flag=false;//Initialize the chance of win false
int count1=0;
//Diagonal checkwin forward
if(i==j){
for(int k=0;k<3;k++){
if(matrix[k][k]==choice){
count1++;
}
if(matrix[k][k]==BLANK)
break;
}
if(count1==3)//Means all diagonal elements are equal
flag=true;
}
//If the Diaganoal Forward is same then return
if(flag){
cout<<"Diagonal Win\n";
return flag;
}
//Reverse Diagonal checkwin
for(int m=0,n=2;m<3,n>=0;m++,n--){
if(matrix[m][n]!=choice || matrix[m][n]==BLANK){
flag=false;//If diagonal is not same
break;
}
flag=true;
}
//If the Reverse Diaganoal Forward is same then return
if(flag){
cout<<"Reverse Diagonal Win\n";
return flag;
}
//Row checkwin
for(int k=0;k<3;k++){
if(matrix[i][k]!=choice || matrix[i][k]==BLANK){
flag=false;// Row is not same
break;
}
flag=true;
}
//If row is same then return
if(flag){
cout<<"Row Win\n";
return flag;
}
//Column checkwin
for(int k=0;k<3;k++){
if(matrix[k][j]!=choice || matrix[k][j]==BLANK){
flag=false;//Column is not same
break;
}
flag=true;
}
//If the Column is same then return
if(flag){
cout<<"Column Win\n";
return flag;
}
return flag;//return the result false result i.e there is no chance of win
//as we have checked all the conditions
}
/************************* Main Function **************************************************/
int main(){
char matrix[3][3];
bool flag;
int toss;
srand(time(NULL));
toss=rand()%2;
if(toss){
flag=true;
cout<<"User Wins the Toss\n";
}
else{
flag=false;
cout<<"System Wins the Toss\n";
}
//Initialise all the elements of matrix to BLANK i.e. Blank
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
matrix[i][j]=BLANK;
cout<<"For user the choice is o\n";
cout<<"For system the choice is x\n";
int v=1;//Initialise the the variable v , it has the increment till 9 to cover all the elements of the matrix
bool system1=false;//To check the chance of win of system
int user_status=0;//To check the chance of win of user and accordingly system will put his move
int system_status;////To check the chance of win of system and accordingly system will put his move
while(v<=9){
int i,j;// "i" is for the row coordinate and "j" is for the column coordinate
if(flag==true){// If user win's the toss
cout<<"Yours turn\n";
cout<<"Enter the row coordinate";
cin>>i;
i--;//For user convenience i th coordinate
cout<<"Enter the column coordinate";
cin>>j;
j--;//For user convenience jth coordinate
if(matrix[i][j]==BLANK)
matrix[i][j]='o';//Put the user move
else{
cout<<"Already Occupied\n"; //Warn user to fill the blank space
continue;//Don't count this in "variable v" means don't increment the variable "v"
//as it was invalid move
}
// After three attempts it will check , this code is for system
if(v>2)
user_status=chance_of_win(matrix,i,j,'o');//User chance of win
//checkwin whether game is over i.e whether user win
if(v>4){
if(checkwin(matrix,i,j,'o')){
cout<<"\n\tBingo !! User win\n\tCongrats Well played\n";
display(matrix);
return 0;
}
}
flag=false;// Let the System play next move
display(matrix);//display the matrix
cout<<"\nWait! System turns\n";
}
else{//System's Turn
if(system1==true){//Chance of System of winning
j=system_status%10;//get the j coordinate
i=system_status/10;//get the i coordinate
//cout<<"System chance win i = "<<i<<" j = "<<j<<endl;
/*If Structure of Check whether place is empty for winning the system*/
if(matrix[i][j]==BLANK){//Is place is empty
matrix[i][j]='x';
if(checkwin(matrix,i,j,'x')){
display(matrix);//Display the current scenerio of the game
cout<<"Sorry You loose !! System wins\n";
return 0;
}//end if structure of check win
}
else//Means space is occupied by user, and chance of winning by system is lost
system1=false;//Now let the system to defense the user's move
/*Ends If Structure of Check whether place is empty for winning the system*/
}
if(system1==false){
if(user_status!=0){//If User is going to win , warn the system
j=user_status%10;//get the j coordinate
i=user_status/10;//get the i coordinate
//cout<<"User chance win i = "<<i<<" j = "<<j<<endl;
}
else{
if(v==9){//There is no point to check random number if noone is winning at the end
cout<<"\t\tMatch draw"<<endl;
return 0;
}
srand(time(NULL));
i=rand()%3; //random i coordinate
srand(time(NULL));
j=rand()%3; //random j coordinate
}
/*If System turn's of writting*/
if(matrix[i][j]==BLANK)
matrix[i][j]='x';
else
continue;
/*End If Structure of writting system turn's*/
}//end If Structure is sytem chance of win = false
if(v>2){// This condition is necessary to avoid irrevelant check
system_status=chance_of_win(matrix,i,j,'x'); //System chance of win
if(system_status==0){
system1=false;
cout<<"\n Not System Chance of win \n";
}
else{
system1=true;
cout<<"\n System Chance of win \n";
}
}
else{
system_status=0;
system1=false;
}
flag=true;//Let the user play his next move
display(matrix);
}
v++;
}//end of while v<9
return 0;