variables in c changing value randomly - c

I'm learning C at school, and as homework I have to write the tictactoe game. No problem with the "algorithm", but I do not understand why if I change the order of the variables declaration, the program output drastically changes or even the programme stops working. For example, if I swap line 12 with line 13, the element of the array coord change values at random points of the programme. Can someone explain me why this happen?
#include <stdio.h>
#define DIM 3
#define MAX 11
int main(void) {
char c;
int state = 0; //Variable for the switch case
int nC, nR; //Variables used to count how many X or O there are in the rows and columns of the grid
int i, j;
int coord[2] = {0, 0}; //Array for the coordinates
char grid[DIM][DIM]; //Grid 3x3
char player1[MAX] = "", player2[MAX] = ""; //Name of the players
printf("Player 1, insert your name (max 10 characters): ");
gets(player1);
fflush(stdin);
printf("Player 2, insert your name (max 10 characters): ");
gets(player2);
for (i = 0; i < DIM; i++) { //Inizialize the grid with '.'
for (j = 0; j < DIM; j++) {
grid[i][j] = '.';
printf("%3c", grid[i][j]);
if (j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
do{
switch (state) {
case 0: //State 0: Player 1 is asked for the coordinates corresponding to the position where you want to insert the X symbol
printf("\n%s your turn: ", player1);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'O') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'X';
c = 'X';
state = 2;
}
else{
state = 0;
printf("Invalid coordinates!\n");
}
break;
case 1: //State 1: Player 2 is asked for the coordinates corresponding to the position where you want to insert the O symbol
printf("\n%s your turn: ", player2);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'X') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'O';
c = 'O';
state = 2;
}
else{
printf("Invalid coordinates!\n");
state = 1;
}
break;
case 2: //State 2: Check if there a right combination of X or O
printf("\n");
for (i = 0; i < DIM; i++) {
for (j = 0; j < DIM; j++) {
printf("%3c", grid[i][j]);
if(j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
nC = 0;
nR = 0;
i = coord[1] - 1;
for (j = 0; j < DIM; j++) {
if(grid[i][j] != c){
break;
}
else{
nR++;
}
}
j = coord[2] - 1;
for (i = 0; i < DIM; i++) {
if (grid[i][j] != c) {
break;
}
else{
nC++;
}
}
if (nC == 3 || nR == 3) state = 3;
else if (c == 'X') state = 1;
else state = 0;
break;
case 3:
if (c == 'X') printf("\n%s IS THE WINNER!\n", player1);
else printf("\n%s IS THE WINNER!\n", player2);
return 0;
break;
}
} while (1);
}

In C, array indices for an array with n elements run from 0 to n−1.
int coord[2] = {0, 0}; defines coord to have two elements, so their indices are 0 and 1.
Throughout the code, coord[1] and coord[2] are used. coord[2] is outside the defined array, so the behavior of the program is not defined by the C standard.

Related

How to Fix the Logic Errors in My "Guess the Movie" Game as a C Program

I have written a Guess the Movie game in the C programming language. My logic seems to be correct but whenever I run the program, it doesn't work as expected.
Here is my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ran = 1;
int l, j = 0, i = 0, total = 0, d = 0;
char b;
char a[20];
char s[1000];
int z;
FILE *my;
printf("Enter your name:\n ");
scanf("%s", s);
ran = rand() % 6;
if (ran == 1)
{
my = fopen("my1.txt", "r");
}
else if (ran == 2)
{
my = fopen("my.txt", "r");
}
else if (ran == 3)
{
my = fopen("my2.txt", "r");
}
else if (ran == 4)
{
my = fopen("my3.txt", "r");
}
else if (ran == 5)
{
my = fopen("my4.txt", "r");
}
for (d = 0; d < 20; d++)
fscanf(my, "%c", &a[d]);
fclose(my);
printf("GUESS THE MOVIE GAME\n");
for (j = 0; j < 7; j++)
{
if (a[j] == 'm')
{
printf("M ");
}
else
{
printf("_ ");
}
}
printf("\n");
printf("Let's begin the game\n");
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
printf("enter character number %d\n",i+1);
scanf("%c", &b);
if (b == a[i])
{
printf("its a right guess\n");
total = total + 4;
i++;
}
else if (b != a[i])
{
printf("Wrong choice\n");
if (total == 1 || total == 0)
{
total=0;
}
else
{
total = total - 2;
}
}
}
}
printf("You have guessd the movie\n");
printf("The movie name is: ");
for (i = 0; i < 7; i++)
{
printf("%c",a[i]);
}
printf("Your score is %d\n",total);
}
This is the program output that I get each time I run the above code:
Enter your name:
raj
GUESS THE MOVIE GAME
_ _ _ _ M _ _
Let's begin the game
Enter character number 1
Wrong choice
Enter character number 1
I
Wrong choice
Enter character number 1
Wrong choice
Enter character number 1
Besides the deficiencies pointed out in comments, there's this major logic error:
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
…
}
}
If the loop encounters an m, it repeats endlessly. Eliminate the if (a[i] != 'm') or add an else ++i.

Sorting an array of structs in C with pointers

I have a coding assignment for my CIS class. The assignment is to write a program the will create an array of structures that will hold information on at max 10 dogs. At the end of the program, you are supposed to sort the array of dogs by either name or size. But I am unable to code the sorting of the array of dog. I was wondering how to sort the array of dogs for later use in the main function.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dog{
char name[20];
int weight;
int age;
int ageDogYears;
char size[7];
};
typedef struct Dog DG;
void calc(DG[], int);
void sort(DG[], int);
void display();
int main(){
DG dArray[10];
int x = 0;
char str[80], *i;
FILE *inFile;
inFile = fopen("dogfile.txt", "r");
if (inFile == NULL){
printf("Error opening file");
exit(1);
}
while(fgets(str, 80,inFile) != NULL){
i = strtok(str, ", ");
strcpy(dArray[x].name, i);
puts(dArray[x].name);
i = strtok(NULL, ", ");
dArray[x].weight = atoi(i);
printf("%d\n", dArray[x].weight);
i = strtok(NULL, ", ");
dArray[x].age = atoi(i);
printf("%d\n", dArray[x].age);
x++;
}
calc(dArray, x);
sort(dArray, x);
return 0;
}
void calc(DG dog[], int numDogs){
int y, i, total;
for(i = 0; i < numDogs; ++i){
if(dog[i].weight <= 20){
//sets the dog size to small
strcpy(dog[i].size, "Small");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 15;
else if(y == 1)
total += 8;
else if(y == 2)
total += 5;
else
total += 4;
}
}
else if(dog[i].weight <= 50){
//sets the dog size to medium
strcpy(dog[i].size, "Medium");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 14;
else if(y == 1)
total += 9;
else if(y == 2)
total += 7;
else
total += 5;
}
}
else{
//sets the dog size to Large
strcpy(dog[i].size, "Large");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 12;
else if(y == 1)
total += 9;
else if(y == 2)
total += 8;
else
total += 7;
}
}
dog[i].ageDogYears = total;
total = 0;
}
}
void sort(DG dog[], int numDogs){
int sortType, i, y, temp;
printf("\n wlould you like to sort by name(N) or size(S): ");
scanf("%c", &sortType);
switch(sortType){
case 'N': case 'n':
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs); ++y){
if(dog[y].weight > dog[y+1].weight){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
break;
default:
if((sortType != 's') && (sortType != 'S'))
printf("\n invalid input! Setting sort type to size.");
//sorting of dog names
}
}
Sample Input
Fluffy,23,6
Fido,65,7
Pepper,44,5
Bowser,75,10
Victor,10,2
Sassy,51,1
Any help would be much appretated! Thanks.
In my opinion, your error resides (despite of other comments I'll do below) in specifying %c as format descriptor to pass a pointer to int to match. You have to pass a pointer to char to make scanf(3) to select the proper place to put the character into. You probably are not getting the right character or no character at all (this leads to Undefined Behaviour in your program)
Some other problems are that you are using the weight field of the structure when requested to sort by name (on n input char) and other errors like this. This includes that you use y < (numDogs) in the inner loop limit condition (it must be y < (numDogs - 1), or you'll compare the y-esim with the y+1-esim element (out of array bounds)
Also, as you are using the same algorithm for both sorting options, I should include the switch statement inside the inner loop (where you do the comparison) as doing otherwise will force you to copy the same sorting code twice (for the overall sorting algorithm), as in:
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs - 1); ++y){
int sortResultGreater;
switch (sortType) {
case 'n': case 'N':
sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0;
break;
default: { /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
static int not_already_printed = 1;
if (not_already_printed) {
printf("Error, sortType must be [nNsS], defaulting to n\n");
not_already_printed = 0; /* so we don't get here again */
}
} /* scope of not_already_printed finishes here */
/* no break used here to fallback to the next case */
case 's': case 'S':
sortResultGreater = dog[y].weight > dog[y+1].weight;
break;
} /* switch */
if(sortResultGreater){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}

Connecting Random number in 2d array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have generated random number into a 2d array.What I want now is to connect the same number by moving it inside the game board.The problems is it doesn't move.
I really need help!!! I am new to c programming btw. Thanks in advance.
Here's my code:
void playgame(char box[ROW][COL])
{
int x, y, choice2,num,direction=0;
char input;
do{
printf("Please select a number (1-7) : \n");
scanf("%i",&num);
if(x==0 || x==ROW-1 ||y==0 || y==COL-1)
{
printf("Invalid!\n");
}
else
{
printf("Numer %i is currently selected!\n", num);
}
}while(x==0 || x==ROW-1 ||y==0 || y==COL-1);
printf("[1]Move\n[2]Sign out\n");
printf("Enter choice: ");
scanf("%d", &choice2);
switch(choice2)
{
case 1:
{
printf("Press 'E' to go up\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'D' to go right\n");
/*codes for moving the character down.....*/
}
{
printf("Press 'S' to go left\n");
/*codes for moving the character left.....*/
}
{
printf("Press 'X' to go down\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'R' to remove the existing path\n");
}
fflush(stdin);
scanf("%c", &input);
break;
case 2: printf("Bye!\n");
}
for(x=0; x<9; x++)
for(y=0; y<9; y++)
{
if(input == 'E')
if(box[x][y]==num)
{
box[--x][y]==num;
}
if(input == 'D')
if(box[x][y]==num)
{
box[x][y++]==num;
}
if(input == 'S')
if(box[x][y]== num)
{
box[x][--y]== num;
}
if(input == 'X')
if(box[x][y]==num)
{
box[--x][y]==num;
}
}
}
try this:
#include <stdio.h>
#include <stdlib.h>
#define ROW 9
#define COL 9
void display(char box[ROW][COL]);
int validMove(int r, int c, char box[ROW][COL]);
void playgame(char box[ROW][COL]){
int r, c, num;
int choice, nr, nc;
char input, n;
for(;;){
printf("Please select a number (1-7) : \n");
if(1 == scanf("%i", &num) && 1<= num && num <= 7)
break;
printf("Invalid!\n");
while(getchar() != '\n');
}
printf("Numer %i is currently selected!\n", num);
n = num + '0';
for(r = 1; r < ROW-1; ++r)
for(c = 1; c < COL-1; ++c)
if(box[r][c] == n)
goto find;
find:
for(;;){
printf("[1]Move\n"
"[2]Sign out\n"
"Enter choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Press 'E' to go up\n"
"Press 'D' to go right\n"
"Press 'S' to go left\n"
"Press 'X' to go down\n"
"Press 'R' to remove the existing path\n");
scanf(" %c", &input);
nr = r;
nc = c;
switch(input){
case 'E':
nr = r - 1;
break;
case 'D':
nc = c + 1;
break;
case 'S':
nc = c - 1;
break;
case 'X':
nr = r + 1;
break;
case 'R':
break;
default:
break;
}
if(validMove(nr, nc, box)){
box[nr][nc] = box[r][c];
box[r][c] = ' ';
r = nr;
c = nc;
display(box);
} else if(input != 'R'){
printf("invalid move!\n");
}
break;
case 2: printf("Bye!\n");
exit(0);
}
}
}
int validMove(int r, int c, char box[ROW][COL]){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
return 0;
if(box[r][c] != ' ')
return 0;
return 1;
}
void initBoard(char box[ROW][COL]){
int r, c;
for(r = 0; r < ROW; ++r){
for(c = 0; c < COL; ++c){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
box[r][c] = '#';
else
box[r][c] = ' ';
}
}
for(int i = 1; i <= 7; ++i){
int r = rand() % (ROW-1-1) + 1;
int c = rand() % (COL-1-1) + 1;
if(box[r][c] == ' ')
box[r][c] = i + '0';
else
--i;
}
}
void display(char box[ROW][COL]){
for(int r = 0; r < ROW; ++r){
for(int c = 0; c < COL; ++c){
putchar(box[r][c]);
}
putchar('\n');
}
}
int main(void){
char board[ROW][COL];
initBoard(board);
display(board);
playgame(board);
return 0;
}

Number Board Program doesn't place hyphens correctly in C

We're supposed to create a number board whereby a user is allowed to select a number for instance, number 5 and one of the number 5's in the board will be clearly indicated as selected with a hyphen above and below it.
Problem now is: No matter what I try the hyphens refuse to move to the right spot.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define HEIGHT 9
#define WIDTH 8
void board(char array[HEIGHT][WIDTH])
{
int x,y,i,j,score,steps = 0;
/****BORDER CREATION*/
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
for(y=0;y<WIDTH+1;y++)
{
printf("\n");
printf("# ");
for(x=0;x<HEIGHT+1;x++)
{
printf("%c ",array[y][x]);
}
printf("# ");
printf("\n\n");
}
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
/****BORDER CREATION*/
}
void instruc(char *name, int *steps, int *selected)
{
/*User record & score header*/
printf("\n-----Hello %s! Let's see what you can do------\n",name);
printf("----------WELCOME TO NUMBER CONNECT----------\n");
printf("----------PREVIOUS PLAYERS' RECORDS----------\n");
printf("----------Name: %s Score(Steps): %i--\n\n",name,*steps);
printf("\nYour score: %i",*steps);
printf("\nNumber %i is currently selected",*selected);
printf("\n\nAction Keys: ");
printf("\nPush 'U' to move UP");
printf("\nPush 'D' to move DOWN");
printf("\nPush 'L' to move LEFT");
printf("\nPush 'R' to move RIGHT");
printf("\nPush 'X' to REMOVE path\n");
printf("\nTo select a new number, press digits from 1 to 7\n");
printf("\nPush 'q' or 'Q' to QUIT\n\n");
}
void select(int *selected,char array[HEIGHT][WIDTH])
{
int i,j,x;
printf("\nPlease select a number (1-8): ");
fflush(stdin);
scanf("%i",selected);
/*POINTER TYPE CONVERTION FAIL
selected = (char)*selected;*/
/*ASCII CHARACTER ATTEMPT FAIL
if (*selected == 1){
*selected = 1;
}
else if (*selected == 2){
*selected = 2;}
else if (*selected == 3){
*selected = 3;}
else if (*selected == 52){
*selected = 4;}
else if (*selected == 53){
*selected = 5;}
else if (*selected == 54){
*selected = 6;}
else if (*selected == 55){
*selected = 7;}
else if (*selected == 56){
*selected = 8;}
else{
printf("Non-Numeric Input not allowed");}*/
printf("\nNumber Selected: %i",*selected);
/*To indicate selected number with hyphens (denoted by 45)*/
for (i = 0; i < WIDTH+1;i++)
{
for (j =0; j < HEIGHT+1; j++){
if (array[i][j] == *selected){
array[i-1][j] = 45;
array[i+1][j] = 45;
}
}
}
printf("\nPosition of i: %i ",i);
printf("Position of j: %i\n\n",j);
}
void assign(char array[HEIGHT][WIDTH], int *selected)
{
int i,j;
/*int rr,rrr;
int x = 0;
srand((unsigned) time(NULL));
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT; j++){
x = (rand()%8+1)+48;
array[i][j] = x;
}
}
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT+3; j++){
rr = rand()%WIDTH;
rrr = rand()%HEIGHT;
x= 32;
array[rr][rrr] = x;
}
}
printf("\n");*/
/*To blank our everything that is not a symbol*/
array[0][1] = 49;
array[0][7] = 49;
array[5][9] = 50;
array[6][1] = 50;
array[1][4] = 51;
array[5][7] = 51;
array[7][2] = 52;
array[5][5] = 52;
array[3][3] = 53;
array[1][1] = 53;
array[7][3] = 54;
array[6][2] = 54;
array[3][7] = 55;
array[7][6] = 55;
array[2][4] = 56;
array[4][4] = 56;
for (i = 0; i < WIDTH+4;i++)
{
for (j = 0; j < HEIGHT+4; j++){
if ((array[i][j] != 49) && (array[i][j] != 50) && (array[i][j] != 51) &&
(array[i][j] != 52) && (array[i][j] != 53) && (array[i][j] != 54) && (array[i][j] != 55) &&
(array[i][j] != 56)){
array[i][j] = 32;
}
}
}
}
int main(void)
{
int i,j,x,y,score = 0,steps = 0,result = 0,selected=0;
char array[HEIGHT][WIDTH],name[20];
printf("Please Input Name: ");
scanf("%s",&name);
instruc(name,&steps,&selected);
assign(array,&selected);
board(array);
select(&selected,array);
board(array);
return 0;
}

ArrayGame. Why doesn't it update the print?

This is my C Programming assignment. We're required to build a simple game that uses array. Our game is like the popular minesweeper game. At first, we initialise the 20*50 array area. Then we put some bombs randomly in the map. In the game, the player is required to travel from the starting point to the ending point to win the game. When the player moves, the movement will make the arrays hidden so that the user knows where did he start. However, in my case, the system doesn't update and make the array empty after the player moves. Can anyone help me with my 's' code? What is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define iMAX 20
#define jMAX 50
char array[20][50];
int i; //row
int j; //column
int z; //bomb
int n; //steps counter
int o; //x
int p; //y
o = 0;
p = 0;
int level;
int bomb;
char move;
int steps;
int main() {
printf("Welcome to the BombArray Game!\n");
printf("\nLevel 1 Begineer : 50 bombs\nLevel 2 Intermediate : 100 bombs\nLevel 3 Advance : 200 bombs\n");
printf("\nI want to challenge level ");
scanf_s("%d", &level);
printf("\n");
srand(time(NULL));
for (i = 0; i < 20; i++) {
for (j = 0; j < 50; j++) {
array[i][j] = '*';
}
}
array[0][0] = 'S';
array[19][49] = 'E';
if (level == 1) {
bomb = 50;
}
else if (level == 2) {
bomb = 100;
}
else if (level == 3) {
bomb = 200;
}
for (z = 0; z < bomb; z++) {
i = rand() % 20;
j = rand() % 50;
array[i][j] = '1';
}
do {
system("cls");
for (i = 0; i < iMAX; i++) {
for (j = 0; j < jMAX; j++) {
if (array[i][j] == 'S') {
printf("S");
}
else if (array[i][j] == '*') {
printf("*");
}
else if (array[i][j] == '1') {
printf("*");
}
else if (array[i][j] == 'E') {
printf("E");
}
else if (array[i][j] == '2') {
printf(" ");
}
}
printf("\n");
}
printf("\n\nMoving direction (w:up s:down a:left d:right e:exit): ");
scanf_s(" %c", &move);
printf("Steps? ");
scanf_s("%d", &steps);
if (move == 's') {
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
}
} while (array[19][49] != 2);
return 0;
}
if (move == 's') {
array[o][p] = '2';
for (n = 0; n < steps; n++) {
i = o;
j = p;
i++;
array[i][j] = '2';
o = i;
p = j;
}
array[o][p] = 'S';
}
You have to delete the S at the Start position and write it at the end position when you move
Some additional things: You don't need that much variables. You can remove i and j (or o and p).
If you enter something others than 1-3 for the level you will have an undefined number of bombs (if you declare the bomb variable as a local variable), therefore you should make a default case.
You never look if you are hitting a bomb, you just overwrite array[i][j] without prove if there's a bomb.
better:
if (move == 's') {
array[i][j] = '2';
for (n = 0; n < steps; n++) {
i++;
if (array[i][j] == '1') {
printf("bomb\n");
return 0;
}
array[i][j] = '2';
}
array[i][j] = 'S';
}

Resources