Header Ads Widget

How to generate random no in c language.

In c there are two function which is used to generate random numbers "rand() and stand()".Which is present in "stdlib.h" header file.
rand()=it is used to generate random numbers.
sran()=it is used before rand() to generate every time               different random numbers.
syntax:.  num=(ran()%(max limit-min limit+1))+min;

Example:
                 If we have to generate random numbers in between 1 to 6.and sum of numbers is equal to 20 .
Then program for this is-

  #include<stdlib.h>
  #inclide<time.h>
   Void main()
    {
        int max,min,sum=0,t;
        min=1;
        max=6;
                        //Space is important at this place
        srand((time(0)); 

        While(1)    // 1 for continuous loop
         {
             t=(ran()%(6-1+1))+1;//formulla
             sum=sum+t;
             if(sum<=20)
                 print("%d ",t);
             else
             {
                if(sum==20)
                   break;
                sum=sum-t;
              }
          }
          getch();
}
                

Post a Comment

1 Comments