How to get the first digit of int number in C

3 Answers

0 votes
#include <stdio.h> 
     
int main() 
{ 
	int n = 7289, first_digit = n;

    while(first_digit >= 10) {
        first_digit = first_digit / 10;
    }

    printf("%d", first_digit);
       
    return 0; 
} 
     
     
     
/*
run:
     
7
   
*/

 



answered Aug 24, 2019 by avibootz
0 votes
#include <stdio.h>
#include <math.h>
 
int main(void) {
    int n = 8405961;
    printf("n: %d\n", n);
 
    int totaldigits_minusone = (int)log10(n); 
  
    int firstdigit = (int)(n / pow(10, totaldigits_minusone));
     
    printf("firstdigit: %d\n", firstdigit);
     
    return 0;
}
 
 
 
   
/*
run:
   
n: 8405961
firstdigit: 8
  
*/

 



answered Jan 10, 2024 by avibootz
0 votes
#include <stdio.h>
#include <math.h>

int get_first_digit_left(int num) {
    int total = (int)log10(num); // total - 1 = 3

    return num / pow(10, (total));
}
 
int main(void) {
    int num = 7483;

    printf("%d", get_first_digit_left(num));
    
    return 0;
}
 
 
 
 
/*
run:
     
7
     
*/

 



answered Jan 10, 2024 by avibootz

Related questions

2 answers 283 views
2 answers 192 views
192 views asked May 29, 2020 by avibootz
1 answer 161 views
1 answer 173 views
1 answer 119 views
1 answer 184 views
184 views asked Aug 24, 2019 by avibootz
2 answers 159 views
...