Write a program to arragne the names in assending order using call by value.
// C++ implementation
#include <stdio.h>
#include <string.h>
#define MAX 50
//Function declaration
void sortNames(char arr[][MAX], int n);
int main()
{
//Declare names array
char arr[][MAX] = {"Joan","Beatrice", "Mary", "Ann"};
int size = sizeof(arr)/sizeof(arr[0]);
//Call functioni passing by value
sortNames(arr, size);
//Display sorted names
printf("Name in sorted order : \n");
for (int i=0; i<size; i++)
printf("%d. %s \n", i+1, arr[i]);
return 0;
}
//Function definition
void sortNames(char arr[][MAX], int n)
{
char temp[MAX];
//Sort names array using bubble sort
for (int j=0; j<n-1; j++)
{
for (int i=j+1; i<n; i++)
{
if (strcmp(arr[j], arr[i]) > 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
Comments
Leave a comment