Lab 9 Strings: MDJ11103 - Computer Programming Laboratory Module
Lab 9 Strings: MDJ11103 - Computer Programming Laboratory Module
Lab 9 Strings: MDJ11103 - Computer Programming Laboratory Module
LAB 9
STRINGS
1
MDJ11103 - Computer Programming Laboratory Module
1. OBJECTIVES:
2. INTRODUCTION:
Array is a collection or a data structure of a fixed number of components where in all of the
components are of the same type.
The data type string is a programmer-defined and is not part of the C language. The C standard
library supplies it.
Strings can be treated as array of type char used to store names of people, places, or anything that
involves a combination of letters. Numbers can be stored as character, a string can be an array of
numbers, too.
To use the data type string, the program must include the header file string.
#include <string.h>
char string1[10];
Index / Subscript
0 W
1 e
2 l
3 c
4 o
5 m
6 e
7 \0
8
9
Notice that string1[7] contains the character ‘\0’, the null character marks the end of a string.
2
MDJ11103 - Computer Programming Laboratory Module
char namelists[10][50];
The above data structure of array can store a list of names or strings; it can store 10 names or strings
with the size of up to 50 characters.
3. TASKS:
3.1 The program shows how to declare, initialize and display strings. Type, compile and run the
program. [Note : The function “sizeof” is to get the variable size in term of byte and the function
“strlen” is to find the length of the string]
#include <stdio.h>
#include <string.h>
int main( )
{
//3 ways of declaring and initializing strings
char string1[10] = {“Welcome”};
char string2[] = {'W','e','l','c','o','m','e','\0'};
char string3[] = "Good Bye";
return 0;
}
3
MDJ11103 - Computer Programming Laboratory Module
c. The string library provides many functions for string processing. Find out what each of the
string function listed below does:
i. strcpy -
ii. strcmp -
iii. strcat -
iv. atoi -
v. atof -
vi. getchar -
vii. putchar -
viii. gets -
ix. puts -
3.2 The program shows how to assign values into strings variables. Type, compile and run the
program.
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 20
int main( )
{
char name[STRING_LENGTH];
float marks[3];
float total = 0;
int i;
/*Display information*/
printf ("\nStudent name : %s", name);
for (i=0;i<3;i++)
printf ("\nTest %d mark : %5.2f",i+1, marks[i]);
return 0;
}
4
MDJ11103 - Computer Programming Laboratory Module
b. Write a program that takes a list of students’ names and marks and calculates the average
marks. You are required to declare two arrays called names and marks. Assume number of
students are 5.
Sample output:
Jason 60.00
Ahmad 77.00
Chong 88.00
Kumar 70.00
Daniel 55.00
5
MDJ11103 - Computer Programming Laboratory Module
3.3 Write a program that resembles a phone book, which stores and displays the names, the
addresses (cities) and the telephone numbers for 10 people.