Search This Blog

C Program to Find Largest Positive Number Formed Using Digits of Given Number

Here i post a c program to find the largest positive number (integer) that can be formed using the digits of a given number (positive integer). The program just splits the number into digits and stores in an array. Then we sort the digits in descending order so that the largest integer comes first. Then we find the largest number by placing the last digit in the array in one's place, the second last in ten's place, and so on. This is a programming round question asked by Zoho company. You may expect this question for technical interviews to test your basic programming skill. The program is as follows:
#include <stdio.h>
int main(void) {
int n,a[30],i,j,t,c;
printf("Enter the number\n");
scanf("%d",&n);
for(i=0,t=n;t!=0;t/=10)
   a[i++]=t%10;
c=i;
for(i=0;i<c-1;i++)
   for(j=0;j<c-i-1;j++)
       if(a[j]<a[j+1])
           {
              t=a[j];
              a[j]=a[j+1];
              a[j+1]=t;
           }
for(t=0,i=0;i<c;i++)
   t=t*10+a[i];
printf("\nLargest number that can be formed by digits of %d is %d",n,t);
return 0;
}

No comments: