Translate

Saturday, 2 June 2012

List of strings (2-d array of characters )


         A two dimensional array has to be used to read and process a list of names, where the first index(subscript) specifies the size of the list i.e. the no of names to be processed and the second index indicates the size of each name.
  Example
          char name[10][20];
where the number 10 specifies that a list having 10 names with each size of 20 characters can be accessed.

We can initialise the list also.
          char name [5][20]={“Ashok”, “Neha”, “Dipesh”, “Sarita”, “Shubham”};
Here also we can leave the first index blank.


Q. Write a program to read a list of n-names and display them in alphabetical order.
#include<iostream>
#include<stdio.h>
#include<string.h>
void main()
{
     char name[50][80], temp[80];
     int n, i, j;
     cout<< “How many names: ”;
     cin>>n;
     cout<< “Enter”<< n << “names”;
     for(i=0; i<n; i++)
          gets( name[i] );
     for(i=0; i<n-1; i++)
          for(j=0; j<n-i-1; j++)
               if(strcmpi((name[j], name[j+1] ) >0)
               {
                    strcpy(temp, name[j]);
                    strcpy(name[j], name[j+1]);
                    strcpy(name[j+1], temp);
               }
     cout<< “Arranged list \n”;
     for(i=0; i<n; i++)
     cout<< name[i]<< “\t”;
}

Total Pageviews