English

Write a program for the following. Define a class Numeral, described as below: Data Members: num (int) Member Methods: (i) Numeral() constructor to initialize member data to null.

Advertisements
Advertisements

Question

Write a program for the following.

Define a class Numeral, described as below:

Data Members:
num (int)
Member Methods:
(i) Numeral() constructor to initialize member data to null.
(ii) Numeral() to accept a value for the member data from the user.
(iii) Numeral() to calculate and return the value of summation of num where-
(Summation of num) = 1+2+3+ ... + num
(iv) int SumDigit() to calculate and return the sum of the digits of num.
(v) Display() To display the member data and also to invoke member methods Summation() and SumDigit() and print their return values.
Write a main() method to create an object of the class and call the above member methods.
Code Writing
Advertisements

Solution

import java.util.*;
class Numeral
{
    int num;
    //Constructor
    Numeral()
    {
        num = 0;
    }
    //Input method
    void Input()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = sc.nextInt();
    }
    //Summation method
    int Summation()
    {
        int sum = 0;
        for(int i = 1; i <= num; i++)
        {
            sum = sum + i;
        }
        return sum;
    }
    //Sum of digits method
    int SumDigit()
    {
        int n = num, sum = 0;
        while(n > 0)
        {
            sum = sum + (n % 10);
            n = n / 10;
        }
        return sum;
    }
    //Display method
    void Display()
    {
        System.out.println("Number = " + num);
        System.out.println("Summation = " + Summation());
        System.out.println("Sum of Digits = " + SumDigit());
    }
    //Main method
    public static void main(String args[])
    {
        Numeral obj = new Numeral();
        obj.Input();
        obj.Display();
    }
}
shaalaa.com
  Is there an error in this question or solution?
Chapter 4: Constructors - Exercises [Page 115]

APPEARS IN

Rupa Pandit Computer Applications [English] Class 10 ICSE
Chapter 4 Constructors
Exercises | Q 4. (b) | Page 115
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×