How to Write a Program to Enter 5 Integer Numbers in an Array and Display Them in Python and Java

How to Write a Program to Enter 5 Integer Numbers in an Array and Display Them in Python and Java

Introduction

This article provides a step-by-step guide to writing a simple program in both Python and Java that allows you to enter 5 integer numbers into an array and then displays those numbers. This is a common exercise for beginners in programming and a great way to practice basic syntax and logic.

Python Implementation

Python is a widely used high-level programming language known for its simplicity and readability. Below is a simple Python program to achieve the goal of entering 5 integer numbers and displaying them.

highlight-py# Initialize an empty list to store the numbersnumbers  []# Loop to get 5 integer inputs from the userfor i in range(5):    while True:        try:            # Prompt the user for an integer            num  int(input("Enter an integer: "))            (num)  # Add the number to the list            break        except ValueError:            print("Invalid input. Please enter an integer.")# Display the numbersprint("Numbers entered: ")for number in numbers:    print(number)/highlight-py

How it Works

The Python program follows these steps:

Create an empty list called numbers to store the integers. Use a loop that runs 5 times to prompt the user for input. Check if the input is a valid integer using a try-except block. Add the valid input to the list. Print out the numbers stored in the list once all 5 inputs are collected.

You can run this code in any Python environment. If you run into any issues or need further assistance, feel free to ask.

Java Implementation

Java is another popular programming language that is known for its versatility and robustness. Here is the equivalent Java program to achieve the same task.

highlight-javaimport ;public class InputDisplay {    public static void main(String[] args) {        Scanner sc  new Scanner();        int[] arr  new int[5];        for (int i  0; i 

How it Works

The Java program follows these steps:

Import the necessary class for reading input. Create an empty array called arr with a fixed size of 5 to store the integers. Use a loop that runs 5 times to prompt the user for input. Check if the input is a valid integer using a try-catch block. Add the valid input to the array. Print out the numbers stored in the array once all 5 inputs are collected.

Ensure to run this program in a suitable Java environment. If you need further assistance, reach out for help!

Conclusion

The goal of homework is to help you understand and apply what you've learned. Try to revisit your textbook and class notes to solidify your understanding. Practice is key to mastering programming concepts. If you need more help, don't hesitate to ask.

If you're struggling or just need some guidance, let me know! I’m here to help you learn and improve.