Computer Science, asked by aritras831, 8 months ago

Write a program in Java to accept
a 3 digits number using function
argument of main method and find
out the sum of first and last 2 digits
of the number. Display the results
with proper message.
12:04​

Answers

Answered by Prawin2020
0

Explanation:

General Algorithm for sum of digits in a given number:

Get the number

Declare a variable to store the sum and set it to 0

Repeat the next two steps till the number is not 0

Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.

Divide the number by 10 with help of ‘/’ operator

Print or return the sum

Below are the solutions to get sum of the digits.

1. Iterative:

C++

// C program to compute sum of digits in 

// number.

# include<iostream>

using namespace std;

/* Function to get sum of digits */

class gfg

{

    public:

    int getSum(int n)

    { 

    int sum = 0;

    while (n != 0)

    {

     sum = sum + n % 10;

     n = n/10;

    } 

 return sum;

 }

};

//driver code

int main()

{

 gfg g;

 int n = 687;

 cout<< g.getSum(n);

 return 0;

Similar questions