C/C++ Program to Read Infinite Numbers and Arrange Them in Ascending Order Full Project For Beginners

  • Post author:
  • Post category:c++
  • Post comments:0 Comments

 

 

main.c

 

 

#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]);
}
}

 

 

main.cpp

 

 

#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];
}
}

Leave a Reply