Computer Applications

Define a class to overload the method display as follows:

void display(): To print the following format using nested loop

5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5

void display(int n): To check and display if the given number is a Perfect number or not. A number is said to be perfect, if sum of the factors of the number excluding itself is equal to the original number.

E.g.
6 = 1 + 2 + 3, where 1, 2 and 3 are factors of 6 excluding itself.

Java

Java Nested for Loops

17 Likes

Answer

import java.util.Scanner;
public class KboatMethodOverload
{
    public void display()
    {
        for (int i = 0; i < 5; i++) {
            for (int j = 5 - i; j <= 5; j++) {
                System.out.print(j + " ");
            }
            for (int k = 4 - i; k > 0; k--) {
                System.out.print("5 ");
            }
            System.out.println();
        } 
    }

    public void display(int n) {
        int sum = 0;

        for (int i = 1; i <= n / 2; i++) {
            if (n % i == 0) {
                sum += i;
            }
        }

        if (n == sum) 
            System.out.println(n + " is a perfect number");
        else
            System.out.println(n + " is not a perfect number");
    }

    public static void main(String args[]) {
        KboatMethodOverload obj = new KboatMethodOverload();
        Scanner in = new Scanner(System.in);

        System.out.println("Pattern: ");
        obj.display();

        System.out.println();
        
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        obj.display(num);

    }
}

Output

Answered By

7 Likes


Related Questions