help in a program

Why is 'break' misplaced in this program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <process.h>
void main()
{clrscr();
int p, q, r, i;
i=1;
l1:
if(i<=3)
{p=random(10);
q=random(10);
r=random(10);
cout<<p<<q<<r;
i++;
if(p==7&&q==7&&r==7)
{cout<<"winner";
break;
}
else
{cout<<"try again";
goto l1;
}
}
getch();
}
closed account (z05DSL3A)
Because break is used with loops (for, while, do while) and switch and you don't have any.
so what can i use here?
Simply because break is not allowed inside if, break is only needed on loops, switch..case etc..

if you want to end your program when ( p==7 && q==7 && r==7) then you have to do something like this:

1
2
3
4
5
if (p==7&&q==7&&r==7) {
    cout<<"winner";
    getch();
    exit ( 0 );
}


or
1
2
3
4
5
if (p==7&&q==7&&r==7) {
    cout<<"winner";
    getch();
    return 0;
}

but in the 2nd example you have to change the return type of main to int instead of void and you don't need getch() at the end of your program
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{ 
    int p, q, r, i;
    i=1;
   
    for(i = 0; i < 3; i++)
    {
        p=random(10);
        q=random(10);
        r=random(10);
        cout<<p<<q<<r;
        i++;
        if(p==7 && q==7 && r==7 )
        {
            cout<<"winner";
            break;
        }
        else
        {
            cout<<"try again";
        }
    }
}
nice ideas but I did something using goto command:)
Can you tell me how to do that program using for, while, or do while loop?(any one)
Thanks in advance:)
Topic archived. No new replies allowed.