2D Arrays and Structures
2D Arrays and Structures
puts() can print only one string at a time, and it places the cursor on next
line
Similarly gets() can receive only one string at a time although it can be a
multi-word string
Standard Library – String
functions
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string into
another
strncmp Compares two strings
strcmpi Compares two strings without regard to
stricmp case
strnicmp Compares first n characters of two strings
without regard to case
Standard Library – String functions
cntd…
strdup Duplicates a string
strchr Finds first occurrence of a given
character in a string
strrchr Finds last occurrence of a given
character in a string
strstr Finds first occurrence of a given string in
another string
strset Sets all characters of a string to a given
character
strnset Sets first n characters of a string to a
given character
strrev Reverses string
Two dimensional arrays
You can have a two dimensional array to store
student number and the marks
int stud[10][2];
int i,j;
for (i=0;i<=9;i++)
{ printf(“ Enter student number and marks”);
scanf(“%d %d”,&stud[i][1],&stud[i][2]);
}
Same way one can print the elements of the 2-d array
Initialization of a 2-d array
can be done in the following
ways
int stud[5][2] = { {1000, 56}, {1001,45},
{1002,78}, {1003,84},
{1004,63}};
int stud[30][2];
to hold student number and marks
for (i=0;i<=2;i++)
scanf(“%c %d %d”,&name[i],&age[i],&mark[i]
for (i=0;i<=2;i++)
printf(“%c %d %d\n”,name[i],age[i],mark[i]
Use of structure…..
typedef struct student
{ char name;
int age;
int mark;
};
student s1,s2,s3;
printf(“Enter name, age and marks of the students”);
scanf(“%c %d %d”,&s1.name,&s1.age,&s1.mark);
scanf(“%c %d %d”,&s2.name,&s2.age,&s2.mark);
scanf(“%c %d %d”,&s3.name,&s3.age,&s3.mark);
printf(“\n%c %d %d”,s1.name,s1.age,s1.mark);
printf(“\n%c %d %d”,s2.name,s2.age,s2.mark);
printf(“\n%c %d %d”,s3.name,s3.age,s3.mark);
The above will also be complex
when there are many students,
say 100
Array of structures is the solution
struct student
{ char name;
int age;
int mark;
};
struct student s[100];
int i;
printf(“Enter name, age and marks of the 100 students”);
for (i=0;i<=99;i++)
scanf(“%c %d %d”,&s[i].name,&s[i].age,&s[i].mark);
for (i=0;i<=99;i++)
printf(“\n%c %d %d”,s[i].name,s[i].age,s[i].mark);