Computer Applications

Define a class to overload the method format as follows: void format(): To print the following pattern using Nested for loops only. 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5 int format(String s): To calculate and return the sum of ASCII codes of each character of the String. Example: CAB Output: 67 + 65 + 66 198 void format(int n): To calculate and display the sum of natural numbers up to n given by the formula.

Java

User Defined Methods

2 Likes

Answer

import java.util.Scanner;

class OverloadFormat
{
    public void format()
    {
        int i, j;
        for(i = 1; i <= 5; i++)
        {
            for(j = i; j <= 5; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }

    public int format(String s)
    {
        int i, sum = 0;
        for(i = 0; i < s.length(); i++)
        {
            sum += (int)s.charAt(i);
        }
        return sum;
    }

    public void format(int n)
    {
        int sum;
        sum = n * (n + 1) / 2;
        System.out.println("Sum = " + sum);
    }

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

        obj.format();

        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        int result = obj.format(str);
        System.out.println("Sum of ASCII = " + result);

        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        obj.format(num);
    }
}

Output

Answered By

1 Like


Related Questions