Coding Challenge Day- 17: Problem 2: Generate an integer array with random numbers

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 17: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: Generate an integer array with random numbers and also the numbers are upto a certain number

Sample input: int length=7, number=20;
Output: [11, 19, 6, 8, 7, 4, 3]

Solutions:

package array;

import java.util.Arrays;

public class Program013generate_random_array {
	
	public static void generate_random_array (int length, int number){
		int array[] = new int[length];
		
		for(int i=0; i<length; i++){
			array[i]= (int) (Math.random()*number); //by multiplying with number the numbers are generated from 0 to number-1
		}
		
		System.out.println(Arrays.toString(array));
	}
	
	public static void main (String [] args){
		int length=7, number=20;
		
		generate_random_array(length, number);
	}
}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: