Find sum and product of first and last digit of a number
In this article I am going to discuss, how you can able to write a java program to find the sum and product of first and last digits of a number by doing coding on mobile.
Here I will explain 2 different approaches. And yes I use my mobile to write code for all programs.
Approach:-1 "find sum, product of first and last digit using loop"
public class sumOfFirstAndLastDigit {
public static void main(String[] args) {
int num = 56943;
int sum = num % 10;
int product = num % 10;
int first_digit = num;
while(num >= 10)
{
num = num / 10;
first_digit = num;
}
System.out.println("The sum of first and last digit is: "+(sum + first_digit));
System.out.println("The product of first and last digit is: "+sum * first_digit);
}
}
Here we have to find out the first and last digit of a number, then we can simply find the sum as well as products of these two digits.
If we divide a number with 10, then the remainder will be the last digit. Here we can achieve this by using modulus operator (%).
For first digit, we have to eliminate digits one by one from last side. We can do this by simply dividing the number with 10, here we have to keet the quotient value.
Now simply we can add and multiply the first and last digits.
Output
Approach:-2 "sum, product of first and last digit of a number using java method"
public class usingMethod {
public static void main(String[] args){
System.out.println("========Using simple method concept========");
findSum s = new findSum();
s.calculateSum(2345);
findProduct p = new findProduct();
p.calculateProduct(2345);
}
}
class findSum{
public void calculateSum(int num)
{
int first_digit = num;
int last_digit = num % 10;
while(num >= 10)
{
num = num / 10;
first_digit = num;
}
System.out.println("The sum of first and last digit is: "+(first_digit + last_digit));
}
}
class findProduct{
public void calculateProduct(int num)
{
int first_digit = num;
int last_digit = num % 10;
while(num >= 10)
{
num = num / 10;
first_digit = num;
}
System.out.println("The product of first and last digit is: "+(first_digit * last_digit));
}
}
In this approach, I have use java method concept to find the sum and product of first and last digit of a number.
Here I have declared two separate methods to find sum and product. Inside that the logic is remain same.
See here we can use inheritance concept to reduce code repetition. But for better understanding I use logic for both the method.
Output
➡️ Hey if you learn something new from the article, please share with your friends.
And please ask me in the comment below, if you face any problem or if you have any doubt related to programming. I will definitely solve your query.