01 March, 2013

C++ Program To Print A Number In An Ordered Form.

This Post Contains A C++ Program To Print A Number In An Ordered Form With Correct Source Code, Algorithm & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'For-Loop', 'While-Loop' & 'Nested Loops' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.


# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.



C++ Program To Print A Number In An Ordered Form.

/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>

/* Start Of Main Program */
void main()
{

/* Declaration Of Variables */
long Num, s;
int a[10], i, j, k, temp;
clrscr();

/* Asking For The Input From User */
cout << " \n Enter Any Number : ";
cin >> Num;
cout << " \n Entered Number Is : " << Num;

/* Storing Number In Array */
j=0;
while( Num > 0 )
{
 i=Num%10;
 a[j]=i;
 j++;
 Num=Num/10;
}

/* Sorting An Array */
for(i=0;i<j;i++)
{
 for(k=i+1;k<j;k++)
 {
  if(a[i]>a[k])
  {
   temp=a[i];
   a[i]=a[k];
   a[k]=temp;
  }
 }
}

/* Converting Array Of Numbers Into A Single Number */
temp=j-2;
Num=s=0;
for(i=0;i<j;i++)
{
 s=a[i];
 for(k=0;k<=temp;k++)
 {
  s=s*10;
 }
 temp--;
 Num=Num+s;
}

/* Printing The Output Onto Screen/Console */
cout << " \n Ordered Number Is : " << Num;
getch();
}
/* End Of Main Program */

Output :

Enter Any Number : 25314
Entered Number Is : 25314
Ordered Number Is : 12345

Algorithm :

1. Initialize necessary variables & one integer array.
2. Accept one 'long int' or 'int' from user.
3. Print accepted number.
4. Store each digit of number in array.
 4.1 While(Num>0)
 4.2 Divide Num by 10, assign remainder to 'i';
 4.3 Store it in array.
 4.4 Increment the array count.
 4.5 Take remaining part of number.
     Num=Num/10
 4.6 End of while loop.
5. Sort the array in ascending order by using 'temp' variable.
6. Convert array into asingle number.
 6.1 temp=j-2. Units position.
 6.2 Initialize necessary variables.
 6.3 for(i=0;i<j;i++)
 6.3.1 Assign 1st array element to 's'.
 6.3.2 for(k=0;k<=temp;k++)
 6.3.3 Multiply s by 10 & assign same to s.
 6.3.4 End of inner for loop.
 6.3.5 Decrement temp.
 6.3.6 Add s to Num.
 6.3.7 End of outer for loop.
7. Print the ordered number.
8. Exit.




No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.