C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Q. Program to print the number of elements present in an array.ExplanationIn this program, we need to count and print the number of elements present in the array. A number of elements present in the array can be found by calculating the length of the array. Length of above array is 5. Hence, the number of elements present in the array is 5. Algorithm
SolutionPythonArrays in Python is declared as ArrayName = [ele1, ele2,...]; len() method returns the length of the array in Python. #Initialize array arr = [1, 2, 3, 4, 5]; #Number of elements present in an array can be found using len() print("Number of elements present in given array: " + str(len(arr))); Output: Number of elements present in given array: 5 CArrays in C are declared as datatype arrayName [size] = {element1, element2,..}; "sizeof" operator gives the size of the array in bytes so, to get the length of the array we divide the size of the array with the size of the first element. #include <stdio.h> int main() { //Initialize array int arr[] = {1, 2, 3, 4, 5}; //Number of elements present in an array can be calculated as follows int length = sizeof(arr)/sizeof(arr[0]); printf("Number of elements present in given array: %d", length); return 0; } Output: Number of elements present in given array: 5 JAVAArrays in Java are created using a new keyword as datatype [] arrayName = new datatype[] {ele1, ele2,...}; length property is used to calculate the length of the array. public class CountArray { public static void main(String[] args) { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; //Number of elements present in an array can be found using the length System.out.println("Number of elements present in given array: " + arr.length); } } Output: Number of elements present in given array: 5 C#Arrays in C# are created using new keyword as datatype [] arrayName = new datatype[] {ele1, ele2,...}; Array. Length property is used to calculate the length of the array. using System; public class CountArray { public static void Main() { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; //Number of elements present in an array can be found using Length Console.WriteLine("Number of elements present in given array: " + arr.Length); } } Output: Number of elements present in given array: 5 PHPArrays in PHP are declared using Array (): $arrayName = Array (element1, element2,..); count () is in-built function in PHP to get the length of array. <!DOCTYPE html> <html> <body> <?php //Initialize array $arr = array(1, 2, 3, 4, 5); //Number of elements present in an array can be found using count() print("Number of elements present in given array: " . count($arr)); ?> </body> </html> Output: Number of elements present in given array: 5
Next Topic#
|