-
Breaking out of a loop
I dont know how to break out of two loops when the number input by the user is found. A user enters a number and it searches the array num[4][8] and when this prints obviously it prints that the number was found or not found 4 times because it only broke the inner loop ONLY when the number has found a match.
Please help! thanks!
Code:
void diff()
{
char ans;
int s;
printf("\n\nSearch for a number in the array?");
fflush(stdin);
scanf("%c", &ans);
if(ans == 'y' || ans == 'Y')
{
printf("\n\nKey in integer to be searched for:");
fflush(stdin);
scanf("%d", &s);
for(suba = 0; suba < 4; suba++)
{
for(subb = 0; subb < 8; subb++)
{
if(num[suba][subb] == s)
{
printf("\n%d is in the array\n", s);
break;
}
else
{
printf("\n%d is not in the array\n", s);
break;
}
}
}
}
if(ans == 'N' || ans == 'n')
{
eoj();
}
}
-
There are two common ways:
Code:
/* Set a flag */
int done = 0;
for ( i = 0; i < 4 && !done; i++ ) {
for ( j = 0; j < 8; j++ ) {
if ( something ) {
done = 1;
break;
}
else {
/* Keep going */
}
}
}
Code:
/* The dreaded goto */
for ( i = 0; i < 4; i++ ) {
for ( j = 0; j < 8; j++ ) {
if ( something )
goto end;
else {
/* Keep going */
}
}
}
end:
-
There's a third less used way...
Code:
for( i = 0; i < foo; i++ )
{
for( x = 0; x < bar; x++ )
{
for( z = 0; z < foo + bar; z++ )
if( condition )
exit( 0 );
else
dostuff( ";)" );
}
}
Quzah.
-
Re
I think one of these might do it. I will give them a try and let you know how it goes. Thanks you guys! =)
-
Re
The exit (0); did it, thanks a lot guys!
-
MORE trouble
I need this to go back to the top and run read() again. I have put them all in one fucntion ebcause its driving me crazy. this assignment never ends. I sure hope this course does! sever e crippling/blinding migraines dont help but I dont question the CAUSE!
Code:
void read()
{
for(suba = 0; suba < 4; suba++)
{
for(subb = 0; subb < 8; subb++)
{
x = rand()%51;
num[suba][subb] = x;
printf("%4d", num[suba][subb]);
}
printf("\n");
}
printf("\n\nSearch for a number in the array?");
fflush(stdin);
scanf("%c", &ans);
if(ans == 'y' || ans == 'Y')
{
printf("\n\nKey in integer to be searched for:");
fflush(stdin);
scanf("%d", &s);
for(suba = 0; suba < 4; suba++)
{
for(subb = 0; subb < 8; subb++)
{
if(num[suba][subb] == s)
{
printf("\n%d is in the array\n\n", s);
printf("Press enter to continue\n\n");
fflush(stdin);
getchar();
exit(0);
}
else
{
printf("\n%d is not in the array\n\n", s);
printf("Press enter to continue\n\n");
fflush(stdin);
getchar();
exit(0);
}
}
}
}
if(ans == 'N' || ans == 'n')
{
eoj();
}
}
-
Actually, exit( 0 );, was meant as a joke. It exits the program.
Quzah.
-
-
I read that. And explained it before. I don't know whether or not I should believe the FAQ. I have no reason to believe its not strapped with more terrorist bombs.
-
You read it, yet you still use it?
Bah wth, just noticed it didn't convert the URL. sigh