C Program to Print Last Two Digits of a Number

Write a C program to print last two digits of a number.

For example,

Input
123456
Output
56

We can easily find the last two digit of a number using modules 100.

  1. Let N be the input.
  2. If N is a one-digit number, simply print N and terminate the program.
  3. Let temp = N % 100.
  4. If temp is greater than 9, simply print temp.
  5. If temp is less than or equal to 9, then it implies that the second last digit of N is 0. First print 0 and then print temp.
#include <stdio.h>

// function to print last 2 digits of n
int print_last_two_digits(int n) {

	int temp;
	printf("Last two digit of %d: ", n);

	if (n <= 9)
		// if n is one digit number, print n
		printf("%d", n);
	else {

		temp = n % 100;
		if (temp <= 9) {

			// if temp is less than equal to 9
			// then the second last digit of n must be 0
			// we first print 0 and then print temp
			printf("0%d", temp);

		}
		else {

			printf("%d", temp);

		}

	}

}

int main() {

	int n;
	printf("Enter a Number: ");
	scanf("%d", &n);
	print_last_two_digits(n);

}

Output

Enter a Number: 123408
Last two digit of 123408: 08

We can solve this problem in another way. We will first convert the number to a string using itoa() and then print the last two characters of the string.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// function to print last 2 digits of n
int print_last_two_digits(int n) {

	char buffer[65];	// buffer to store string
	int len;
	printf("Last two digit of %d: ", n);
	if (n <= 9) {
		printf("%d", n);
	}
	else {
		itoa(n, buffer, 10);	// convert n to string and store it in buffer[]
		len = strlen(buffer);	// length of buffer
		printf("%c%c", buffer[len - 2], buffer[len - 1]);	// printing last two characters of the buffer[]
	}

}

int main() {

	int n;
	printf("Enter a Number: ");
	scanf("%d", &n);
	print_last_two_digits(n);

}

Output

Enter a Number: 5434211
Last two digit of 5434211: 11

Read

Leave a Comment

Your email address will not be published. Required fields are marked *