Scala | Create Array with Range
Last Updated :
11 Apr, 2023
Array is a special kind of collection in Scala. It is a fixed size data structure that stores elements of the same data type. By using range() method to generate an array containing a sequence of increasing integers in a given range. We can use final argument as jump to create the sequence. if we do not use final argument, then jump would be assumed as 1. Below are some examples of array with range:
Example:
Scala
// Scala program to create array with range
import Array._
// Creating object
object GFG
{
// Main method
def main(args: Array[String])
{
var array1 = range(1, 15)
var array2 = range(1, 15, 3)
// Print all the elements of array1
for ( i <- array1 )
{
print( " " + i )
}
println()
// Print all the elements of array2
for ( i <- array2 )
{
print( " " + i )
}
}
}
In above example, an array of range (1, 15). In this range difference is not given so by default difference of range will be 1 element. Elements in the array are 1, 4, 7, 10 and 13. Here, we are creating an array of range (1, 15, 3). Which means an array with elements between 1 and 15 and range difference is 3. Elements in the array are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, and 14. For some of the collections, such as List and Array, we can also create a Range and convert it to the desired sequence: The REPL shows the array that can be created directly from a Range is toArray. We can also use a Range to create a sequence of characters as below:
Example:
Scala
// Scala program to create array with range
import Array._
// Creating object
object GFG
{
// Main method
def main(args: Array[String])
{
val array1 = ('A' to 'F').toArray
val array2 = ('a' to 'f').by(2).toArray
// Print all the elements of array1
for ( i <- array1 )
{
print( " " + i )
}
println()
// Print all the elements of array2
for ( i <- array2 )
{
print( " " + i )
}
}
}
In above example, an array of range ('A' to 'F').toArray. In this, range difference is not given so by default difference of range will be 1 character. characters in the array are A, B, C, D, E and F. Here, we are creating an array of range ('a' to 'f').by(2).toArray. Which means an array with characters between a and f and range difference is 2. Characters in the array are a, c, and e.
In Scala, you can create an array with a range using the Array.range() method. This method takes three arguments: start, end, and step. It generates a sequence of values from start to end (exclusive) with a specified step value and returns an array containing those values.
Here's an example code that creates an array of integers from 1 to 10 with a step of 2 using Array.range() method:
Scala
object RangeArrayExample {
def main(args: Array[String]): Unit = {
val arr: Array[Int] = Array.range(1, 10, 2)
println("Printing array elements:")
for (i <- arr) {
println(i)
}
}
}
OutputPrinting array elements:
1
3
5
7
9
In this example, we first create an array arr using Array.range() method with start value of 1, end value of 10 (exclusive), and step value of 2. Then, we use a for loop to print each element of the array. As a result, the output is an array of integers from 1 to 10 with a step of 2.
Advantages of creating an array with a range using Array.range() method in Scala:
- It provides a concise and readable way to create arrays with a range of values.
- The step argument allows you to create arrays with a specified interval between elements.
- It returns an array with a fixed size, which is useful when you need to work with arrays of a specific length.
Disadvantages of creating an array with a range using Array.range() method in Scala:
- It only works with numerical data types, such as Int, Double, Float, etc.
- It generates a new array object every time it is called, which can be inefficient for large arrays. In such cases, it may be more efficient to create an empty array and then populate it with values using other methods.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read