How to get the first and the last digit of a number in C

2 Answers

0 votes
#include <stdio.h>
 
int main(void) {
	int number = 87354;

	int firstDigit = number;
	while (firstDigit >= 10)  
		firstDigit /= 10; 
	printf("%d\n", firstDigit);
 
	int lastDigit = number % 10;
	printf("%d\n", lastDigit); 
      
	return 0;
}
  
  
  
/*
run:
  
8
4
  
*/

 



answered Jun 3, 2020 by avibootz
edited Jun 8, 2020 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);
     
    int lastdigit = n % 10;
    printf("lastdigit: %d\n", lastdigit);
     
    return 0;
}
 
 
 
   
/*
run:
   
n: 8405961 
firstdigit: 8  
lastdigit: 1 
  
*/

 



answered Jan 15, 2021 by avibootz
edited Jan 15, 2021 by avibootz

Related questions

1 answer 196 views
1 answer 161 views
2 answers 236 views
1 answer 101 views
1 answer 108 views
1 answer 97 views
...