Showing posts with label Random. Show all posts
Showing posts with label Random. Show all posts

How To Write a C program that generates two random numbers ?

Write a C program that generates two random numbers.


Print both numbers that are generated.

Then use a ternary (or conditional) operator to identify the largest of the 2 numbers and print the result.

Seed the random number generator so the numbers generated are not the same every time.

Submit the .c file only.

Sample Run:

Random 1:8809
Random 2:27141
The max of 8809 and 27141 is 27141.


  1. #include <stdio.h>
  2. #include <stdlib.h> // void srand(unsigned int); - int rand(); - NULL - RAND_MAX,
  3. #include <time.h> // time_t time(time_t*) - NULL
  4.  
  5. int main()
  6. {
  7.     srand((unsigned int)time(NULL)); // seeds srand with the number of seconds since January 1st 1970
  8.     int rand1 = rand(); //init the vars to random
  9.     int rand2 = rand(); //init the vars to random
  10.     int max = rand1 > rand2 ? rand1 : rand2; //Ternary (three) conditional operator which sets max = rand1 if true and max = rand2 if false
  11.     printf("Random 1: %d \n", rand1);
  12.     printf("Random 1: %d \n", rand2);
  13.     printf("The max of %d and %d is %d \n", rand1, rand2, max);
  14.     return 0;
  15. }

C Program Generates 10 Random Integers Between 0 and 99.

How to write a C Program that Generates 10 Random Integers Number Between 0 and 99 in C Programming Language ?


This C program generates 10 random integers between 0 and 99. 
The srand() function generates a seed value for the rand() function.

Solution For C Program:

C Program to Find Random Number

How to write a C Program to Find Random Number in C Programming Language ?


Solution For C Program :

/*C Program to Find Random Number.*/

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

int main(void)
{
int i;
time_t t;
srand((unsigned) time(&t));
printf(“Ten random numbers from 0 to 99\n\n”);
for(i=0; i<10;i++)
printf(“%d\n”,rand()%100);
}

Input reads in the array positions and range for random generation.

How to write a C Program to Input reads in the array positions and range for random generation in C Programming Language ?

Solution:

  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <math.h>
  4.  
  5.     /*Input reads in the array positions and range for random generation.*/
  6.  
  7. void readInput()    {
  8.     int inputArray[2];
  9.  
  10.     puts("Please enter the number of positions and the range second:");
  11.     scanf("%d %d", &inputArray[0], &inputArray[1]);
  12.  
  13.     return inputArray[0 - 1];
  14. }
  15.  
  16. int main()  {
  17.     int inputArray[2] = readInput();
  18.  
  19.     printf("%d %d", inputArray[0], inputArray[1]);
  20. }