get the first digit of a number in c code example

Example: find sum of first and last digits in java

public class Main {

    public static void main(String[] args) {
        System.out.println(sumFirstAndLastDigit(1221));
        System.out.println(sumFirstAndLastDigit(2342));
        System.out.println(sumFirstAndLastDigit(10));
        System.out.println(sumFirstAndLastDigit(-123));
	// write your code here
    }
    public static int sumFirstAndLastDigit(int number){
        if (number<0){
            return -1;  //checking boundary conditions
        }
        else if(number==0){
            return 0;
        }
        else{
            int lastDigit=number%10; // to extract last significant digit
            while(number>=10){
                number=number/10;
            }
            int firstDigit=number;
            return (lastDigit+firstDigit);
        }
    }

Tags:

Cpp Example