0

I am writing a random compliment generator program in C

#include <stdio.h>

int main()
{
    int i;
    char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
    for(i=0;i<sizeof(compliment)/sizeof(compliment[0]);i++)
    {
        puts(compliment[i]);
    }
    return 0;
}

output of this program is:

You look so beautiful!
You are a great person!
Your hair is so stunning!

But I want the compliments to be displayed randomly and just one not all of them. How can I do this? which function should I use?

EDIT: Thanks for comments. I did it:

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

int main()
{
int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
srand(time(NULL));
puts(compliment[rand() % 3]);
return 0;
}
OrangeBike
  • 145
  • 8
  • 1
    look for the `rand()` function to generate a random index – MarcoLucidi May 16 '20 at 09:41
  • 1
    What do you mean with one at a time? if you want to pick one of the messages randomly, remove the `for` line and use `puts(compliment[rand() % 3]);` Do not forget to set the seed with `srand(time(NULL));` at the very begin. – David Ranieri May 16 '20 at 09:41
  • Thank you I am reading about it now. Seems like this is what I need! – OrangeBike May 16 '20 at 09:42

1 Answers1

1

First we can use the shuffle() function from Shuffle array in C

void shuffle(int *array, size_t n)
{
    if (n > 1) 
    {
        size_t i;
        for (i = 0; i < n - 1; i++) 
        {
          size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
          int t = array[j];
          array[j] = array[i];
          array[i] = t;
        }
    }
}

Add

#include <time.h>

And in main()

int i;
char compliment[3][30] = {"You look so beautiful!", "You are a great person!", "Your hair is so stunning!"};
const int size = sizeof(compliment)/sizeof(compliment[0]);
srand(clock()); // set random seed

int a[size];
for(i=0 ; i<size ; i++) a[i] = i;
shuffle(a, size);

for(i=0;i<size;i++)
{
    puts(compliment[a[i]]);
}
Déjà vu
  • 28,223
  • 6
  • 72
  • 100