-2

I´m very new at coding and I want to create a programm that generates 6 random numbers in an array, and repeat the process 20 times. So far, I can get the array to fill with random numbers and to do the 20 loops but I can´t get the random numbers from repeating inside the array. Any tips?

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    printf("\n5.1 Lottoziehung 6 aus 49 \n\n");

    int Ziehung[6]; 
    int Zufallszahl; //random variable
    srand((unsigned) time(0));
    for (int i=1; i<=20; i++)//Iterationen
    {
        printf("Ziehung %i: ",i); //Ziehungen Anzahl (the 20 loops)

                    for (int j=0;j<=5;j++){ //Array

                        int Zufallszahl=(rand() % 49)+1; //random num gen

                            if (Zufallszahl>0){
                            Ziehung[j]=Zufallszahl; //Array; Zahl innerhalb Ziehung widerholt
                            printf(" %i,",Ziehung[j]);
                            }//if
                            else {
                            j-1;
                            }//else
                }//for

                 printf("\n");
 }

    return 0;
}
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
0079x
  • 1
  • welcome to stackoverflow. i recommend [taking the tour](https://stackoverflow.com/tour), as well as reading [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [what's on topic](https://stackoverflow.com/help/on-topic).  and please notice that `c#` is very different from `c` – Franz Gleichmann Nov 30 '21 at 12:19
  • Does this answer your question? [C Generate random numbers without repetition](https://stackoverflow.com/questions/23176467/c-generate-random-numbers-without-repetition) (search term: `c random without repetition`) – Franz Gleichmann Nov 30 '21 at 12:19
  • 1
    `j-1;` <<-- does nothing. (expression has no side effects) – wildplasser Nov 30 '21 at 12:22

1 Answers1

0

All things are esier if you divide your program into some pieces and put them into the functions:

int isDistinct(const int *array, const int val, const size_t len)
{
    int result = 1;
    for(size_t i = 0; i < len; i++)
    {
        if(array[i] == val)
        {
            result = 0;
            break;
        }
    }
    return result;
}

#define SIZE 6

int main(void)
{
    int Ziehung[SIZE]; 
    int Zufallszahl; //random variable

    srand(time(NULL));

    for(size_t i = 0; i < SIZE; )
    {
        Zufallszahl = rand() % 49 + 1;
        if(isDistinct(Ziehung, Zufallszahl, i))
        {
            Ziehung[i] = Zufallszahl;
            i++;
        }
    }
    for(size_t i = 0; i < SIZE; i++)
    {
        printf("[%d] ", Ziehung[i]);
    }
    printf("\n");
}
0___________
  • 60,014
  • 4
  • 34
  • 74