Reputation: 13
im a new programmer and user here. I don't want to use goto in my code because I don't want to be called " a bad programmer". I need your experience to get rid of that.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int control = 1;
char a[50], harf[5][10];
a[0] = 65 + rand() % 26;
for (int i = 1; i < 50; i++)
{
if (i % 2 == 0)
a[i] = 65 + rand() % 26;
else
a[i] = 97 + rand() % 26;
come:
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
if (i % 2 == 0)
{
a[i] = 65 + rand() % 26; goto come;
}
else
{
a[i] = 97 + rand() % 26; goto come;
}
}
else
continue;
}
cout << a[i]<<" ";
}
system("pause");
}
Upvotes: 0
Views: 50
Reputation: 4145
Replace
come:
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
if (i % 2 == 0)
{
a[i] = 65 + rand() % 26; goto come;
}
else
{
a[i] = 97 + rand() % 26; goto come;
}
}
else
continue;
}
with
int loop=0;
do
{
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
if (i % 2 == 0)
{
a[i] = 65 + rand() % 26;
}
else
{
a[i] = 97 + rand() % 26;
}
loop=1;
break;
}
else
loop=0;
}
}while(loop);
This is a more general sort of solution than some other answers. It's based on realizing that when you find a match (a[i] == a[j])
you just want to run the main for
loop again, from the top. (You can achive the same result by setting j
to -1, but that won't work in all situations, and certainly not if j
needs to be unsigned
)
Upvotes: 0
Reputation: 5779
Simply replace the come
block (the inner for-cycle) with a function. Then, instead of goto come
, you call come()
(assuming the name of the function is "come").
Upvotes: 0