मराठी

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

प्रश्न

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.
कोड लेखन
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 4: Constructors - Exercises [पृष्ठ ११५]

APPEARS IN

रूपा पंडित Computer Applications [English] Class 10 ICSE
पाठ 4 Constructors
Exercises | Q 4. (b) | पृष्ठ ११५
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×