C/C++ Program to Read Infinite Numbers and Arrange Them in Ascending Order

In this program we are reading infinite numbers and then arranging them in ascending order. Here infinite means, the program should read numbers until a particular number is entered to terminate the reading process. In our case we are using -1 to stop the reading process. As we already don’t know how many numbers will be entered by the user so we are using concept of dynamic memory allocation to allocate memory for a number at the run time. I have used indexing with pointer to make the program more readable and easy to understand. You can comment below if you find any difficulty in understanding the program.

C Program

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

void main()
{
 int *p,*q,i=1,j,k,temp;  //q for storing address of 1st number
 printf(" Enter Numbers(-1 to stop reading):n ");

 p=(int*)malloc(sizeof(int));
 scanf("%d",&p[0]);

 while(p[i-1]!=-1) //read until -1 is entered
 {
  i++;
  p=(int*)realloc(p,sizeof(int)*i);
  q=p;
  scanf("%d",&p[i-1]);
 }

 p=q;

 //sorting numbers using bubble sort
 for(j=1;j<i;++j)
 {
  for(k=0;k<i-j-1;++k)
  {
   if(p[k]>p[k+1])
   {
    temp=p[k];
    p[k]=p[k+1];
    p[k+1]=temp;
   }
  }
 }

 printf("n");

 for(j=0;j<i-1;++j)
 {
  printf(" %d",p[j]);
 }
}

C++ Program

#include<iostream.h>
#include<stdlib.h>

void main()
{
 int *p,*q,i=1,j,k,temp;  //q for storing address of 1st number
 cout<<" Enter Numbers(-1 to stop reading):n ";

  p=(int*)malloc(sizeof(int));
 cin>>p[0];

  while(p[i-1]!=-1) //read until -1 is entered
 {
  i++;
  p=(int*)realloc(p,sizeof(int)*i);
  q=p;
  cin>>p[i-1];
 }

  p=q;

  //sorting numbers using bubble sort
 for(j=1;j<i;++j)
 {
  for(k=0;k<i-j-1;++k)
  {
   if(p[k]>p[k+1])
   {
    temp=p[k];
    p[k]=p[k+1];
    p[k+1]=temp;
   }
  }
 }

  cout<<"n";

  for(j=0;j<i-1;++j)
 {
  cout<<" "<<p[j];
 }
}

Output
C/C++ Program to Read Infinite Numbers and Arrange Them in Ascending Order

3 thoughts on “C/C++ Program to Read Infinite Numbers and Arrange Them in Ascending Order”

Leave a Comment

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