I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
How do i fill this array with consecutive numbers starting from 1? All help is appreciated!!!
Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.
In C++ there is already such a function that is named iota and declared in the header <numeric> . do { i = 0; a = a - i; array[a - 1] = a; i++; } while (a > 0); the variable a is not being changed because in the beginning of each iteration the variable i is set to 0. printf("Resulting array is %d", array[a]);
Consecutive numbers are numbers that follow each other in order. They have a difference of 1 between every two numbers. In a set of consecutive numbers, the mean and the median are equal. If n is a number, then the next numbers will be n+1 and n+2.
Since Java 8
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range
is in increments of 1. The javadoc is here.
Or use rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
The simple way is:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
array[k] = k + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With