Pages

Thursday, January 5, 2023

ICSE Java Programming Array of Numbers 2022 Q4 SPECIMEN PAPER Solved

ICSE Java Programming Array of Numbers 2022 Q4 SPECIMEN PAPER Solved

Question 4

Define a class to declare an array of size 20 of double datatype, accept the elements into the array and perform the following:

Calculate and print the sum of all the elements.

Calculate and print the highest value of the array.



Python Code (Without using class)

_array = []
array_size = 20
max_element = 0.0
sum = 0.0
print("Enter the elements in the array:")
for i in range(array_size):
    print("Enter the element at the position:",(i+1))
    _array.append(float(input()))
    sum += _array[i]
    if max_element < _array[i]:
        max_element = _array[i]
print("Sum of all the elements is ",sum)
print("Maximum element in the array ",max_element)

JAVA CODE

import java.util.Scanner;

public class ICSEJava {
    public static void main(String[] args) {
        Array obj = new Array();
        obj.inputArray();
        obj.sumOfElements();
        obj.maxElement();
    }
}

class Array {
    public void inputArray() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < this.array_size; i++) {
            System.out.println("Enter the element:");
            this.array[i] = in.nextDouble();
        }
        in.close();
    }

    public void maxElement() {
        for (int i = 0; i < this.array_size; i++)
            if (this.max_element < this.array[i])
                this.max_element = this.array[i];
        System.out.println("Maximum element in the array " + this.max_element);
    }

    public void sumOfElements() {
        for (int i = 0; i < this.array_size; i++)
            this.sum += this.array[i];
        System.out.println("Sum of all the elements is " + this.sum);
    }

    Array() {
        this.sum = 0;
        this.max_element = 0;
    }

    private double[] array = new double[20];
    private double sum;
    private double max_element;
    private static int array_size = 20;
}

No comments:

Post a Comment