Udemy coupon 100 off 2017 ::Udemy coupon code free :: Get 100+ Free Udemy coupons Here

Array Initialization with Random Numbers with out Repetitive Value.

Array Initialization with Random Numbers With Out Repetitive value.


Source code:


import java.util.Random;  
class ArrayInitRandom
{
public static void main(String args[])
{
int arrayVaules[]=new int[10];  
       // choose array size as per your requirement. here 10.

int tempnum;
int t=0; // just for checking purpose
Random r= new Random();
for(int j=0;;)
         {
t=0;

/*Random number generated and stored in tempnum.
   Here 10 is given as max limit (in method 
   r.nextInt(10)) because i want to initialize 
  array with values from 0 to 9. You can specify    according to your requirement. */

tempnum= r.nextInt(10);   

// This for loop is to check whether generated random //number is already there in array or 
//not.If it is already there t variable is set to 1

for(int k=0;k<j;k++)  
{
if(tempnum==arrayVaules[k])
{
t=1;
}
}
if(t!=1)
{
                arrayVaules[j]=tempnum;
j++;
if(j==10)   // My array size is 10. 
        {
break;
}
}
                       }

//To show Out put. 
for(int l=0;l<10;l++)
{
System.out.println("value at index   "+ l +"   is   "+arrayVaules[l]);
}
}
}



  • Save the file with name ArrayInitRandom.java 
  • Complie with: javac ArrayInitRandom.java
  • Run with: java ArrayInitRandom


Out Put is as following :
(Note that Out put may very as we have initialized with random numbers.) 


No comments:

Post a Comment