JARGILA
JARGILA

Reputation: 13

goto and junping loop by loop c++

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");
}

screenshot

Upvotes: 0

Views: 50

Answers (3)

Tim Randall
Tim Randall

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

L.C.
L.C.

Reputation: 1145

No need to create a function, replace your "goto" with "j = -1;"

Upvotes: 1

Martin Heraleck&#253;
Martin Heraleck&#253;

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

Related Questions