Advertisement

C Program to find the second largest digit of a number


In this program, You will learn how to find the second largest digit of a number in c


1234 => Second largest digit is: 3

Example: How to find the second largest digit of a number in c

#include<stdio.h>
int main() {

   int n, num, rev=0;
   int r, l = 0, sl = 0;

   printf("Enter a number:");
   scanf("%d", &n);

   while (n > 0) {
       r = n % 10;
       if (l < r) {
           l = r;
       }

       rev = rev * 10 + r;
       n = n / 10;
   }
   printf("First largest digit:%d", l);

   n = rev;
   while (n > 0) {
       r = n % 10;
       if (l != r) {
           if (sl < r) {
               sl = r;
           }
       }
       n = n / 10;
   }
   printf("\nSecond largest digit:%d", sl);

   return 0;
}

Output:

Enter a number:23586
First largest digit:8
Second largest digit:6