📌  相关文章
📜  国际空间研究组织 | ISRO CS 2018 |问题 42(1)

📅  最后修改于: 2023-12-03 14:50:48.306000             🧑  作者: Mango

ISRO CS 2018 - Question 42

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.

Problem Statement

You are given an array of integers. Your task is to write a program to find the smallest and largest elements in the array.

Input

The input consists of two lines:

  • The first line contains an integer n (1 ≤ n ≤ 100), the number of elements in the array.
  • The second line contains n space-separated integers a1, a2, ..., an (-10^3 ≤ ai ≤ 10^3).
Output

Your program should output two lines:

  • The first line should contain the smallest element in the array.
  • The second line should contain the largest element in the array.
Example

Input:

5
3 -2 7 0 -1

Output:

-2
7
Solution

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.