Practical-17
Write a program to accept 10 numbers and sort them with use of pointer.
Introduction
In this program, we will learn to accept 10 numbers and sort them with use of pointer.
Algorithm
- Start
- Declare an integer variable to store number of elements.
- Declare an integer pointer variable.
- Ask the user to enter number of elements.
- Allocate memory for the array.
- Ask user to fill the array.
- Use a cycle to sort the array using Bubble Sort.
- Print the sorted array.
- End
Code
Practical-17.c
#include <stdio.h>
void main()
{
// Declaring variables
int *arr, numOfElements, i, j, temp;
// Ask the user to enter number of elements
printf("How many elements do you wish to store? \n");
scanf("%d", &numOfElements);
// Allocating memory for the array
arr = (int*) malloc(numOfElements * sizeof(int));
// Ask user to fill the array
printf("Enter %d numbers:\n", numOfElements);
for(i = 0; i < numOfElements; i++)
{
scanf("%d", arr+i);
}
// Sorting the array using Bubble Sort
for(i = 0; i < (numOfElements - 1); i++)
{
for(j = 0; j < (numOfElements - i - 1); j++)
{
if(*(arr+j) > *(arr+(j+1)))
{
temp = *(arr+j);
*(arr+j) = *(arr+(j+1));
*(arr+(j+1)) = temp;
}
}
}
// Print the sorted array
printf("Sorted elements:\n");
for(i = 0; i < numOfElements; i++)
{
printf("%d ", *(arr+i));
}
}
Output
How many elements do you wish to store?
5
Enter 5 numbers:
5
4
3
2
1
Sorted elements:
1 2 3 4 5
Explanation
In this program, we have used a pointer to store the address of the array. We have used a cycle to sort the array using Bubble Sort. We have used a cycle to print the sorted array.