R
R
Retr0Hacker2021-11-25 13:29:08
C++ / C#
Retr0Hacker, 2021-11-25 13:29:08

How to check if a number is repeatable in an array?

Good day to all! I'm still new to C, but I need to complete the task:

Generate an array of K (K <= 200) odd random numbers (use library functions to generate random numbers). The array must not have identical parts. Determine the minimum and maximum elements of the array and indicate their numbers.

How can I check if a number repeats in an array?
Thanks in advance to everyone who responds;)

The code that is now:

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

void main()
{
  srand(time(nullptr));
  const int SIZE = 10;
  int arr[SIZE];;
  int *ptr;
  for (size_t i = 0; i < SIZE; i++)
  {
    ptr = arr + i;
    while (true)
    {
      *ptr = rand() % 1000;
      if (*ptr % 2 == 0)
        continue;
      
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-11-25
@wataru

Get a flag variable. Loop through the already formed array, compare the current number with the number in the array. If a match is found, write it to the bool flag. After the loop, look at the flag.
You can exit the loop with a break if it matches.
Odd numbers can be generated immediately by multiplying random by 2 and adding 1.

R
Rsa97, 2021-11-25
@Rsa97

In the general case - go through the already filled part of the array and check that the new number does not occur there.
In your particular case, you can create an array of 1000 elements and mark already recorded numbers in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question