Description: In this problem, the program takes a list as input and calculates its length, i.e., the number of elements present in the list. The length of the list is an important property often required in various tasks, such as iteration or validating input. The program should print the total number of elements in the list, whether the list is empty or contains elements.
// Input: A list of elements
procedure FindLength(list)
length ← 0
for i ← 0 to length of list - 1 do
length ← length + 1
end for
print length
end procedure
def find_length(lst):
length = len(lst)
print(length)
# Example usage
find_length([1, 2, 3, 4, 5])
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class ListLengthFinder {
public static void findLength(List<Integer> list) {
System.out.println(list.size());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("Enter the number of elements: ");
int n = scanner.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++) {
list.add(scanner.nextInt());
}
findLength(list);
}
}
#include <iostream>
#include <vector>
using namespace std;
void findLength(const vector<int>& list) {
cout << list.size() << endl;
}
int main() {
int n, element;
vector<int> list;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> element;
list.push_back(element);
}
findLength(list);
return 0;
}