Tuesday, 12 April 2016

C And C++ Program to find first and last digit of any number Problem Solution.


C Solution:

#include <stdio.h>
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    long long num, firstDigit, lastDigit, digits,div = 1,tmp;

    /// Reads number from user
    printf("Enter any number: ");
    scanf("%lld", &num);

    lastDigit = num % 10; ///Gets last digit
    tmp = num;
    int CHECK = 1;
    while(tmp > 0){
        if(CHECK){
            div = 1;
            CHECK = 0;
        }
        else div *= 10;
        tmp /= 10;
    }
    firstDigit = num / div; /// Gets first digit

    printf("First digit = %lld\n", firstDigit);
    printf("Last digit = %lld\n", lastDigit);

    return 0;
}

C++ Solution:

#include <iostream>
using namespace std;
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    long long num, firstDigit, lastDigit, digits,div = 1,tmp;

    /// Reads number from user
    cout << "Enter any number: ";
    cin >> num;

    lastDigit = num % 10; ///Gets last digit
    tmp = num;
    bool CHECK = true;
    while(tmp > 0){
        if(CHECK){
            div = 1;
            CHECK = false;
        }
        else div *= 10;
        tmp /= 10;
    }
    firstDigit = num / div; /// Gets first digit

    cout << "First digit = " << firstDigit << endl;;
    cout << "Last digit = " << lastDigit << endl;;

    return 0;
}

No comments:

Post a Comment