Monday, 16 November 2015

C++ Program To Read Infinite Number And Arrange Ascending Order Using Pointer

Problem :- Write A C++ Program To Read Infinite Number Then Arrange Ascending Order Using Pointer .

Logic :- We are using Malloc and realloc (reallocated memory during run time ) after getting -1 stop inserting numbers and then use an any sorting algorithm and print the element of array . if you don't know any sorting algorithm then you have to check here C Program For Bubble Sort In Ascending And Descending Order

Solution :-

#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
  //By-Ghanendra Yadav
  int *p,*q,i=1,j,k,temp;
 
  cout<<" Enter Numbers (-1 To Stop Reading) :\n ";
  p=(int*)malloc(sizeof(int));
  cin>>p[0];

  while(p[i-1]!=-1)
  {
  i++;
  p=(int*)realloc(p,sizeof(int)*i);
  q=p;
  cin>>p[i-1];
  }
  p=q;
  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++ Program To Read Infinite Number And Arrange Ascending Order Using Pointer

No comments:
Write comments

Recommended Posts × +