A string is a 1D array of characters, so an array of strings is a 2D array of characters. Just like we create a 2D array of int, float etc, we can also create a 2D array of character.
Syntax for declaring a 2-D array of characters:
char prg[3][12] = { {'c', 'o', 'd', 'i', 'n', 'g', '\0'}, {'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', '\0'}, {'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', '\0'} };
This above initialization is equivalent to:
char prg[3][12] = { "coding", "learning", "programming" };
Q1: Input 10 names and print them.
#include<stdio.h> void main() { char name[10][20]; int i; printf("Enter 10 names: "); for(i=0;i<=9;i++) { gets(name[i]); } printf("Input Names are:\n"); for(i=0;i<=9;i++) { puts(name[i]); } }
Q2: Input 10 names and find largest name (take ASCII value for comparing).
Q3: Input 10 names and find smallest name (take ASCII value for comparing).
Q4: Input 10 names and sort them in ascending order.
#include <stdio.h> #include <string.h> void main() { char name[10][20], t[20]; int i, j; printf("Enter 10 names"); for(i=0;i<=9;i++) { gets(name[i]); } for(i=0;i<=8;i++) { for(j=0;j<=8-i;j++) { if(strcmp(name[j], name[j+1]) < 0) { strcpy(t,name[j]); strcpy(name[j], name[j+1]); strcpy(name[j+1], t); } } } printf("10 names are: "); for(i=0;i<=9;i++) { puts(name[i]); } }
Q5: Input 10 names and sort them in descending order.