Swift program to create a two-dimensional array

Here, we are going to learn how to create a two-dimensional array in Swift programming language?
Submitted by Nidhi, on June 18, 2021

Problem Solution:

Here, we will create a two-dimensional array using the subscript operator and print created 2D array on the console screen.

Program/Source Code:

The source code to create a two-dimensional array is given below. The given program is compiled and executed successfully.

// Swift program to create a two-dimensional array

import Swift

let twoArr: [[Int]] = [[1,3,5,7], [2,4,6,8]]

// print first row
print("First Row:")
print(twoArr[0][0])
print(twoArr[0][1])
print(twoArr[0][2])
print(twoArr[0][3])

// print second row
print("Second Row:")
print(twoArr[1][0])
print(twoArr[1][1])
print(twoArr[1][2])
print(twoArr[1][3])

Output:

First Row:
1
3
5
7
Second Row:
2
4
6
8

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created a 2D array of integers twoArr. The twoArr array contains 2 rows, each row contains 4 items. After that, we accessed and printed both rows on the console screen.

Swift Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.