1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <stdio.h>
void print(int a[], int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%d", a[i]);
printf("\t");
}
}
int findSmallest(int a[], int size)
{
int min = a[0]; // Assign min to first value in a array
int i;
for (i = 0; i < size; i++)
{
if(a[i] < min ) // Check if next value is lower than min
min = a[i]; // if yes, give min the value of a[i]
}
return min; // return lowest vlaue
}
int main()
{
int a[] = {5, 15, 34, 54, 14, 2, 52, 72};
int *p = &a[1], *q = &a[5];
int temp;
int min;
printf("*~*~The original array*~*~\n");
print(a, 8);
printf("\n");
/* (a) Swap element 1 with element 5 */
temp = *p;
*p = *q;
*q = temp;
printf("\n");
printf("*~*~Swap element 1 and 5*~*~\n");
print(a, 8);
printf("\n");
/* (b) Swap element 2 with element 0 */
temp = a[2];
a[2] = a[0];
a[0] = temp;
printf("\n");
printf("*~*~Swap element 2 and 0*~*~\n");
print(a, 8);
printf("\n");
/* (c) Swap element 4 with element 7 */
temp = a[4];
a[4] = a[7];
a[7] = temp;
printf("\n");
printf("*~*~Swap element 4 and 7*~*~\n");
print(a, 8);
printf("\n\n");
/* (d) Find the smallest element */
printf("*~*~Find the Smallest Element*~*~\n");
min = findSmallest(a, 8);
printf("The smallest element is %d\n", min);
/* (e) Swap the smallest number with the first element in the array */
printf("*~*~Set the smallest number to the first position in array*~*~\n");
temp = a[0]; // set temp to first value in array
for(int i=0;i<8;i++)
{
if(a[i]==min)// If value at location is lowest
{
a[i]=temp; // Assign first element of array at lowest number location
i=8; // exit loop
}
}
a[0] = min; // Assign first array location with lowest value
print(a, 8);
printf("\n");
return 0;
}
|