📅  最后修改于: 2023-12-03 14:50:48.306000             🧑  作者: Mango
This is a question from the ISRO CS 2018 exam. It requires you to write a program that finds the largest and smallest elements in an array of integers.
You are given an array of integers. Your task is to write a program to find the smallest and largest elements in the array.
The input consists of two lines:
n
(1 ≤ n ≤ 100), the number of elements in the array.n
space-separated integers a1, a2, ..., an (-10^3 ≤ ai ≤ 10^3).Your program should output two lines:
Input:
5
3 -2 7 0 -1
Output:
-2
7
The solution to this problem is straightforward. We can iterate through the array and keep track of the smallest and largest elements. Here is the Python code for this:
n = int(input())
a = list(map(int, input().split()))
# initialize the smallest and largest elements to be the first element of the array
min_element = a[0]
max_element = a[0]
# iterate through the rest of the array and update the smallest and largest elements
for x in a[1:]:
if x < min_element:
min_element = x
if x > max_element:
max_element = x
# output the smallest and largest elements
print(min_element)
print(max_element)
This program starts by reading the input and storing the elements in a list. It then initializes the smallest and largest elements to be the first element in the list. Then, it iterates over the rest of the list, updating the smallest and largest elements as it goes. Finally, it outputs the smallest and largest elements. This program runs in O(n) time, where n is the number of elements in the array.