C Program to Find First Digit Of a Number

How to write a C Program to Find First Digit Of a Number with an example?.

C Program to Find First Digit Of a Number

This program will allow the user to enter any number. And then, it is going to find the First Digit of the user entered value.

/* C Program to Find First Digit Of a Number */
 
#include <stdio.h>
#include <math.h>
 
int main()
{
  	int Number, FirstDigit, Count;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	Count = log10(Number);
  	
  	FirstDigit = Number / pow(10, Count);
  
  	printf(" \n Total Number of Digit in a Given Number %d =  %d", Number, Count);
	printf(" \n The First Digit of a Given Number %d =  %d", Number, FirstDigit);
 
  	return 0;
}
C Program to Find First Digit Of a Number 1

Within this C Program to Find First Digit Of a Number, User entered Value : Number = 1234

Count = log10(Number) – This will return the total number of digits in a Number -1
Count = 3

FirstDigit = 1234 / pow(10, 3) = 1234 / 1000 = 1.234 = 1

C Program to return First Digit Of a Number

This program will use the While Loop to find the First Digit of the user entered value.

/* C Program to Find First Digit Of a Number */
 
#include <stdio.h>
 
int main()
{
  	int Number, FirstDigit;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	FirstDigit = Number;
  	
  	while(FirstDigit >= 10)
  	{
  		FirstDigit = FirstDigit / 10;
	}
  
	printf(" \n The First Digit of a Given Number %d =  %d", Number, FirstDigit);
 
  	return 0;
}
 Please Enter any Number that you wish  : 354
 
 The First Digit of a Given Number 354 =  3

Within this Program to Find First Digit Of a Number, Number = 354

While Loop First Iteration while (354 >= 10)
FirstDigit = FirstDigit / 10 = 354 / 10 = 35

While Loop Second Iteration while (35 >= 10)
FirstDigit = FirstDigit / 10 = 35 / 10 = 3

While Loop Third Iteration while (3 >= 10)
Condition is False so, the C Programming compiler will exit from the While Loop and prints 3 as output

Program to Find First Digit Of a Number using Function

This C program to display First Digit Of a Number is the same as above. However, this time, we divided the code using Functions concept.

#include <stdio.h>
#include <math.h>

int First_Digit(int num);
 
int main()
{
  	int Number, FirstDigit;
 
  	printf("\n Please Enter any Number that you wish  : ");
  	scanf("%d", & Number);
  	
  	FirstDigit = First_Digit(Number);
  	
	printf(" \n The First Digit of a Given Number %d =  %d", Number, FirstDigit);
 
  	return 0;
}

int First_Digit(int num)
{
	while(num >= 10)
	{
		num = num / 10;
	}
	return num;
}
 Please Enter any Number that you wish  : 657489
 
 The First Digit of a Given Number 657489 =  6