C Program to Find Second Last Digit of a Number

Write a C program to find the second last digit of a number.

For example,

Input
123456
Output
5

Steps

  1. Let N be the input number.
  2. If N is a one-digit number, return -1.
  3. Set N = N / 10. This step removes the last digit of N.
  4. N % 10 gives us the last digit of N. Since we have already removed the last digit of N in the previous step, N % 10 is equal to the second last digit of the input number.
  5. Return N % 10.
#include <stdio.h>

// function to return second last digit of N
int second_last_digit(int N) {

	// remove last digit of N
	N = N / 10;
	
	// N % 10 gives the last digit of N
	// since we have already removed last digit of N
	// therefore, N % 10 gives us the second last digit of N
	return N % 10;

}

int main() {

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

	printf("Second Last Digit of %d = %d", N,  second_last_digit(N));

}

Output

Enter a Number: 1234567
Second Last Digit of 1234567 = 6

The problem you just solved was very simple. It won’t be enough to crack rounds of many companies. We recommend you to visit Coding Ninjas and check out their courses. You will learn about all the important algorithms and data structures from industry experts that will help you a lot in cracking coding interviews.

Read

Leave a Comment

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