w3resource logo


C Programming Exercises

C Exercises: Generate a random number

Secondary Nav

C Variable Type : Exercise-5 with Solution

Write a C program to generate a random number.

Expected Output :

Guess the number (1 to 10): 6                                           
The number is higher                                                    
                                                                        
Guess the number (1 to 10): 7                                           
That is correct!              

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;
	}

Solution

#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



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number