C program that generates a random positive float number in a fixed interval with a maximum distance between endpoints of 100
Posted by Samath
Last Updated: January 01, 2017

Write a C program that generates a random positive float number in a fixed interval with a maximum distance between endpoints of 100 (e.g. [0,100] or [101,201]). Both interval points are given by the user through console. The generated random number inside the given interval must be less than or equal to 10975. Calculate the factorial (n!) of the resulting random number.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])

{
	int flag = 0; // This flag is used to control the while loops to get the correct input from the user.
	int i; // This is the counter for the for loops.
	double factorial = 1; // This will accumulate the factorial for our random number.
	int endpoint1, endpoint2; // This will be the endpoints for the interval that our random number will be inside of.
	int distance; // This will be the distance between the two endpoints
	srand(time(NULL)); // This will help generate better random numbers by using the current time as the seed.
	// This while loop will assure the program that the user only inputs a number less than 10875.
	while(flag == 0)
	{
		printf("Enter first endpoint of interval: ");
		scanf("%d", &endpoint1);
		if(endpoint1 <= 10875 && endpoint1 >= 1) // It makes sure that the number is smaller than 10876 and bigger than 0.
		flag = 1;// When this flag changes to 1, the user's input was correct.
	}
	flag = 0; // Since we will used it again for our second input
	// This while loop will assure the program that the user only inputs a number that will have a maximum distance of 100 from the first endpoint.
	while(flag == 0)
	{
	printf("Enter second endpoint of interval: ");
	scanf("%d", &endpoint2);
	distance = endpoint2 - endpoint1;
	if(distance <= 100 && distance >= 1) // It makes sure that the distance between endpoints is smaller than 101 and bihher than 0.
		flag = 1;// When this flag changes to 1, the user's input was correct.
	}
	printf("The inputs for the interval are [ %d , %d ]\n", endpoint1, endpoint2);
	int random = endpoint1 + (rand()%distance)+1; // This generates our random number between our two endpoints.
	printf("Random number: %d\n", random);
	/*
	This for loop accumulates the factorial of each number until we reach our random number.
	Unfortunately I couldn't find a data type that could hold up such big numbers when it passes over 170.
	The unsigned long int can only hold up to 4294967295. The one I used was double which holds up to 1.8x10^308.
	The more appropiate datatype would be long double which can hold up to 1.2x10^4932.
	*/

	for( i = 1; i <= random; i++)
	{
		factorial *= i;
	}
	printf("The factorial for the random number %d is: %f\n", random, factorial);
	system("PAUSE");
	return 0;
}