1

I am trying accomplish the following tasks using C and arrays:

This is what I could do for now. I also need to print the output. What should I do or edit, thanks.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
    int n;
    printf("How many elements in array?:");
    scanf("%d",&n);
    int array0[n];
    for(int i = 0 ; i < n ; i++)
    {
      array0[i]= rand()%9 + 1;
    }

    int array1[10];

    for(int i = 0 ; i < 10 ; i++)
    {
      array1[i]= 0;
    }
    int index;
    for(int i = 0 ; i < n ; i++)
    {
      index = array0[i];
      array1[index-1]++;
    }
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Berkant Duman
  • 13
  • 1
  • 5

2 Answers2

1

It's fine, you just need to print the output after that:

for (int i = 1; i <= 9; ++i)
    printf("\n%d appears %d times", i, array1[i - 1]);

Note:

  1. It would be better to add srand(time(NULL)); once before calling rand() so that your code can generate different random numbers at different runtime.

  2. rand() % 9 + 1 will generate numbers in the range [1, 9]. So int array1[10]; can be changed to int array1[9]; to save some memory. But if you need numbers in the range [1, 10] then don't change that but change rand() % 9 + 1 to rand() % 10 + 1 and let the printing loop run upto 10.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
  • Didn't he said numbers between 1 and 10? Shouldn't the formula be `rand()%10 + 1` instead of making the array smaller ? – Tudor Mar 30 '20 at 14:04
  • @Tudor See my comment below the question. I was taught that, "between a and b" = [a, b). Also in statistics, frequency intervals are divided with this convention. I am not sure, but OP can clarify otherwise. Or, I'll edit my answer with this update. – Ardent Coder Mar 30 '20 at 14:11
0

As mentioned in comments , if you want number in range 1 to 10 :

array0[i]= rand()%10 + 1;

I suggest int array1[10]={0}; instead of this loop:

for(int i = 0 ; i < 10 ; i++)
{
  array1[i]= 0;
}

and here is complete code with printing:

int main()
{
int n;
printf("How many elements in array?:");
scanf("%d",&n);
int array0[n];
for(int i = 0 ; i < n ; i++)
{
  array0[i]= rand()%10 + 1;//for your range
}

int array1[10]={0};

/*for(int i = 0 ; i < 10 ; i++)
{
  array1[i]= 0;
}*/
int index;
for(int i = 0 ; i < n ; i++)
{
  index = array0[i];
  array1[index-1]++;
}
    for (int i = 0; i < 10; i++)
    {
        printf("number %d appears:%d\n", i + 1, array1[i]);
    }
}

also as @Ardent Coder said add srand(time(NULL)); bfeore rand() to generate different random numbers at different runtimes.

hanie
  • 1,863
  • 3
  • 9
  • 19
  • 1
    Please note that `int array1[10]={0};` isnt necesarelly faster since `array1` is a local (auto) variable. You should check [Difference in initializing and zeroing an array in c/c++](https://stackoverflow.com/questions/453432/difference-in-initializing-and-zeroing-an-array-in-c-c) – Tudor Mar 30 '20 at 14:20