Scala – Files I/O

Scala – Files I/O ”; Previous Next Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files. The following is an example program to writing to a file. Example import java.io._ object Demo { def main(args: Array[String]) { val writer = new PrintWriter(new File(“test.txt” )) writer.write(“Hello Scala”) writer.close() } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file. Output Hello Scala Reading a Line from Command Line Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line. Example object Demo { def main(args: Array[String]) { print(“Please enter your input : ” ) val line = Console.readLine println(“Thanks, you just typed: ” + line) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Please enter your input : Scala is great Thanks, you just typed: Scala is great Reading File Content Reading from files is really simple. You can use Scala”s Source class and its companion object to read files. Following is the example which shows you how to read from “Demo.txt” file which we created earlier. Example import scala.io.Source object Demo { def main(args: Array[String]) { println(“Following is the content read:” ) Source.fromFile(“Demo.txt” ).foreach { print } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Following is the content read: Hello Scala Print Page Previous Next Advertisements ”;

Prolog – Hello World

Prolog – Hello World ”; Previous Next In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment. Hello World Program After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows − write(”Hello World”). Note − After each line, you have to use one period (.) symbol to show that the line has ended. The corresponding output will be as shown below − Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console. Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps − Step 1 − From the prolog console, go to File > Change Dir, then click on that menu. Step 2 − Select the proper folder and press OK. Now we can see in the prolog console, it shows that we have successfully changed the directory. Step 3 − Now create one file (extension is *.pl) and write the code as follows − main :- write(”This is sample Prolog program”), write(” This program is written into hello_world.pl file”). Now let’s run the code. To run it, we have to write the file name as follows − [hello_world] The output is as follows − Print Page Previous Next Advertisements ”;

Scala – Exception Handling

Scala – Exception Handling ”; Previous Next Scala”s exceptions work like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn”t actually have checked exceptions. When you want to handle exceptions, you use a try{…}catch{…} block like you would in Java except that the catch block uses matching to identify and handle the exceptions. Throwing Exceptions Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows. throw new IllegalArgumentException Catching Exceptions Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle exception. Example import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader(“input.txt”) } catch { case ex: FileNotFoundException =>{ println(“Missing file exception”) } case ex: IOException => { println(“IO Exception”) } } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Missing file exception The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn. The finally Clause You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates. Try the following program. Example import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader(“input.txt”) } catch { case ex: FileNotFoundException => { println(“Missing file exception”) } case ex: IOException => { println(“IO Exception”) } } finally { println(“Exiting finally…”) } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Missing file exception Exiting finally… Print Page Previous Next Advertisements ”;

Scala – Discussion

Discuss Scala ”; Previous Next Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates the features of object-oriented and functional languages. This tutorial explains the basics of Scala in a simple and reader-friendly way. Print Page Previous Next Advertisements ”;

Rust – Array

Rust – Array ”; Previous Next In this chapter, we will learn about an array and the various features associated with it. Before we learn about arrays, let us see how an array is different from a variable. Variables have the following limitations − Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. An array is a homogeneous collection of values. Simply put, an array is a collection of values of the same data type. Features of an Array The features of an array are as listed below − An array declaration allocates sequential memory blocks. Arrays are static. This means that an array once initialized cannot be resized. Each memory block represents an array element. Array elements are identified by a unique integer called the subscript/ index of the element. Populating the array elements is known as array initialization. Array element values can be updated or modified but cannot be deleted. Declaring and Initializing Arrays Use the syntax given below to declare and initialize an array in Rust. Syntax //Syntax1 let variable_name = [value1,value2,value3]; //Syntax2 let variable_name:[dataType;size] = [value1,value2,value3]; //Syntax3 let variable_name:[dataType;size] = [default_value_for_elements,size]; In the first syntax, type of the array is inferred from the data type of the array’s first element during initialization. Illustration: Simple Array The following example explicitly specifies the size and the data type of the array. The {:?} syntax of the println!() function is used to print all values in the array. The len() function is used to compute the size of the array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [10, 20, 30, 40] array size is :4 Illustration: Array without data type The following program declares an array of 4 elements. The datatype is not explicitly specified during the variable declaration. In this case, the array will be of type integer. The len() function is used to compute the size of the array. fn main(){ let arr = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [10, 20, 30, 40] array size is :4 Illustration: Default values The following example creates an array and initializes all its elements with a default value of -1. fn main() { let arr:[i32;4] = [-1;4]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [-1, -1, -1, -1] array size is :4 Illustration: Array with for loop The following example iterates through an array and prints the indexes and their corresponding values. The loop retrieves values from index 0 to 4 (index of the last array element). fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); for index in 0..4 { println!(“index is: {} & value is : {}”,index,arr[index]); } } Output array is [10, 20, 30, 40] array size is :4 index is: 0 & value is : 10 index is: 1 & value is : 20 index is: 2 & value is : 30 index is: 3 & value is : 40 Illustration: Using the iter() function The iter() function fetches values of all elements in an array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); for val in arr.iter(){ println!(“value is :{}”,val); } } Output array is [10, 20, 30, 40] array size is :4 value is :10 value is :20 value is :30 value is :40 Illustration: Mutable array The mut keyword can be used to declare a mutable array. The following example declares a mutable array and modifies value of the second array element. fn main(){ let mut arr:[i32;4] = [10,20,30,40]; arr[1] = 0; println!(“{:?}”,arr); } Output [10, 0, 30, 40] Passing Arrays as Parameters to Functions An array can be passed by value or by reference to functions. Illustration: Pass by value fn main() { let arr = [10,20,30]; update(arr); print!(“Inside main {:?}”,arr); } fn update(mut arr:[i32;3]){ for i in 0..3 { arr[i] = 0; } println!(“Inside update {:?}”,arr); } Output Inside update [0, 0, 0] Inside main [10, 20, 30] Illustration: Pass by reference fn main() { let mut arr = [10,20,30]; update(&mut arr); print!(“Inside main {:?}”,arr); } fn update(arr:&mut [i32;3]){ for i in 0..3 { arr[i] = 0; } println!(“Inside update {:?}”,arr); } Output Inside update [0, 0, 0] Inside main [0, 0, 0] Array Declaration and Constants Let us consider an example given below to understand array declaration and constants. fn main() { let N: usize = 20; let arr = [0; N]; //Error: non-constant used with constant print!(“{}”,arr[10]) } The compiler will result in an exception. This is because an array”s length must be known at compile time. Here, the value of the variable “N” will be determined at runtime. In other words, variables cannot be used to define the size of an array. However, the following program is valid − fn main() { const N: usize = 20; // pointer sized let arr = [0; N]; print!(“{}”,arr[10]) } The value of an identifier prefixed with the const keyword is defined at compile time and cannot be changed at runtime. usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for. Print Page Previous Next Advertisements ”;

Scala – Traits

Scala – Traits ”; Previous Next A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits. Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait. Syntax trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = !isEqual(x) } This trait consists of two methods isEqual and isNotEqual. Here, we have not given any implementation for isEqual where as another method has its implementation. Child classes extending a trait can give implementation for the un-implemented methods. So a trait is very similar to what we have abstract classes in Java. Let us assume an example of trait Equal contain two methods isEqual() and isNotEqual(). The trait Equal contain one implemented method that is isEqual() so when user defined class Point extends the trait Equal, implementation to isEqual() method in Point class should be provided. Here it is required to know two important method of Scala, which are used in the following example. obj.isInstanceOf [Point] To check Type of obj and Point are same are not. obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type. Try the following example program to implement traits. Example trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = !isEqual(x) } class Point(xc: Int, yc: Int) extends Equal { var x: Int = xc var y: Int = yc def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y } object Demo { def main(args: Array[String]) { val p1 = new Point(2, 3) val p2 = new Point(2, 4) val p3 = new Point(3, 3) println(p1.isNotEqual(p2)) println(p1.isNotEqual(p3)) println(p1.isNotEqual(2)) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output true false true Value classes and Universal Traits Value classes are new mechanism in Scala to avoid allocating runtime objects. It contains a primary constructor with exactly one val parameter. It contains only methods (def) not allowed var, val, nested classes, traits, or objects. Value class cannot be extended by another class. This can be possible by extending your value class with AnyVal. The typesafety of custom datatypes without the runtime overhead. Let us take an examples of value classes Weight, Height, Email, Age, etc. For all these examples it is not required to allocate memory in the application. A value class not allowed to extend traits. To permit value classes to extend traits, universal traits are introduced which extends for Any. Example trait Printable extends Any { def print(): Unit = println(this) } class Wrapper(val underlying: Int) extends AnyVal with Printable object Demo { def main(args: Array[String]) { val w = new Wrapper(3) w.print() // actually requires instantiating a Wrapper instance } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output It will give you the hash code of Wrapper class. Wrapper@13 When to Use Traits? There is no firm rule, but here are few guidelines to consider − If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all. If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy. If you want to inherit from it in Java code, use an abstract class. If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class. If efficiency is very important, lean towards using a class. Print Page Previous Next Advertisements ”;

Scala – Strings

Scala – Strings ”; Previous Next This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class. Creating a String The following code can be used to create a String − var greeting = “Hello world!”; or var greeting:String = “Hello world!”; Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above. Try the following example program. Example object Demo { val greeting: String = “Hello, world!” def main(args: Array[String]) { println( greeting ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Hello, world! As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object. Use the following code segment to find the length of a string − Example object Demo { def main(args: Array[String]) { var palindrome = “Dot saw I was Tod”; var len = palindrome.length(); println( “String Length is : ” + len ); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output String Length is : 17 Concatenating Strings The String class includes a method for concatenating two strings − string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in − “My name is “.concat(“Zara”); Strings are more commonly concatenated with the + operator, as in − “Hello,” + ” world” + “!” Which results in − “Hello, world!” The following lines of code to find string length. Example object Demo { def main(args: Array[String]) { var str1 = “Dot saw I was “; var str2 = “Tod”; println(“Dot ” + str1 + str2); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Dot Dot saw I was Tod Creating Format Strings You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Try the following example program, which makes use of printf() method − Example object Demo { def main(args: Array[String]) { var floatVar = 12.456 var intVar = 2000 var stringVar = “Hello, Scala!” var fs = printf(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string” + “is %s”, floatVar, intVar, stringVar); println(fs) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. command >scalac Demo.scala >scala Demo Output The value of the float variable is 12.456000, while the value of the integer variable is 2000, and the string is Hello, Scala!() String Interpolation String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal. There are three types (interpolators) of implementations in String Interpolation. The ‘s’ String Interpolator The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator. The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement. val name = “James” println(s “Hello, $name”) //output: Hello, James String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’. println(s “1 + 1 = ${1 + 1}”) //output: 1 + 1 = 2 Try the following example program of implementing ‘s’ interpolator. Example object Demo { def main(args: Array[String]) { val name = “James” println(s”Hello, $name”) println(s”1 + 1 = ${1 + 1}”) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Hello, James 1 + 1 = 2 The ‘ f ’ Interpolator The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc. Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90. val height = 1.9d val name = “James” println(f”$name%s is $height%2.2f meters tall”) //James is 1.90 meters tall It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is

Prolog – Home

Prolog Tutorial PDF Version Quick Guide Resources Job Search Discussion Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major example of the fourth generation language that supports the declarative programming paradigm. This is particularly suitable for programs that involve symbolic or non-numeric computation. Audience This reference has been prepared for the beginners to help them understand the basics of prolog. Prerequisites For this tutorial, it is assumed that the reader has a prior knowledge in coding. Print Page Previous Next Advertisements ”;

Rust – Functions

Rust – Functions ”; Previous Next Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. Sr.No Function & Description 1 Defining a function A function definition specifies what and how a specific task would be done. 2 Calling or invoking a Function A function must be called so as to execute it. 3 Returning Functions Functions may also return value along with control, back to the caller. 4 Parameterized Function Parameters are a mechanism to pass values to functions. Defining a Function A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below Syntax fn function_name(param1,param2..paramN) { // function body } A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions. Example – Simple function definition //Defining a function fn fn_hello(){ println!(“hello from function fn_hello “); } Invoking a Function A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function. Syntax function_name(val1,val2,valN) Example: Invoking a Function fn main(){ //calling a function fn_hello(); } Here, the main() is the caller function. Illustration The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function. fn main(){ //calling a function fn_hello(); } //Defining a function fn fn_hello(){ println!(“hello from function fn_hello “); } Output hello from function fn_hello Returning Value from a Function Functions may also return a value along with control, back to the caller. Such functions are called returning functions. Syntax Either of the following syntax can be used to define a function with return type. With return statement // Syntax1 fn function_name() -> return_type { //statements return value; } Shorthand syntax without return statement //Syntax2 fn function_name() -> return_type { value //no semicolon means this value is returned } lllustration fn main(){ println!(“pi value is {}”,get_pi()); } fn get_pi()->f64 { 22.0/7.0 } Output pi value is 3.142857142857143 Function with Parameters Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Parameters can be passed to a function using one of the following techniques − Pass by Value When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument. The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same. fn main(){ let no:i32 = 5; mutate_no_to_zero(no); println!(“The value of no is:{}”,no); } fn mutate_no_to_zero(mut param_no: i32) { param_no = param_no*0; println!(“param_no value is :{}”,param_no); } Output param_no value is :0 The value of no is:5 Pass by Reference When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero. fn main() { let mut no:i32 = 5; mutate_no_to_zero(&mut no); println!(“The value of no is:{}”,no); } fn mutate_no_to_zero(param_no:&mut i32){ *param_no = 0; //de reference } The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing. The output will be − The value of no is 0. Passing string to a function The main() function passes a string object to the display() function. fn main(){ let name:String = String::from(“TutorialsPoint”); display(name); //cannot access name after display } fn display(param_name:String){ println!(“param_name value is :{}”,param_name); } Output param_name value is :TutorialsPoint Print Page Previous Next Advertisements ”;

Scala – Arrays

Scala – Arrays ”; Previous Next Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one. Declaring Array Variables To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference. The following is the syntax for declaring an array variable. Syntax var z:Array[String] = new Array[String](3) or var z = new Array[String](3) Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following − Command z(0) = “Zara”; z(1) = “Nuha”; z(4/2) = “Ayan” Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array − var z = Array(“Zara”, “Nuha”, “Ayan”) Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9. Processing Arrays When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known. Below is an example program of showing how to create, initialize and process arrays − Example object Demo { def main(args: Array[String]) { var myList = Array(1.9, 2.9, 3.4, 3.5) // Print all the array elements for ( x <- myList ) { println( x ) } // Summing all elements var total = 0.0; for ( i <- 0 to (myList.length – 1)) { total &plus;= myList(i); } println(“Total is ” + total); // Finding the largest element var max = myList(0); for ( i <- 1 to (myList.length – 1) ) { if (myList(i) > max) max = myList(i); } println(“Max is ” &plus; max); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5 Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package. Multi-Dimensional Arrays There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays. The following is the example of defining a two-dimensional array − var myMatrix = ofDim[Int](3,3) This is an array that has three elements each being an array of integers that has three elements. Try the following example program to process a multi-dimensional array − Example import Array._ object Demo { def main(args: Array[String]) { var myMatrix = ofDim[Int](3,3) // build a matrix for (i <- 0 to 2) { for ( j <- 0 to 2) { myMatrix(i)(j) = j; } } // Print two dimensional array for (i <- 0 to 2) { for ( j <- 0 to 2) { print(” ” &plus; myMatrix(i)(j)); } println(); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 0 1 2 0 1 2 0 1 2 Concatenate Arrays Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method. Example import Array._ object Demo { def main(args: Array[String]) { var myList1 = Array(1.9, 2.9, 3.4, 3.5) var myList2 = Array(8.9, 7.9, 0.4, 1.5) var myList3 = concat( myList1, myList2) // Print all the array elements for ( x <- myList3 ) { println( x ) } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 1.9 2.9 3.4 3.5 8.9 7.9 0.4 1.5 Create Array with Range Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1. Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18. Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, …, and 19. The following example program shows how to create an array with ranges. Example import Array._ object Demo { def main(args: Array[String]) { var myList1 = range(10, 20, 2) var myList2 = range(10,20) // Print all the array elements for ( x <- myList1 ) { print( ” ” &plus; x ) } println() for ( x <- myList2 ) { print( ” ” &plus; x ) } } } Save the above program in Demo.scala. The following