Swift Program to Count the elements of an Array


In this article, we will learn how to write a swift program to count the elements of an array. To count the elements of an array swift provide a count property. This property will return the total number of elements present in the specified array. For example 

  • Arr = [3, 5, 6, 4, 6] so the count will return 5.

Syntax

var count: Int{get}

Or you can also write it as −

arrayName.count

Here count is the property of the array to count the total elements present inside the array. To use this property we use the dot operator in between the array name and the property name.

Algorithm

  • Step 1 − Create an array of any data type.

  • Step 2 − Count the elements of the array using the count property and store the result in another variable.

var res1Array = IntArray.count
  • Step 3 − Print the output

Example

import Foundation
import Glibc
 
// Creating an array of integer type
var IntArray : [Int] = [34, 56, 23, 55, 78, 12]

// Creating an array of string type 
var StringArray : [String] = ["Cow", "Bird", "Monkey", "Cat"]

// Counting the elements of the array
// Using count property
var res1Array = IntArray.count
var res2Array = StringArray.count

print("Integer Array:", IntArray)
print("Total number of elements:", res1Array)
print("\nString Array:", StringArray)
print("Total number of elements:", res2Array)

Output

Integer Array: [34, 56, 23, 55, 78, 12]
Total number of elements: 6

String Array: ["Cow", "Bird", "Monkey", "Cat"]
Total number of elements: 4

Here in the above code, we create two different types(that is Int and String) of arrays and then count their elements using the count property and display the final result.

Conclusion

So, this is how we can count the total number of elements present in the array with the help of the count property.

Updated on: 20-Dec-2022

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements