C++/plz help
Expert: vijayan - 12/4/2008
Questionhi
in this code below in the line that i have signed i don't know why it just print the value x=1 and y=2 befor running BUG function though i have persisted to change the value of x and y in the 'if' or 'else'in BUG function
plz..i need your help about this problem:-(
#include <stdlib.h>
#include <time.h>
#include<string.h>
#include<stdio.h>
void BUG(int x,int y);
int stor1[50],stor2[50],mark[40][20],count=0,m,n;
void main()
{
int j=0,i=0,w=0,t=0,x=0,y=0;
printf("Enter m&n:1<m<41,1<n<21\n");
scanf("%d%d",&m,&n);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
mark[i][j]=0;
m=m+1;
n=n+1;
x=m/2;
y=n/2;
i=0;
for(j=0;j<=n;j++)
mark[i][j]='#';
i=m;
for(j=0;j<=n;j++)
mark[i][j]='#';
j=0;
for(i=0;i<=m;i++)
mark[i][j]='#';
j=n;
for(i=0;i<=m;i++)
mark[i][j]='#';
stor1[0]=m/2;
stor2[0]=n/2;
mark[x][y]=1;
t=mark[i][j];
do{
printf("BEFOR ENTERING LOOPx=%d,y=%d\n\n",x,y);//*<----------printing the same value for x and y evrey time
BUG(x,y);
for(i=1;i<=m-1;i++)
for(j=1;j<=n-1;j++){
if(t==0)
w=0;
else{
w=1;
}
}
}while(w!=1);
printf("Time=%d\n",count);
}
void BUG(int x,int y){
int a=0,b=0;
int k = 1 + int( 8.0 * ( rand() / ( RAND_MAX + 1.0 ) ) ) ;
a++;
b++;
printf("Direction=%d\n",k);
if(k==1){
x=x-1;
y=y+1;
count++;
}
else if(k==2){
y=y+1;
count++;
}
else if(k==3){
x=x+1;
y=y+1;
count++;
}
else if(k==4){
x=x+1;
count++;
}
else if(k==5){
x=x+1;
y=y-1;
count++;
}
else if(k==6){
y=y-1;
count++;
}
else if(k==7){
x=x-1;
y=y-1;
count++;
}
else if(k==8){
x=x-1;
count++;
}
stor1[a]=x;
stor2[b]=y;
if(mark[x][y]=='#'){
a=a-1;
b=b-1;
x=stor1[a];
y=stor2[b];
}
else{
mark[x][y]=1;
}
}
thanx
Bita
Answer void BUG( int x, int y ) ;
function BUG takes the parameters by value. what bug gets are copies of x and y. changes to these copies do not affect the x and y in main.
modify BUG to take the parameters by reference instead of by value:
void BUG( int& x, int& y ) ;
or, if you are programming in pure C, take the parameters by address (pointers):
void BUG( int* x, int* y ) ;
in this case, call BUG like this: BUG( &x, &y ) ;
and in BUG, use *x, *y instead of x, y.