Q.) WAP to Sort the Elements in ascending order an array With C program.
#include< stdio.h>
#include< stdlib.h>
int main()
{
int *a,n,i,j,temp;
printf("Enter size of array:");
scanf("%d",&n);
a = malloc(sizeof(int)*n);
printf("Enter %d Elements:",n);
for(i=0;i< n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i< n-1;i++)
{
for(j=0;j< n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("After sorting it in ascending order:");
for(i=0;i< n;i++)
{
printf("%d ",a[i]);
}
getch();
}
Output
Sample Input 1:
5 5 7 9 3 1
Sample Output 1:
1 3 5 7 9
Program Explanation
Step 1 : Include header files (#include< stdio.h> and #include< conio.h>).
Step 2 : Start with main function with return type.
Step 3 : parenthesis to start and end the program { }.
Step 4 : declare variables with data type i.e, '*a,n,i,j,temp' is an integer type so we use "int" data type.
Step 5 : Use output function printf() to print the output on the screen.
Step 6 : Use input function scanf() to get input from the user.
Step 7 : here, Sort the Elements in ascending order an array ,Enter size of array . then scanf function was seen this size of array , and give a message on screen enter a element after enter element, then loop will start and check the condition.then condition was true the enter the loop and scanf function was seen the a[i] and then go to another loop for(i=0;i< n-1;i++) and check condition and then go to loop for(j=0;j< n-1;j++) here also condition was it will check if statement ,if(a[j]>a[j+1]) and then inter the loop and calculated the expression and print the "After sorting it in ascending order" and then for loop was run for(i=0;i< n;i++) and give output of the program "a[i]" :
Step 8 : using getch() function to hold the screen.