I'm trying to print the first digit of a number but the output is zero every time

Viewed 51

I'm trying to print the first digit of the inputted number, but the output comes out as zero. Why is this not working?

#include <iostream>
#include <math.h>
using namespace std;

int main(void){
    int n;
    int count = 0;
    cout<<"enter the number: ";
    cin>>n;
    while(n!=0){
        n=n/10;
        count=count + 1;
    }
    cout<<"number of digits in your number are: "<<count<<endl;
    int z = pow(10, count-1);
    int first = n/z;
    cout<<"the first digit of your number is: "<<first<<endl;
    return 0;
}
1 Answers

When your while loop ends, the value of the variable 'n' becomes zero (the reason why the while loop ends in the first place). For the calculation outside the while loop to be correct, the value of the variable 'n' needs to remain unchanged, which is why you'll have to store it inside a temporary variable.

Before the while loop begins:

int Temporary=n;

Afterward:

int first=Temporary/z;

Output:

enter the number: 345
number of digits in your number are: 3
the first digit of your number is: 3
Related