C++ Tic Tac Toe Game - c++

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;

Related

Moving a number in a zig zag pattern through a 2D array C++

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
//function protypes
void gameBoard(); //prints board
void diceRoll();
void move();
//global variables
int roll;
int playerOne = 0;
int playerTwo = 99;
int board[5][8] = {{33,34,35,36,37,38,39,40},
{32,31,30,29,28,27,26,25},
{17,18,19,20,21,22,23,24},
{16,15,14,13,12,11,10, 9},
{ 1, 2, 3, 4, 5, 6, 7, 8}};
void diceRoll() { //asks player to input a charater to roll a dice
srand(time(0));
roll = ((rand() % 6) + 1); //sets num to a random number between 1 and 6
}
void gameBoard(){ // prints game board
for (int i = 0; i < 5; ++i){
for (int j = 0; j < 8; ++j){
cout << board[i][j] << " ";
if (board[i][j] <= 8){
cout << " ";
}
}
cout << endl << endl;
}
}
void move(int player, int& colPos, int& rowPos){
int tempCol;
int tempRow;
int previous;
for (int i = 0; i <= 2; i++){
if(i % 2 == 1){
tempCol = colPos + roll;
colPos = tempCol;
tempCol = colPos - roll;
if(colPos > 7){
colPos = 7;
rowPos--;
}
board[rowPos][colPos] = player;
}
}
}
int main() {
int turn = 1;
int colPos1 = 0;
int rowPos2 = 4;
int colPos1 = 0;
int rowPos2 = 0;
while(winner == false){
if(turn == 1){
turn = 2; //allows to switch back and forth bewteen turns
diceRoll(player1); //rolls die
move(playerOne, colPos1, rowPos2);
gameBoard(); //prints game board
}else{
turn = 1; //allows to switch back and forth bewteen turns
diceRoll(player2); //rolls die
move(playerTwo, colPos2, rowPos2);
gameBoard(); //prints game board
}
}
return 0;
}
So the code above is for a chutes and ladders game. The program above should run without any errors. I am almost done with this code but am having issues with the move function. Here I am trying to move through a 2D array (the gameboard) as each player rolls a die. There are two issues with the current code. One after a player moves a space the space that they have previously left remains marked with the player. In addition, once it goes across through an entire row it does not advance to the next row. Thanks for your help in advance.
Note: I deleted a lot of code to make it more relevant to the question so it may have errors now.
"After a player moves a space the space that they have previously left remains marked with the player"
In move(int player, int& colPos, int& rowPos)you already know which player you are updating and the current row and column position so you can use this as an opportunity to remove the mark on the current board piece and set it back to its default value e.g. once you step into move call something like void ResetBoardPositition(int colPos, int rowPos) and then update the new position with the player marker (alternatively you could not change the game board at all and just print the player position at the draw stage since you store their positions anyway)
"Once it goes across through an entire row it does not advance to the next row"
Your code isn't doing anything to take account of the fact you need to reverse direction every time you change rows. Each time you go past column 7 you just set the column to 7 and reduce the row. This means that your next roll will immediately take you past the column threshold again, set it to 7 and reduce the row count. You'll need to use some form of direction modifier for the roll so you have something like:
int direction = 1;
if (rowPos % 2 == 1)
direction = -1;
tempCol = colPos + (roll * direction);
colPos = tempCol;
tempCol = colPos - (roll * direction);
Your check for the colPos would need to account for this too
if (colPos > 7) {
colPos = 7;
rowPos--;
} else if (colPos < 0) {
colPos = 0;
rowPos--;
}
There is also the issue that you do not account for the full roll here i.e. you set the column to the flat value meaning if you were on column 7, roll a 3 (which should put you at column 5 on the next row) you only move 1 space to the next row and stop there.
Hope these answer your main questions but I think there are some other logic issues going on here with your move code.
To answer your questions, the reason the previous spaces still have that player's name in it is because that value is never reset after the player leaves. What you could do is create an int for the current position before the player gets there, move the player to the new position, and then set the old position to the int you created. I saw that your move function has an int previous, so just use that.
Second, when I ran it, the player would go through the first row, then just move up the last column. From what I saw, your move function only manipulates tempCol and colPos, but not tempRow or rowPos. Moving those will help the player move between the rows.
Also, on a side note, I saw a few things for you to look out for. You declared your function as
void diceRoll();
But when you defined it, you wrote it like this:
void diceRoll(string name) { //asks player to input a charater to roll a dice
I would suggest rather adding in your parameters when you declare it or just declare it and define it all at once.
Second, you probably haven't messed with it much, but the checkWinner() function doesn't change the value of winner.
if (pos1 || pos2 != board[0][7]) {
winner == false;
}
else {
winner == true;
}
Using == is for checking the value, not for assigning, so take out one of them.

Logic error with array and for loop

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

Simulating a random walk scenario on a 4x4 board

The problem I am working on is as follows. Imagine a 4x4 chess board on top of which you place a king. The probability of you placing the king on each of the squares is one of the inputs (not necessarily the same for all the squares). The king has to make n number of moves (n is an input). The goal is to run an 'experiment' to find the probability after n moves.
My friend solved the problem by creating a general formula using linear algebra. As a challenge/verification of his answer I want to make this program in c++.
We both start with making one generalization. That is since the board is symmetrical we only consider if the king is at a side, corner or middle square of the board.
C S S C
S M M S
S M M S
C S S C
Therefore, we input only P(S_{initial}), P(C_{initial}), P(M_{initial}), the number of moves the king makes, and the number of 'experiments' we make.
The code for my program is below. My results disagreed with my friend's, so I checked my code by setting n to 1 and P(S_{initial}), P(C_{initial}) and P(M_{initial}) to 1/2, 1/4, and 1/4, respectively. By conditional probability I know that P(S)=59/120, P(C)=21/160, P(M)=181/481. My computations do not agree, so I am sure there is a bug or error in my code, but I cannot track it down. I appreciate any help.
Also I know my code is scruffy and inefficient so I appreciate comments about how to improve it. Thanks for your help.
EDIT: To input the initial probabilities I input 2, 1 and 1 for S, C and M, respectively.
EDIT2: Turned out that I used "=" instead of the operator "==" in my if statements. Thank you #Christopher Oicles. Everything works now as expected.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <time.h>
using namespace std;
int S, C, M; //probability 'ratios', i.e. prob of S is S/(S+C+M)
int n; // number of steps
int trials;
int initial(int a,int b,int c); // this 'throws the die' to find where to start and returns 0 for side, 1 for corner, 2 for middle
int step(int a); // this throws the die to make a step and returns the same format
int trial(); //this makes n number of steps, starting at initial(a,b,c) and returns 0,1,2
double data[]={0,0,0}; // the result of the experiment, each element holds the number of times a trial returned the S,C,M where number of s = data[0], I increment this by one every time I run trial();
int main()
{
srand(time(NULL));
for(int i=0;i<3;i++) //reset data array
data[i]=0;
std::cout << "Enter probability ratio of S:";
std::cin >> S;
std::cout << "Enter probability ratio of C:";
std::cin >> C;
std::cout << "Enter probability ratio of M:";
std::cin >> M;
std::cout << "Enter number of steps per trial:";
std::cin >> n;
std::cout << "Enter number of trials:";
std::cin >> trials;
for(int i=0;i<trials;i++)
data[trial()]++;
for(int i=0;i<3;i++)
std::cout << data[i]/trials << " \n";
for(int i=0;i<3;i++)
std::cout<<data[i]<<" ";
cout << "\n \n";
}
int trial(){
int current;// the current place S, C or M or 0,1,2
int next;
current = initial(S,C,M);
for(int i=0;i<n;i++)
{next = step(current);
current = next;}
return current;
}
int initial(int side,int corner,int middle){
int t = rand() % (side+corner+middle); //generates a random number from zero to a+b+c-1
//now we apply the probability
if(t < side)
return 0; //side
if(t >= side && t < (side+corner))
return 1; //corner
if(t>=(side+corner))
return 2; //middle
}
int step(int a){
int t;
switch(a){
case 0: //we are on a side
{t = rand()%5;
if(t < 2){return 0;} //2/5 chance to go to a side
if(t = 2){return 1;} //1/5 chance to go to a corner
if(t > 2){return 2;} //2/5 chance to go to a middle
break;}
case 1: //we are on corner
{t = rand()%3;
if(t < 2){return 0;} //2/3 chance to go to side
if(t = 2){return 2;} //1/3 chance to go to middle
break;}
case 2: //we are on middle
{t = rand()%8;
if(t < 4){return 0;} //1/2 chance go to side
if(t = 4){return 1;} //1/8 chance of corner
if(t > 4){return 2;} //3/8 chance of middle
break;}
}
}

2d array finished mine sweeper board program

Hello I am attempting to write a program and I seem to be stick. This program is in the end supposed to display two variants of a single 10 by 10 mine sweeper board. One of which where if there is a mine in that location it displays an asterisk(*) and if there is no mine it displays a period. The second variant also needs to display an asterisk where the mines are located on the board. But instead of a period it has to display the number of mines located 1 space away in any direction. I can't seem to think of how to easily write a program that will add up each of the mines located around each point. I also can't figure out why my program asks the initial question twice even if it meets the criteria for stopping the loop the first time around.
/*
Program: minesweeper(sort of)
The intention of this program is to display essentially two mine sweeper game boards one of which displays a *
where all of the mines would be located and a . where no mines are located. Then the second display
should display a * where all of the mines are and then display a number based on how many mines surround that space.
*/
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
double get_probability();
int plant_mines(bool mineCells[10][10], double prob);
int print(bool mineCells[10][10]);
int count_mines(bool mineCells[10][10], int mineCounters[10][10]);
int main()
{
//used to hold true if there is a mine located at said location or false if there is no mine
bool mineCells[10][10];
//used to hold a value of -5 if the corrosponding value on mineCells is true and if the corrosponding value on
//minecells is false it should add up and hold the value of how many mines are surroudning it.
int mineCounters[10][10];
get_probability();
double prob = get_probability();
plant_mines(mineCells, prob);
print(mineCells);
int stop;
cin >> stop;
return 0;
}
//asks the user for a number between 0 and 1 to use as the probability of mines apearing laster on.
double get_probability()
{
double prob;
bool repeat;
do
{
cout << "Please enter a number between 0 and 1: ";
cin >> prob;
//should execute once asking the user for a input between 0 and 1 and if the input is not between those two it shoud
//then continue to repeat untill the permaiters set in the question are met.
if (prob >= 0 && prob <= 1)
{
break;
}
else
{
repeat = true;
}
}while (repeat = true);
return prob;
}
//takes the probability given by the user and then uses it to generate that percentage of mines on the field
int plant_mines(bool mineCells[10][10], double prob)
{
srand((unsigned int)time(NULL));
for (int count = 0; count < 10; count++)
{
for (int counter = 0; counter < 10; counter++)
{
//generates a random number between 0 and 1 and sets it equal to the variable random
double random = static_cast<double>(rand()) / RAND_MAX;
//is the variable random is less than or equal to the probability then the array is set to true meaning
//there is a mine located at that position
if (random <= prob)
{
mineCells[count][counter] = true;
}
//iff the random number is greater than the user input than there is no mine located at said position
else
{
mineCells[count][counter] = false;
}
}
}
return mineCells[10][10];
}
//Should count up the mines surronding the location to be output later on
//(the mines surrounding the location do include all mines 1 space diagonal, vertical and horizontal from said location)
int count_mines(bool mineCells[10][10], int mineCounters[10][10])
{
for (int count = 0; count < 10; count++)
{
for (int counter = 0; counter < 10; counter++)
{
if (mineCells[count][counter] == 1)
{
mineCounters[count][counter] = 0;
}
else
{
}
}
cout << endl;
}
return 0;
}
//displays a * where ever a mine is locate and a . where ever a mine is not located
int print(bool mineCells[10][10])
{
for (int count = 0; count < 10; count++)
{
for (int counter = 0; counter < 10; counter++)
{
if (mineCells[count][counter] == 1)
{
cout << "*";
}
else
{
cout << ".";
}
}
cout << endl;
}
return 0;
}

How to write a program that shows if a number is prime and can display the prime numbers from 1 to 100 in a file

I am trying to write a program that will tell you if the numbered entered is prime or not and will write all the prime numbers from 1 to 100 to a file and displays the numbers. This is what I have so far, but I'm lost.
bool isPrime(int);
int _tmain(int argc, _TCHAR* argv[])
{
int num, answer, choice, i, numb=1;
do
{
cout<< "Enter a number and I will tell you if it is prime or not."<<endl;
cin>> num;
if (isPrime(num))
cout<<num<<" is a prime number."<<endl;
else
cout<<num<< " is not a prime number."<<endl;
cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no)"<<endl;
cin>>choice;
if (choice == 1)
{
while(numb<=100)
{
i=2;
while(i<=numb)
{
if(num%i==0)
break;
i++;
}
if(i==num)
cout<<numb<<" is Prime"<<endl;
numb++;
}
}
else
{
cout<<"Would you like to run the program again? (1 for yes and 2 for no)"<<endl;
cin>>answer;
if (answer == 2)
{
exit(0);
}
}
while (answer == 1);
}
system("pause");
return 0;
}
bool isPrime (int number)
{
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
Really feel you are over-thinking this. You've done the hard part which was writing the isprime function.
Displaying the numbers is trivial, just write a for loop to go through the numbers and check which are prime, if a specific number is prime then print it to screen.
Then just add the write to file inside the loop for those numbers you print to screen.
Why not just reuse your isPrime()?
cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no) <<endl;
cin>>choice;
for (i=2; i < 100; i++)
{
if (isPrime(i)) cout << i << endl;
}
You're way over complicating things for yourself when printing all the primes from 1 to 100. Take a step back and think about what you want to do; cycle from 1 to 100, print the number if its prime.
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
cout << i << endl;
}
The while keyword of your do-while loop is on the wrong line. It should follow the closing brace. Compiler said around line 56 of the example code you posted.
After making changes to conform to standard C++, I compiled and ran the program. I chose the option to list all the primes up to 100. It is generous and displaying all the numbers, prime or not (hint: even numbers after 2 are not prime).
I inserted the following lines at the beginning:
#include <iostream>
using namespace std;
I changed the main function from _tmain to main since I'm not using Visual Studio compiler. Likewise the arguments too:
int main(int argc, char * argv[])
By the way, if you are not passing parameters to your program, you can simplify the declaration of main to:
int main(void)
Here is a modification to speed up your prime detector:
bool isPrime (int number)
{
int i;
if (number == 2)
{
return true;
}
if ((number % 2) == 0)
{
return false;
}
for (i = 3; i < number; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
This cuts down the number of checks by half because every even number after 2 is not prime, only odd numbers.