120 likes | 218 Views
Today’s Agenda. Array of Strings Exercise on Array of Strings. Arrays of Strings. Declaration: char name[5][30]; Five strings each contains maximum thirty characters. Initialization: char[5][10]={“One”,”Two”,”Three”,”Four”,”Five”}; Other valid declarations:
E N D
Today’s Agenda • Array of Strings • Exercise on Array of Strings
Arrays of Strings • Declaration: • char name[5][30]; • Five strings each contains maximum thirty characters. • Initialization: • char[5][10]={“One”,”Two”,”Three”,”Four”,”Five”}; • Other valid declarations: • char[][]={“One”,”Two”,”Three”,”Four”,”Five”}; • char[5][]={“One”,”Two”,”Three”,”Four”,”Five”};
String Arrays: Reading and Displaying void main() { char name[5][30]; printf(“\n Enter five strings”); /* Reading strings */ for(i=0;i<5; i++) scanf(“%s”,name[i]); /* Printing strings */ for(i=0;i<5; i++) printf(“\n%s”,name[i]); }
Write a C program to read the full name of the customers and their telephone numbers. Full name includes Surname followed by first name and then the middle name. • Sort the customer names in alphabetical order with surname first followed by comma (,) and initials of the first and middle names. Display this sorted customer list along with their telephone no. • E.g Ghokle Suraj Ram should be written as Ghokle,S.R
OUTPUT mayuri@atlas:~/cp1$ ./a.out Enter names and telephone numbers sharma anil sudhir 1234 verma mona abhay 9876 garg sona abhi 7654 modak tinu pintu 9870 shree shits sumit 8765 Customer list in alphabetical order garg,s.a 7654 modak,t.p 9870 sharma,a.s 1234 shree,s.s 8765 verma,m.a 9876
Declarations • char fname[20][10],mname[20][10],sname[20][10]; • char name[20][15],telephone[20][10],dummy[20];
Code for required format of full name for(i=0;i<n;i++) { strcpy(name[i],sname[i]); strcat(name[i],","); dummy[0] = fname[i][0]; dummy[1] = '\0'; strcat(name[i],dummy); strcat(name[i],"."); dummy[0] = mname[i][0]; dummy[1] = '\0'; strcat(name[i],dummy); }
Code for Sorting list in alphabetical order along with telephone numbers for(i=1;i<n;i++) for(j=1;j<=n-i;j++) if(strcmp(name[j-1],name[j]) > 0) { strcpy(dummy,name[j-1]); strcpy(name[j-1],name[j]); strcpy(name[j],dummy); strcpy(dummy,telephone[j-1]); strcpy(telephone[j-1],telephone[j]); strcpy(telephone[j],dummy); }
Print the list for(i=0;i<n;i++) printf("%s \t %n",name[i],telephone[i]);
Exercise : Array of Strings • Problem Statement: Write a C program that will read and store the details of a list of students in the format • ID NAME MARKS • And produce the following output • Alphabetical list of Names, ID’s and Marks. • List sorted on ID’s • List sorted on Marks
Exercise • Write a C program which will read a line of text and rewrite it in the alphabetical order. 2. Write a C program to replace a particular word by another word in a given string. Both the words are provided by the user at run time.