C array's values changing randomly - c

Okay so I have been working on a small rouge like game to teach myself c however I cannot figure out why the array's end up changing randomly after initialization. Here is the code I have:
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
const int x=10;
const int y=10;
int rexit[]={5,5};
int player[]={1,1};
int enemy[]={x,y};
int useless[]={1,1};
/*
int getinput(int len){
char temp[100];
return(atoi(strtok(fgets(temp,len+1,stdin),"\n")));
}
*/
void bad(){
float bob;
float temp[8]={1,1};
temp[1]=player[1]-enemy[1];
temp[2]=player[2]-enemy[2];
bob=pow(temp[1],2)+pow(temp[2],2);
printf("%f\n",bob);
if (sqrt(bob)<=5){
if (abs(player[1]-enemy[1])>abs(player[2]-enemy[2])){
if (player[1]-enemy[1]<0 && enemy[1]-1>=0){
enemy[1]=enemy[1]-1;
}
else if (enemy[1]+1<=x && player[1]-enemy[1]!=0){
enemy[1]=enemy[1]+1;
}
}
else;
if (player[2]-enemy[2]<0 && enemy[2]-1>=0){
enemy[2]=enemy[2]-1;
}
else if (enemy[2]+1<=y && enemy[2]-player[2]!=0){
enemy[2]=enemy[2]+1;
}
}
}
void map() {
int s;
int a;
bad();
printf("%i %i\n",rexit[1],rexit[2]);
printf("+");
for (a=0;a<=x;a++){
printf("-");
}
printf("+\n");
for (s=0;s<=y;s++){
printf("|");
for (a=0;a<=x;a++){
if ((player[1]==rexit[1] && player[2]==rexit[2]) || (player[1]==enemy[1] & player[2]==enemy[2])){
exit(EXIT_SUCCESS);
}
else if (rexit[1]==s && rexit[2]==a){
printf("E");
}
else if (player[1]==s && player[2]==a){
printf("*");
}
else if (enemy[1]==s && enemy[2]==a){
printf("#");
}
else{
printf(".");
}
}
printf("|\n");
}
printf("+");
for (a=0;a<=x;a++){
printf("-");
}
printf("+\n");
}
void move(){
char me=_getch();
int temp=0;
me=toupper(me);
if (me=='W'){ player[1]=player[1]-1; if (player[1]<=0) player[1]=0;}
else if (me=='S'){ player[1]=player[1]+1; if (player[1]>=y) player[1]=y;}
else if (me=='A'){ player[2]=player[2]-1; if (player[2]<=0) player[2]=0;}
else if (me=='D'){ player[2]=player[2]+1; if (player[2]>=x) player[2]=x;}
else {temp=1;}
if (temp==1){
move();}
else{
system("cls");
map();}
}
void circle(char c,int x)
{
int i,j;
for(i=-x;i<x;i++)
{
for(j=-x;j<x;j++)
{
if(i*i+j*j<x*x)
printf("%c",c);
else
printf(" ");
}
printf("\n");
}
}
void main(){
printf("%i %i\n",enemy[1],enemy[2]);
printf("%i %i\n",useless[1],useless[2]);
system("title BioGames");
system("color A"); // the colours are from 1 to 15
map();
while (true){
move();
}
}

You are treating your array indexing as 1-based. Arrays in C are 0-based.
For example, you declare:
int player[]={1,1};
The only valid indices for this array are 0 and 1 (ie player[0] and player[1]).
There is no such thing as player[2] - that is accessing memory outside the array bounds. This is probably why you think your arrays are changing randomly. They are either being affected by out-of-bound writes to other arrays, or you are simply experiencing undefined behaviour.

Your arrays useless and enemy are declared to contain two values each at initialization. Your main is printing array indices 1 and 2. In C, however, array indices start at 0. So you should be printing indices 0 and 1.

Related

how to print an array in c according to if they are ascending and descending in different lines?

I am trying to print the elements of an array in different lines according to if they are ascending or descending. for example I have an array:
a[] = {3,5,6,8,4,2,-1,-3,6,5,4,1,3}; after I call the method printArr(a, sizeof(a), indexStart); the output should be:
3568
842-1-3
-36
6541
13
here is my code:
void printArr(int *a, int size, int index){
int i=index;
if(i==size)
return;
printf("%d",a[i]);
if(a[i]<a[i+1]){
while(a[i]<a[i+1] && i<size){
printf("%d",a[i+1]);
i++;
}
printf("\n");
}
else{
while(a[i]>a[i+1] && i<size){
printf("%d",a[i+1]);
i++;
}
printf("\n");
}
printArr(a,size,i);
}
here is my main:
int main()
{
int a[] = {3,5,6,8,4,2,-1,-3,6,5,4,1,3};
printArr(a,13,0);
return 0;
}
when I run it (CodeBolcks) I get the following input:
3568
842-1-3
-36
6541
1370
where did the 70 at the end come from?
when I compile it in Linux(terminal) I get the following :
3568
842-1-3
-36
6541
1332767
where did the 32767 at the end come from? how can I fix my code?
I have to use loops and recursion.
i range check is wrong.
fix like this
void printArr(int *a, int size, int index){
int i=index;
if(i>=size-1)
return;
printf("%d",a[i]);
if(a[i]<a[i+1]){
while(i<size-1 && a[i]<a[i+1]){
printf("%d",a[i+1]);
i++;
}
printf("\n");
}
else{
while(i<size-1 && a[i]>a[i+1]){
printf("%d",a[i+1]);
i++;
}
printf("\n");
}
printArr(a,size,i);
}

How to incorporate an input array in this program

This is a code that has to take an input array from the user and input the same after removing the duplicates. However, I am unsure on how to incorporate an input array in this, and right now it has the elements hardcoded. This is my first week of programming so I apologize if this is a silly question. This is the code:
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int l[nelems] = {1,2,3,1,4,4,5,6};
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
Try using a for loop and scanf.
int i;
for(i=0;i<nelems;i++){
scanf("%d",&l[i]);
}
This is what you need.
#include <stdio.h>
#include <stdbool.h>
#define nelems 8
int main()
{
int i;
int l[nelems] ;
for(i=0;i<nelems;i++)
{
printf("enter %d number :",i);
scanf("%d",&l[i]);
}
for(int m=0;m<nelems;m++)
{
bool wase = 0;
for(int n=0;n<nelems && m>n;n++)
{
if (l[m] == l[n] && m != n)
wase = 1;
}
if (wase == 0){
printf("%d\n", l[m]);
}
}
return 0;
}
If you like int-type array, you can just declare another one:
int input[nelems];
and follow the user968000 advice, remembering that when you are typing the sequence in your console you have to put a white space between each number.
To avoid that, I'd rather use char-type arrays, declared as follows:
char l[nelems] = {'1', '2', '3' /*etc.*/};
char input[nelems];
Then you make a for loop, as user968000 suggested:
int i;
for(i=0;i<nelems;i++)
scanf("%c", &input[i]);
In this case you won't need the white spaces between the digits. Notice the '&' character in the scanf function: just put it as I showed, you'll surely learn what it is in next lessons.
So you have an input array and you can handle it as you want.

8 Puzzle with Backtracking

I was reading this book from Skiena, Programming Challenges and after the backtracking chapter there was a question about solving the 15-puzzle with backtracking, which I reduce it to 8-puzzle just experimenting. I have this recursive code and I am wondering whether it have a chance to find the solution ever. The code is kind of ugly (be warned):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int arr[20][20]={
{3,1,2},
{4,0,5},
{6,8,7}
};
int moveX[20]={1,1,1,0,0,-1,-1,-1};
int moveY[20]={0,1,-1,1,-1,0,1,-1};
int depth=0;
int findRow(){
int i,j;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(arr[i][j]==0){
return i;
}
}
}
}
int findCol(){
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(arr[i][j]==0){
return j;
}
}
}
}
void print(){
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%i ",arr[i][j]);
}
printf("\n");
}
printf("\n");
}
int isReady(){
if(arr[0]==1 && arr[1]==2 && arr[2]==3 && arr[3]==4 && arr[4]==5 && arr[5]==6 && arr[6]==7 && arr[7]==8){
return 1;
}
else return 0;
}
void perm(int row,int col,int n){
if(n>=9){
print();
if(isReady())
printf("Finished");
depth++;
return;
}
int i=0;int diffX,diffY,temp;
int r=findRow();
int c=findCol();
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
for(i=0;i<8;i++){
diffX=row+moveX[i];
diffY=col+moveY[i];
if(diffX>=0 && diffX<4 && diffY>=0 && diffY<4){
perm(diffX,diffY,n+1);
}
}
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
}
int main()
{
perm(0,0,0);
return 0;
}
My question is, is there a chance with this code to find the solution and second, can anybody how the puzzle can be solved in reasonable time?
You have five problems. First, the isReady function is incorrect. It should look like this:
int isReady(){
if(arr[0][0]==1 && arr[0][1]==2 && arr[0][2]==3 &&
arr[1][0]==4 && arr[1][1]==5 && arr[1][2]==6 &&
arr[2][0]==7 && arr[2][1]==8){
return 1;
}
else return 0;
}
Second, you are exceeding your puzzle bounds with diffX and diffY. You need to change this:
if(diffX>=0 && diffX<4 && diffY>=0 && diffY<4){
to this:
if(diffX>=0 && diffX<3 && diffY>=0 && diffY<3){
Third, your findRow function also exceeds the puzzle bounds. Change all of the 4 to 3.
Fourth, you should check your victory condition only after you have made your move. So move your victory check below the swap:
temp=arr[r][c];
arr[r][c]=arr[row][col];
arr[row][col]=temp;
// This victory check is now below the move.
if(n>=9){
print();
if(isReady())
printf("Finished");
depth++;
return;
}
Fifth, you should change your initial call from this:
perm(0,0,0);
to this:
perm(1,1,0);
The way you have it, you are always forcing a move to the upper left as your first move. The modified way keeps the 0 in the center so it doesn't force your first move. When I ran this code with all of the modifications I made, it found 3 solutions. When I further modified the code to check for solutions at any depth, it found 2 solutions at depth 8 and 3 solutions at depth 9.

Comparing two arrays in C?

So I have two arrays, a[17] and b[12]. I want to compare the first 12 numbers of each, and if the numbers match have it print out a "0", if they dont match have it print out a "1". But it doesnt work. It should print "000001111111 " but it doesnt. Can anyone please tell me why?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i, j;
int a[17] = {1,0,1,0,0,1,0,1,0,1,0,0,0,1,1,0,1};
int b[12] = {1,0,1,0,0,0,1,0,1,0,1,1};
for(i=0;i<12;i++)
for(j=0;j<12;j++)
if(a[i] == b[j])
printf("1");
else
printf("0");
system("pause");
return 0;
}
Your code should be:
for(i=0;i<12;i++) {
if(a[i] == b[i]) {
printf("1");
} else {
printf("0");
}
}
There is no need of two loops.
You want to compare elements from arrays at same indices, so the indices i should be same for both arrays.

Using a different library in C

I just coded from scratch a program that would count the upper and lowercase letters and blank spaces of whatever the user input. Since then I found out that code for those specific functions have already been prewritten in another library! My question is, how can all the code that I have written below be simplified with the use of
isupper(int c), islower(int c), and isspace(int c) which are defined in ctype.h.
#include <stdio.h>
int main(void){
int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;
printf("Please enter a phrase:\n\n");
while((iochar=getchar())!=EOF)
{
if ((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
{
numwhites++;
putchar(iochar);
}
else
if((iochar>='0')&&(iochar<='9'))
{
numdigits++;
putchar(iochar);
}
else
if(('a'<=iochar)&&(iochar<='z'))
{
numlower++;
putchar(iochar-32);
}
else
if(('A'<=iochar)&&(iochar<='Z'))
{
numupper++;
putchar(iochar);
}
else
putchar(iochar);
}
printf("%d white characters, %d digits, ",numwhites,numdigits);
printf("%d lowercase have been converted to ",numlower);
printf("uppercase and %d uppercase.\n",numupper);
printf("\n\n");
return 0;}
Here is it written better and cleaned up:
#include <stdio.h>
#include <ctype.h>
int main(int argc, char **argv) {
int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;
printf("Please enter a phrase:\n\n");
while ((iochar=getchar()) != EOF) {
// increase counts where necessary
if (isspace(iochar)) {
numwhites++;
} else if (isdigit(iochar)) {
numdigits++;
} else if (islower(iochar)) {
numlower++;
iochar = toupper(iochar);
} else if (isupper(iochar)) {
numupper++;
}
// this happens always, don't put it in the if's
putchar(iochar);
}
printf("%d white characters, %d digits, ", numwhites, numdigits);
printf("%d lowercase have been converted to ", numlower);
printf("uppercase and %d uppercase.\n", numupper);
printf("\n\n");
return 0;
}
Just #include <ctype.h> and then change e.g.
if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
to
if (isspace(iochar))
etc.
For full details see man ctype.

Resources