Introduction to C Programming - Exercise on Arrays
Sorting an Array
#include<stdio.h>
int main()
{
int a[5] = { 3,1,2,4,5 };
int i = 0, j = 0,n=5,temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
}
system("pause");
return 0;
}
Output
Finding and Displaying only unique elements in an array
#include<stdio.h>
int main()
{
int a[5] = { 1,1,2,2,3};
int j = 0, i = 0,n=5;
for (i = 0; i < n; i++)
{
if (a[i] != a[i + 1])
j = j + 1;
a[j] = a[i + 1];
}
for (i = 0; i < j; i++)
{
printf("%d", a[i]);
}
system("pause");
return 0;
}
Output
Reversing the contents of an array
#include<stdio.h>
int main()
{
int a[5] = { 1,2,3,4,5};
int j = 0, i = 0,n=5,temp=0;
for (i = 0; i < n/2; i++)
{
temp = a[i];
a[i] = a[n -i-1];
a[n - i-1] = temp;
}
for (i = 0; i < n; i++)
{
printf("%d", a[i]);
}
system("pause");
return 0;
}
Output