-
What's wrong with this?
I am trying to get this thing work out but i am completely helpless now. I have problem in that bold part.
Code:
for (i=0; i<N; i++)
{
a[i+1]=a[i];
b[i+1]=b[i];
val=random()%MAX;
printf("val=%d\n",val);
if (val==0)
{
x=x+1;
a[i+1]=x;
}
else if (val==1)
{
y=y+1;
b[i+1]=y;
}
else if (val==2)
{
x=x-1;
a[i+1]=x;
}
else {
y=y-1;
b[i+1]=y;
}
for (q=0; q<i+1; q++)
{
if (a[q]==a[i+1] && b[q]==b[i+1])
goto found;
}
found:
printf("exit2\n");
}
-
What are you trying to do and what does it do?
-
Sorry i posted on worng part . I am writing C code not C++.
I am trying to check final value instored at a and b with their previous values and just got to found and print exit2.
-
and how does it not work?
can you post a compilable example?
-
Basically the random number help to get me the values of a[] and b[]. Then with and for statement i am just trying to get those values of a [] and b[] and trying to compare.
-
can you post a compilable example?
-
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 4
#define ISEED 1000
#define N 3
#define M 1
double a[N+1], b[N+1];
int main()
{
int val, i, j,v,f, q;
srandom(ISEED);
for (j=0; j<M; j++)
{
for (v=0; v<N+1; v++)
{
a[v]=0; b[v]=0;
}
int x=0,y=0;
for (i=0; i<N; i++)
{
a[i+1]=a[i];
b[i+1]=b[i];
val=random()%MAX;
printf("val=%d\n",val);
if (val==0)
{
x=x+1;
a[i+1]=x;
}
else if (val==1)
{
y=y+1;
b[i+1]=y;
}
else if (val==2)
{
x=x-1;
a[i+1]=x;
}
else {
y=y-1;
b[i+1]=y;
}
for (q=0; q<i+1; q++)
{
if (a[q]==a[i+1] && b[q]==b[i+1])
goto found;
}
found:
printf("exit2\n");
}
}
-
it should print exit2 once only but it's not so.
-
Well, it's repeating because your found label is inside a loop.
-
i am just testing my program thru that printf statement. I just want to break both the loop i.e i and q when the condition is true.
-
if (a[q]==a[i+1] && b[q]==b[i+1])
when this condition is true the loop should break and the loop of for(i.... ) should also break.
-
Ok, then put the found label on the other side of the }.
-
Then introduce a flag,
Code:
int flag = 1;
for (i = 0; (i < N) && (flag != 0); i++)
{
for(q = 0; (q < i + 1) && (flag != 0); q++)
{
}
}
Don't use goto.
-
Thanx robwhit that worked. I was just wandering and thinking it in complicated ways.
-
Some people recommend using a goto to break out of nested loops.
-
I am completely new to this field this is my third program.
So, can u explain me why shouldn't we use goto.
-
Use of goto is generally not recommended because there are more legible alternatives to use instead, like loops. Sure, one or two gotos may not seem that bad, but it makes the program flow jump all over the place makes it more difficult to see what's going on.
-
in this case M can be more than one. So i want o get of that loop and again start the program fro next value.
-
when i kept found: just above for(j=0........) statement it didn't work.
-
Ok, then I would suggest you use flags like zacs7 suggested.