Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fill an array with consecutive numbers

Tags:

java

arrays

input

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!!!

like image 418
Dan Avatar asked Feb 13 '15 01:02

Dan


People also ask

How do you order an array of consecutive numbers?

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.

How do you create an array of consecutive numbers in C++?

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]);

What is consecutive number in array?

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.


2 Answers

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
like image 172
Sotirios Delimanolis Avatar answered Sep 28 '22 09:09

Sotirios Delimanolis


The simple way is:

int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
    array[k] = k + 1;
like image 30
user253751 Avatar answered Sep 28 '22 10:09

user253751