C Program to Build Number Guessing Game on Command Line

Hello reader, If you are looking to know the concept “C Program to Build Number Guessing Game on Command Line” then read this article to learn about it clearly. Move on to the article directly.

C Program to Build Number Guessing Game on Command Line

C Program to Build Number Guessing Game on Command Line

Source Code

// C program for the above approach
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

// Function that generate a number in
// the range [1, N] and checks if the
// generated number is the same as the
// guessed number or not
void guess(int N)
{
	int number, guess, numberofguess = 0;

	// Generate a random number
	number = rand() % N;

	printf("Guess a number between"
		" 1 and %dn",
		N);

	// Using a do-while loop that will
	// work until user guesses
	// the correct number
	do {

		if (numberofguess > 9) {
			printf("nYou Loose!n");
			break;
		}

		// Input by user
		scanf("%d", &guess);

		// When user guesses lower
		// than actual number
		if (guess > number)

		{
			printf("Lower number "
				"please!n");
			numberofguess++;
		}

		// When user guesses higher
		// than actual number
		else if (number > guess)

		{
			printf("Higher number"
				" please!n");
			numberofguess++;
		}

		// Printing number of times
		// user has taken to guess
		// the number
		else
			printf("You guessed the"
				" number in %d "
				"attempts!n",
				numberofguess);

	} while (guess != number);
}

// Driver Code
int main()
{
	int N = 100;

	// Function call
	guess(N);

	return 0;
}

Final Thoughts

I hope this article helps you to know about “C Program to Build Number Guessing Game on Command Line“. If you face any issues please let me know via the comment section. Share this article with other C/C++ developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment