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

In this program, we are perusing unbounded numbers and afterwards organizing them in rising request.

Here interminable implies, the program should peruse numbers until a specific number is entered to end the understanding procedure.

For our situation we are utilizing – 1 to stop the understanding procedure.

As we as of now don’t have a clue what number of numbers will be entered by the

client so we are utilizing the idea of dynamic memory assignment to apportion memory for a number at the run time.

I have utilized ordering with a pointer to make the program progressively clear and straightforward.

You can remark underneath on the off chance that you discover any trouble 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

Leave a Comment

error: Alert: Content is protected!!