C++ exercises solutions: C++ pointers (con)


C++ pointer exercises (con.)

1. Write a C++ function to sort an array of ten integer values in ascending order.

The function will accept two arguments-- a pointer that points to the array and the array size. The function returns a pointer that points to the sorted array.

Solution:


#include<iostream>
#include<conio.h>
 
using namespace std;
int *sortAsc(int *p, int size);
   int main()
    {
     int arr[]={23,34,2,3,5,12,42,56,89,8};
     int *p=sortAsc(arr,10);
     //output the sorted array
     int i;
     for(i=0;i<10;i++)
       cout<<*(p+i)<<endl;
    
     getch();
     return 0;
 
    }
   


int *sortAsc(int *p, int n){
    int i,j;
    for(i=0;i<n;i++)
        for(j=i+1;j<n;j++)
            if(*(p+j)<*(p+i))
              {
                int temp=*(p+j);
                *(p+j)=*(p+i);
                *(p+i)=temp;
                }
   return p;
}

 

2. Modify the solution of exercise 1 in order to sort the array in descending order.

Solution:


#include<iostream>
#include<conio.h>
 
using namespace std;
int *sortAsc(int *p, int size);
   int main()
  {
     int arr[]={23,34,2,3,5,12,42,56,89,8};
     int *p=sortAsc(arr,10);
     //output the sorted array
     int i;
     for(i=0;i<10;i++)
       cout<<*(p+i)<<endl;
    
     getch();
     return 0;
 
    }
   


int *sortAsc(int *p, int n){
    int i,j;
    for(i=0;i<n;i++)
        for(j=i+1;j<n;j++)
            if(*(p+j)>*(p+i))
              {
                int temp=*(p+j);
                *(p+j)=*(p+i);
                *(p+i)=temp;
                }
   return p;
}


Comments

Mustafa  comment

 Mustafa

Thank you for everything


2017-05-08
Bravid comment

 Bravid

These are useful exercises!
Thank a lot...


2013-08-06



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.