Read any 3 digit number from user and display sum of first and last digit of the same
Answers
Answer:
In c language:
#include <stdio.h>
int main()
{
int num, sum=0, firstDigit, lastDigit;
/* Input a number from user */
printf("Enter any number to find sum of first and last digit: ");
scanf("%d", &num);
/* Find last digit to sum */
lastDigit = num % 10;
/* Copy num to first digit */
firstDigit = num;
/* Find the first digit by dividing num by 10 until first digit is left */
while(num >= 10)
{
num = num / 10;
}
firstDigit = num;
/* Find sum of first and last digit*/
sum = firstDigit + lastDigit;
printf("Sum of first and last digit = %d", sum);
return 0;
}
In java:
import java.util.Scanner;
public class SumOfFirstAndLastDigitProgram {
// method to find sum of first and last digit
private static int FirstLastDigitSum(int number) {
// declare variables
int lastDigit, firstDigit, divisor;;
int totalDigits = 0;
int sum = 0;
// find last digit
lastDigit = number%10;
// find total number of digits
totalDigits = findDigits(number);
// calculate divisor value
divisor = (int)Math.pow(10, totalDigits-1);
// find first digit
firstDigit = number / divisor;
// add values
sum = firstDigit + lastDigit;
return sum;
}
// method to find total number of digits
private static int findDigits(int number) {
int count = 0;
while(number!=0) {
count++;
number = number/10;
}
return count;
}
public static void main(String[] args) {
// declare variables
int number = 0;
int sum = 0;
// create Scanner class object
// for reading the values
Scanner scan = new Scanner(System.in);
// read input
System.out.print("Enter an integer number:: ");
number = scan.nextInt();
// find sum of digits of number
sum = FirstLastDigitSum(number);
// display result
System.out.println("The sum of first & last"
+" digit of the number "+number
+" = "+ sum);
// close Scanner class object
scan.close();
}
}
Explanation:
Input a number from user. Store it in some variable say num.
To find last digit of given number we modulo divide the given number by 10. Which is lastDigit = num % 10.
To find first digit we divide the given number by 10 till num is greater than 0.
Finally calculate sum of first and last digit i.e. sum = firstDigit + lastDigit.