Write a program that inputs the names of students of a class and display them in ascending and descending order.
So let’s Write Code:
Let’s build logic First:
Algorithm for code:
- Step 1: Start
- Step 2: Declare 2D array.
- Step 3: Take inputs from user.
- Step 4: Defining function for ascending order.
- Step 5: Defining function for decending order.
- Step 6: Calling the functions.
- Step 7: Print elements.
- Step 8: End program
Code:
Write a program that inputs the names of students of a class and displays them in ascending and descending order.
#include<iostream>
#include<string.h>
using namespace std;
main()
{
int i;
char names[10][20];
void sort_asc(char [10][20]);
void sort_des(char [10][20]);
for(i = 0; i<=9; i++)
{
cout<<"Enter value of student no. "<<i+1<<" ? ";
cin>>names[i];
}
sort_asc(names);
cout<<"\nStudent names in ascending order\n";
for(i = 0; i<=9; i++)
cout<<names[i]<<endl;
sort_des(names);
cout<<"\nStudent names in descending order\n";
for(i = 0; i<=9; i++)
cout<<names[i]<<endl;
}
// definition of sort_asc() function
void sort_asc(char nm[10][20])
{
int i, u;
char temp[20];
u = 9;
while(u>=1)
{
i = 0;
while(i<u)
{
if(strcmp(nm[i],nm[i+1]) > 0)
{
strcpy(temp, nm[i]);
strcpy(nm[i], nm[i+1]);
strcpy(nm[i+1], temp);
}
i++;
}
u--;
}
}
// definition of sort_des() function
void sort_des(char nm[10][20])
{
int i, u;
char temp[20];
u = 9;
while(u>=1)
{
i = 0;
while(i<u)
{
if(strcmp(nm[i],nm[i+1]) < 0)
{
strcpy(temp, nm[i]);
strcpy(nm[i], nm[i+1]);
strcpy(nm[i+1], temp);
}
i++;
}
u--;
}
}
Hope You will learn Something. Happy Coding.
Visit my YouTube Channel as Well๐ https://www.youtube.com/watch?v=JuIHQ9cLSEw&list=PLbIhkHxfUIItTdcyCb34uRIrPJbXBndIl&index=4
Click on the below Links for more Programming Exercises:
Conditional Structure Exercises: ๐https://myustaadg.com/category/programming-exercises/conditional-structures-exercises/
Array Exercises: ๐https://myustaadg.com/category/programming-exercises/arrays-exercises/