Value of 2D Array not being change by switch statement - c++

I am trying to code a game of Tic-Tac-Toe, but for some reason my switch function doesn't appear to be running. What am I doing wrong?
#include <iostream>
using namespace std;
int n = 0;
int Player[2] {1, 2};
int moveChosen=0;
int n1 = 0, n2 = 0;
void Display(int grid[][3], int row, int column)
{
cout<<"Coordinates: \n";
cout<<"1"<<" | "<<"2"<<" | "<<"3"<<"\n";
cout<<"--|---|--\n";
cout<<"4"<<" | "<<"5"<<" | "<<"6"<<"\n";
cout<<"--|---|--\n";
cout<<"7"<<" | "<<"8"<<" | "<<"9"<<"\n";
cout<<"Current Moves: \n";
cout<<grid[0][0]<<" | "<<grid[0][1]<<" | "<<grid[0][2]<<"\n";
cout<<"--|---|--\n";
cout<<grid[1][0]<<" | "<<grid[1][1]<<" | "<<grid[1][2]<<"\n";
cout<<"--|---|--\n";
cout<<grid[2][0]<<" | "<<grid[2][1]<<" | "<<grid[2][2]<<"\n";
}
int moveChoice(int Choice)
{
cout<<"Player "<<Player[n]<<" please pick where to move. ";
cin>>Choice;
if (Choice < 1 || Choice > 9)
{
while (Choice < 1 || Choice > 9)
{
cout << "Invalid choice, please enter a new number: ";
cin >> Choice;
}
}
return Choice;
}
void CheckMoveValid(int grid[][3], int Choice)
{
switch (Choice)
{
case 1:
if(grid[0][0] != 0)
{
cout<<"Invalid move, space already filled. ";
}
else
{
moveChosen = Player[n];
n1 = 0;
n2 = 0;
break;
}
break;
case 2:
if(grid[0][1] != 0)
{
cout<<"Invalid move, space already filled. ";
}
else
{
moveChosen = Player[n];
n1 = 0;
n2 = 1;
break;
}
}
}
int main()
{
int grid[3][3]={{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
int Choice, CheckWin = 0;
while (CheckWin < 1)
{
Display(grid, 3, 3);
moveChoice(Choice);
CheckMoveValid(grid, Choice);
if (n=0)
{
n = 1;
}
else
{
n = 0;
}
grid[n1][n2] = Player[n];
}
return 0;
}
If I put cout << "0" << endl; between line 65 and 66, nothing happens even when I enter 1, and whatever I tried I could not get "Invalid move, space already filled. " to trigger.

In main(), the call to moveChoice() prompts the user for input, but then discards that input. The Choice variable in main() is never assigned a value, so the call to CheckMoveValid() exhibits undefined behavior.
Get rid of the Choice parameter in moveChoice(), it is not needed. Have main() assign the return value of moveChoice() to the Choice variable, eg:
int moveChoice()
{
int Choice;
...
cin >> Choice;
...
return Choice;
}
...
int main()
{
...
int Choice;
...
Choice = moveChoice(); // <-- HERE!!!
CheckMoveValid(grid, Choice);
...
}

Related

Uncontrolled looping and function Skipping in C++?

I am trying to read two user inputted numbers from a keypad onto a discovery board. I have the code working for reading the first number in but for some reason when it hits the same Keypad(); function for the second time it doesn't appear to be calling the function up to allow an input instead it skips over the scan and prints the lines under it and if you press the button to start over it is random where the program picks up, any ideas what could be causing this. I am compiling on mbeds online Ide. below is the code as well.
#include <iostream>
#include "mbed.h"
DigitalIn columns[3] = {PB_6, PB_7, PD_0}; // Columns for digital input
DigitalOut rows[4] = {PA_5, PA_1, PA_2, PA_3}; // rows for digital output
DigitalIn startButton(USER_BUTTON);
DigitalOut led1(LED1); // reference LED
int numpad[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {-2, 0, -1}}; // keypad
int Total();
int Keypad();
int c = 0;
int Read;
int Num1 = 0;
int SelectOp();
int Oper;
int main() {
while (1) {
if (startButton == 1) {
printf("%s\n\rInput First Number\n\r");
wait(.5);
Keypad();
int First = Num1;
Num1 = 0;
printf("%s\n\r Your first number is ");
printf("%i", First);
printf("%s\n\r Input your second number\n\r");
wait(.5);
Keypad(); // this seems to be getting skipped
int Second = Num1;
Num1 = 0;
printf("%s\n\r Your Second number is ");
printf("%i", Second);
printf("%s\n\rSelect Operator: 1(+), 2(-), 3(*), 4(/)");
Keypad();
Oper = Num1;
}
}
}
int Keypad() {
columns[0].mode(PullUp);
columns[1].mode(PullUp);
columns[2].mode(PullUp);
while (1) {
if (Read == -1) {
return Num1;
}
for (int i = 0; i < 4; i++) {
rows[0] = 1;
rows[1] = 1;
rows[2] = 1;
rows[3] = 1;
rows[i] = 0;
wait(0.01);
for (int j = 0; j < 3; j++) {
if (columns[j] == 0) {
Read = numpad[i][j];
Total();
c++;
if (c == 5) {
c = 0;
}
wait(0.005);
while (columns[j] == 0)
;
}
}
}
}
}
int Total() {
if (Read >= 0) {
Num1 *= 10;
Num1 += Read;
printf("%i\n\r", Num1);
} else {
return Num1;
}
return Num1;
}
When Read is set to -1 during the first loop through Keypad(), it's still -1 when you enter Keypad() again, thus returning instantly.
Using some space to echo #Scheff on the importance of scoping variables according to their expected lifetimes and thus minimizing global variables wherever possible.

invalid types 'int[int]' for array subscript in multidimensional array c++

While doing my course project of card game, i got this error
Invalid types `int[int]' for array subscript'
Here is the code :
#include <iostream>
#include <stdlib.h>
#include <time.h>
int randomize(int, int);
int* generateCardNumber(int[5]);
int* generateCardLogo(int, int[13][4], int[5]);
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
int printResult(int[5]);
void showCard(int, int[5], int[5], int[5], int[5]);
void printCard(int[5], int[5]);
using namespace std;
int main()
{
srand(time(NULL));
int player1Number[5], player1Logo[5];
int *number1, *logo1;
int player2Number[5], player2Logo[5];
int *number2, *logo2;
int cardInfo[13][4];
int **card;
char answer;
do
{
int playerInput;
int d, c, r;
int player1Score, player2Score;
cout<<"Welcome to the card game!"<<endl;
cout<<" Choose player{1: Player 1; 2: Player 2} : ";
cin>>playerInput;
cout<<endl;
do
{
cout<<"Press d to deal card :";
}while(d != 'd');
number1 = generateCardNumber(player1Number);
logo1 = generateCardLogo(1,cardInfo, player1Number);
for (int i = 0; i<5; i++)
{
cardInfo[player1Number[i]][player1Logo[i]] = 1;
}
number2 = generateCardNumber(player2Number);
logo2 = generateCardLogo(2,cardInfo, player2Number);
for (int i = 0; i<5; i++)
{
cardInfo[player2Number[i]][player2Logo[i]] = 1;
}
showCard(playerInput,player1Number,player1Logo,
player2Number,player2Logo);
do
{
cout<<"Press c to compare card :";
}while(c != 'c');
*card = compareCard(player1Number,player1Logo,
player2Number,player2Logo,cardInfo);
for (int i = 0; i<5; i++)
{
if(cardInfo[player1Number[i]][player1Logo[i]] = -1)
{
player1Number[i] = -1;
player1Logo[i] = -1;
}
else if(cardInfo[player2Number[i]][player2Logo[i]] = -1)
{
player2Number[i] = -1;
player2Logo[i] = -1;
}
}
showCard(playerInput,player1Number,
player1Logo,player2Number,player2Logo);
do
{
cout<<"Press r to show result :";
}while(r != 'r');
if(playerInput == 1)
{
cout<<"Player1 (You): ";
player1Score = printResult(player1Number);
cout<<"Player2 (Computer): ";
player2Score = printResult(player2Number);
if(player1Score > player2Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer): ";
player1Score = printResult(player1Number);
cout<<"Player2 (You): ";
player2Score = printResult(player2Number);
if(player2Score > player1Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
cout<<"Do you want to play again? (y/n)"<<endl;
cin>>answer;
}while(answer == 'Y' || answer == 'y');
}
int randomize (int x, int y)
{
return (rand()%y + x);
}
int* generateCardNumber (int numberArray[5])
{
int arrayStoring[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i<5; i++)
{
do
{
numberArray[i] = randomize(1,13);
}while (arrayStoring[numberArray[i]] == 1);
arrayStoring[numberArray[i]] = 1;
}
return numberArray;
}
int* generateCardLogo (int turn, int cardInfo[4][13], int player2Number[5])
{
int logoArray[5];
if(turn == 1)
{
for (int i = 0; i<5; i++)
{
logoArray[i] = randomize(1,4);
}
return logoArray;
}
else if(turn == 2)
{
for (int i = 0; i<5; i++)
{
do
{
logoArray[i] = randomize(1,4);
}while (cardInfo[player2Number[i]][logoArray[i]] == 1);
}
return logoArray;
}
}
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
{
for(int j=0; j<5 ; j++)
{
if(player1Number[i] == player2Number[j])
{
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
else if(player1Logo[i] > player2Logo[j]) cardInfo[player2Number[i]][player2Logo[i]] = -1;
break;
}
}
}
return cardInfo;
}
int printResult (int playerNumber)
{
int playerScore = 0;
for (int i = 0; i<5; i++)
{
if(playerNumber[i] == -1) break;
else if(playerNumber[i] == 0)
{
playerScore += 15;
cout<<"15 ";
}
else if(playerNumber[i] > 0 && playerNumber[i] < 10 )
{
playerScore += (playerNumber[i] + 1);
cout<< (playerNumber[i] + 1) <<" ";
}
else if(playerNumber[i] >= 10)
{
playerScore += 12;
cout<<"12 ";
}
if(i<4) cout<<"+ ";
else if(i==4)
{
cout<<"= "<<playerScore<<" points";
}
}
return playerScore;
}
void printCard (int numberArray[5], int logoArray[5])
{
for (int i = 0; i<5; i++)
{
switch(numberArray[i])
{
case -1 :
cout<<"<fold> ";
break;
case 0 :
cout<<"Ace ";
break;
case 1 :
cout<<"2 ";
break;
case 2 :
cout<<"3 ";
break;
case 3 :
cout<<"4 ";
break;
case 4 :
cout<<"5 ";
break;
case 5 :
cout<<"6 ";
break;
case 6 :
cout<<"7 ";
break;
case 7 :
cout<<"8 ";
break;
case 8 :
cout<<"9 ";
break;
case 9 :
cout<<"10 ";
break;
case 10 :
cout<<"Jack ";
break;
case 11 :
cout<<"Queen ";
break;
case 12 :
cout<<"King ";
break;
}
switch(logoArray[i])
{
case -1:
break;
case 0:
cout<<"Diamond ";
break;
case 1:
cout<<"Club ";
break;
case 2:
cout<<"Heart ";
break;
case 3:
cout<<"Spade ";
break;
}
}
}
void showCard (int playerInput, int player1Number, int player1Logo, int player2Number, int player2Logo)
{
if(playerInput == 1)
{
cout<<"Player1 (You):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (Computer):"<<endl;
printCard(player2Number, player2Logo);
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (You):"<<endl;
printCard(player2Number, player2Logo);
}
}
Honestly, i still newbie at programming. So i didn't know that i can't return a whole array from a function. After searching for clue, i found out that i can use pointer to return an array from function. When i try to fix the code, this error come out and i didn't know what i need to fix.
The error keep appearing when i try to use the array from the function parameter,such as this
if(player1Number[i] == player2Number[j])<br/>
from function
int** compareCard(int player1Number, int player1Logo, int player2Number,
int player2Logo, int cardInfo)
and onward.
Can someone help me figure this out? Correction to the code would be very appreciated. Thankyou very much! (Sorry if my english is bad)
You're declaring compareCard with a bunch of arrays (so int pointers) as parameters:
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
Then, however, you're implementing it using integers (not pointers) as parameters:
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
You're also using them as arrays:
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
Also, the return type is wrong. You're declaring it as int*, but then implement it as int**. You have to ensure that the signature of your function matches. It looks like taking the signature of the declaration and applying it to the definition should fix this compile time error.
Does your compiler issue any warnings for these function declarations? If not, see if you can set it to be more strict with warnings. Getting the correct warnings for potential errors greatly increases debug efficiency.

BinarySearch function not working

I've got a menu that I've been working on, and everything now seems to work, except for the binary search function. I am entering the size of the array, filling the array, printing it, then sorting it with my chronological menu, and then when I do sequential search, it seems to work. However, binary search does not even return -1 to indicate that the number was not found, the program just stops. Suggestions? Thanks.
#include<iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int size=0; //global variable size
int a[100]; //global array
int getSize()
{
cout << "Array Size: ";
cin >> size;
return size;
cout << endl;
}
int sequentialSearch(int n)
{
for(int i=0;i<size;i++)
{
if(n==a[i])
{
return (i+1);
}
}
return -1;
}
int binarySearch(int n)
{
int low=0,high=size,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==n)
{
return mid+1;
}
else if(a[mid]>n)
high=mid-1;
else if(a[mid]<n)
low=mid-1;
}
return -1;
}
void sort1()
{
int i, j;
for (i = 0; i < size-1; i++)
{
for (j = 0; j < size-i-1; j++)
if (a[j] > a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
void sort2()
{
int i, j, m;
for (i = 0; i < size-1; i++)
{
m = i;
for (j = i+1; j < size; j++)
{
if (a[j] > a[m])
m = j;
}
int temp=a[m];
a[m]=a[i];
a[i]=temp;
}
}
void printMenu()
{
cout<<"0. Exit\n";
cout<<"1.Get the size needed for todays use of the array \n";
cout<<"2.Fill an array with random numbers from 1-100 \n";
cout<<"3.Print the array with position numbers \n";
cout<<"4.Sort the array in ascending sequence \n";
cout<<"5.Sort the array in descending sequence \n";
cout<<"6.Sequential search of the array for a target\n";
cout<<"7.Binary search of the array for a target\n";
}
void printTheArray()
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<" is at position :"<<i+1<<endl;
}
}
void fillWithRandom()
{
for(int i=0;i<size;i++)
{
int x=rand()%101;
a[i]=x;
}
}
void dispatch(int ch)
{
switch(ch)
{
case 1:cout<<"Size of array :"<<getSize() << endl;
break;
case 2:fillWithRandom();
break;
case 3: printTheArray();
break;
case 4:sort1();
break;
case 5:sort2();
break;
case 6:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res1=sequentialSearch(t);
if(res1!=-1)
cout<<"Found in position :"<<res1<<endl;
else if(res1==-1)
cout<<"Not Found \n";
break;
}
case 7:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res=binarySearch(t);
if(res!=-1)
cout<<"Found in position :"<<res<<endl;
else if(res==-1)
cout<<"Not Found \n";
break;
}
default:cout<<"wrong choice\n";
}
}
int main ()
{
printMenu();
int choice;
cout<<"Type in a choice"<<endl;
cin>>choice;
while(choice!=0)
{
dispatch(choice); // one big switch statement
printMenu();
cout<<"Type in a choice"<<endl;
cin>>choice;
}
cout << endl;
// wrap-up
cout << "This program is coded by Troy Wilms" << endl; // fill in your name
// stops the program to view the output until you type any character
return 0;
}
for example, if you try finding 4 in list {1, 3, 5}, low will be always 0 and high will be always 2. because of the code 'low = mid - 1' I think it should be changed to 'low = mid + 1'

Why is "2" always being returned from my function? Trying to find the index of a searched number within an array

I am trying to return the index of array if it matches a user defined number. I cant figure out why, no matter what I enter, the function returns "2".
#include <iostream>
using namespace std;
int search(int x, int *list);
int main()
{
int x;
int list[10] = { 20, 1, 18, 3, 16, 5, 14, 7, 12, 9};
cout << "Enter a number to search the list for: ";
cin >> x;
cout << endl;
cout << search(x, &list[10]) << endl;
system("PAUSE");
return 0;
}
int search(int x, int *list)
{
bool match = false;
for (int i = 0; i < 10; i++)
{
if (list[i] == x)
{
match = true;
}
if (match == true)
{
return i;
}
else if (match == false && i == 9)
{
return -1;
}
}
}
Because you have invoked undefined behavior by starting the search at index 10:
search(x, &list[10]) should be search(x, list).
...and what's with that whole else if in the loop. Why not just return -1 at the end of the function. And why have a match variable - if a match is found just return i.
for (int i = 0; i < 10; i++)
{
if (list[i] == x)
{
return i;
}
}
return -1;

CodeBlocks .exe has stopped working

my .exe well compiled program stops working after run it in CodeBlocks,
It stops after typing cin>>f.name the to the console after the choosed choice
I have a Windows 8 and i use GNU GCC compiler here is the code,maybe there is a code error , i don t know
tanks for your attention
:
using namespace std;
struct employee
{
string name;
int age;
};
employee employeeList[10];
class Stack
{
int pos;
public:
Stack(){};
void push(employee e)
{
employeeList[pos] = e;
pos++;
}
employee pop(int n)
{
if(n = pos - 1)return employeeList[pos];
if(n < pos - 1)
{
return employeeList[pos];
for(int j =n; j < pos; j++ )
{
employeeList[pos] = employeeList[pos + 1];
}
}
pos--;
}
string print(int n)
{
n = pos;
cout<<employeeList[pos].name<<endl;
}
char menu()
{
char choice;
cout << "Press 1. to push an employee"<<endl;
cout << "Press 2. to pop an employee"<<endl;
cout << "Press 3. to show an employee"<<endl;
cin>> choice;
return choice;
}
};
int main()
{
Stack s;
char input = s.menu();
int j;
do
{
switch(input)
{
case '1' :{employee f; cin>>f.name; s.push(f);}break;
case '2' :{int n; cin>>n; s.pop(n);} break;
case '3' :{int n; cin>>n; s.print(n);}break;
}
j++;
}
while(j < 10);
return 0;
}
You didn't proper initialization of instance variable "pos" of class "Stack". This means that initially it can have any value. If that value is beyond the range of your "employeeList", you are accessing an area of memory that does not belong to you. That's probably a segmentation error.