﻿ C exercises: Generate a random number - w3resource

# C Exercises: Generate a random number

## C Variable Type : Exercise-5 with Solution

Write a C program to generate a random number.

Sample Solution:

C Code:

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

int main ()
{
int number, input;
/* initialize random seed: */
srand ( time(NULL) );
/* Generate a random number: */
number = rand() % 10 + 1;
do {
printf ("\nGuess the number (1 to 10): ");
scanf ("%d",&input);
if (number > input)
printf ("The number is higher\n");
} while (number!=input);
printf ("That is correct!\n\n");
return 0;
}
```
```

Sample Output:

```Guess the number (1 to 10): 6
The number is higher
```

C Programming Code Editor:

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

int main ()
{
int number, input;
/* initialize random seed: */
srand ( time(NULL) );
/* Generate a random number: */
number = rand() % 10 + 1;
do {
printf ("\nGuess the number (1 to 10): ");
scanf ("%d",&input);
if (number > input)
printf ("The number is higher\n");
} while (number!=input);
printf ("That is correct!\n\n");
return 0;
}```

Improve this sample solution and post your code through Disqus