C++ 2D array and nested for loop, sorting data from user's input

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: This program must be run at command prompt

To do: Request string input from user, store in an array and then sort the strings

To show: How to use the 2D array and nested for loop to store stings and then sort the strings

 

// a program will sort a list of strings entered by the user

#include <iostream>

using namespace std;

#include <cstring>

 

int main(void)

{

// declare two arrays named tname with 1-Dimension and name with 2-Dimension

char tname[20], name[20][20];

// normal variables...

int i, j, n;

 

cout<<"Enter the number of names: ";

cin>>n;

 

// outer loop for counter...

for(i=0; i<n; i++)

{

cout<<"\nEnter the name(one word) "<<(i+1)<<": ";

cin>>name[i];

}

// inner for loop, read row by row set outer for loop...

for(i=0; i<n-1; i++)

// innermost for loop, read column by column of the characters...

for(j = i+1; j<n; j++)

// set the condition...

// strcmp - compare the string standard library function

// do the sorting...

if(strcmp(name[i], name[j])>0)

{

// strcpy()/strcpy_s() - copy the strings...

// compare and swap...

// strcpy(tname, name[i]);

strcpy_s(tname, sizeof(tname), name[i]);

strcpy_s(name[i], sizeof(name[i]), name[j]);

strcpy_s(name[j], sizeof(name[j]), tname);

}

cout<<"\nSorted names:\n";

for (i =0; i<n; i++)

 

cout<<"\n"<<name[i];

cout<<endl;

 

return 0;

}

 

Output example:

 

Enter the number of names: 5

Enter the name(one word) 1: Mike

Enter the name(one word) 2: Josh

Enter the name(one word) 3: Smith

Enter the name(one word) 4: Peter

Enter the name(one word) 5: Joyce

Sorted names:

Josh

Joyce

Mike

Peter

Smith

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index