You are on page 1of 6

LABORATORY EXERCISE #6

ARRAYS AND STRINGS

OBJECTIVES
 To introduce the concept of arrays.
 To learn more about strings and <string.h>.
THEORY

ARRAYS
An array is a collection of variables of the same type occupying an adjacent region in memory.
e.g.
elements 5 23 -1 400

no[0] no[1] no[2] no[3]

Array elements are numbered or indexed from 0 to (N-1) where N is called the array size. N
must be a positive non-zero number. In the case above, N is 4. The index numbers 0 to 3 are
also known as the subscripts of the array name no.

Array Initialization

An array must be initialized before its use. In the example above we initialize the array with:
int no[4]; //initialization
no[0] = 5; //assignment of elements
no[1] = 23;
no[2] = -1;
no[3] = 400;
or:
int no[4] = {5, 23, -1, 400}; //initialization and assignment of elements

If the number of values in the list is less than the size of the array, the remaining elements of
the array are initialised to zero. Consequently, if the number of values in the list is more than
N-1, then an error will occur. In
int no[] = {5, 23, -1, 400};
where the size of the array is not specified, the compiler automatically assigns the array size N
(in this case, 4) by counting the number of elements in the list.

Other examples of array initialization:


int scores[10]; //array of integers
float fare[5]; //array of floats
char paragraph[100]; //array of characters
The preprocessor #define is often a convenient way to change the size of an array in long
programs. Every time a new array size is preferred, you need go over the lines of the code. For
e.g. the label SIZE below is replaced with 4 throughout the program during compilation:

#include <stdio.h>
Output:
#define SIZE 4
Enter no[0] = 2
int main() Enter no[1] = 4
{ Enter no[2] = 8
int no[SIZE], i; Enter no[3] = 16
for (i=0; i<SIZE; i++)
{ no[0] = 2
printf("Enter no[%i] = ", i); no[1] = 4
scanf("%i", &no[i]); no[2] = 8
}
no[3] = 16
for (i=0; i<SIZE; i++)
{
printf("\nno[%i] = %i", i, no[i]);
}
return 0;
}

Character Arrays and Strings

A string is simply an array of characters. Its initialization method is slightly different from other
data types because a NULL, or the end-of-string character ‘ \0’ is appended at the end of the
array. e.g.
char letters[6] = { ’h’, ’e’, ’l’, ’l’, ’o’,’\0’ }; //has 6 elements but only 5 may be used
char letters[] = “abcde”; //in this form, ‘\0’ is automatically appended

Example: Output:
What is your name? MARIA
int main() Hello, MARIA!
{
char name[20]; //name may have 19 characters only What is your name? MARIA SHARA
printf("What is your name? "); Hello, MARIA!
scanf("%s", name); //the & beside name may be omitted Note: Only the MARIA is assigned to
printf("Hello, %s!", name); name because of the space. Try
return 0; changing %s to %[ ABC...Z].
} Characters inside the [] define the
valid input chars. Include a space.

The arrays mentioned so far are called one-dimensional array or 1D array.


Two-dimensional Arrays, 2D

The number of subscripts determines the array dimension. For example, no [N] refers to a one-
dimensional array size N. Similarly, no[ N][ M ] refers to a two-dimensional array which is like
a table having N columns and M rows. Higher-dimensional arrays may be formed by adding
more subscripts e.g. no[N][M][L]

The program below allows us to enter elements into a 2-dimensional integer array. This may be
used with matrices or multiplication tables, and several other applications.

#include <stdio.h> Output:


int main()
{ Enter element [0][0]: 1
int no[3][3], col,row; Enter element [1][0]: 2
for (row=0; row<3; row++) //input Enter element [2][0]: 3
{ Enter element [0][1]: 4
for (col=0; col<3; col++) Enter element [1][1]: 5
{
Enter element [2][1]: 6
printf("Enter element no[%i][%i]: ", col,row );
Enter element [0][2]: 7
scanf("%i", &no[col][row]);
} Enter element [1][2]: 8
} Enter element [2][2]: 9
for (row=0; row<3; row++) //display 1 2 3
{ 4 5 6
for (col=0; col<3; col++) 7 8 9
{
printf("%i\t", no[col][row]);
} 2D Array
printf("\n");
} [0][0] [1][0] [2][0]
return 0;
} [0][1] [1][1] [2][1]

[0][2] [1][2] [2][2]

For strings, two-dimensional arrays usually refer to the first subscript as the array index while
the second subscript is the length of each string. For example:

char string name[10][20];

means there are 10 names with each name 19 (one less 20) characters long. Do not select a
length that is too long since this consumes memory space.
The program below asks for a date in month/day/year format then outputs the month name in
words. It selects the name from an array. monthname[0] refers to January while month[11]
refers to December.

# include <stdio.h> Output:


# include <stdlib.h>
int main() Enter a date(mm/dd/yyyy) : 02/14/2014
{ February 14, 2014
char monthname[12][15] = { "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
int mm,dd,yyyy;
printf("Enter a valid date (mm/dd/yyyy) : ") ;
scanf("%d / %d / %d", &mm, &dd, &yyyy) ;
printf("\nThe day is : %s %d %d",
monthname[mm-1], dd, yyyy ) ;) ;
}

STRING.H

This header file is needed to manipulate character arrays. Don’t forget to type #include
<string.h> at the upper portion of your code to use its functions. They are the ff:

 strlen(str) - String Length


Returns the number of characters in the string, not including the null character.

 strcmp(str1, str2) - String Compare


Compares strings str1 and str2. If equal, the result is 0. If str1>str2, the result is a
positive number. If str1<str2, the result is a negative number.

 strcasecmp() - Case-insensitive version of strcmp().


 strncmp(str1, str2, n) - String Compare n Characters
Compares str1 and str2 up to n characters. If equal, the result is 0. If str1>str2, the
result is a positive number. If str1<str2, the result is a negative number.

 strncasecmp(str1, str2, n) - Case-insensitive version of strncmp()



 strcpy(str1, str2) - String Copy
Copies the contents of str2 into str1.

 strncpy(str1, str2, n) - String Copy n Characters


Copies n characters of str2 into str1.

 strcat(str1, str2) - String Concatenate


Attaches the contents of str2 to the end of str1

 strnat(str1, str2, n) - String Concatenate n Characters


Attaches n characters of str2 to the end of str1

 strstr(str1, str2) - Search String


Searches whether str2 is a substring of str1. If found, returns a pointer to the first
occurrence of str2 in str1. If str2 is not found, returns a NULL pointer.

 strrchr(str, c) - Search Charater


Searches for the occurrence of character c in str. If found, returns a pointer to the last
occurrence of character c in str. If c is not found, returns a null pointer.

EXERCISES
1. Make an ATM program which will display the following menu:
ATM Menu
C - Check Balance
D - Deposit
W - Withdraw
Select an option: ___
Use a function for each C, D and W selection. Once an option is chosen, the required
output is displayed, then the program ends. The ff. are the output requirements:
 C option: (Make sure to initialize the balance amount.) The balance amount will
display.
 D option: The amount to deposit is asked. Add this to balance then display the new
balance.
 W option: The amount to withdraw is asked. Subtract this from balance then display
the new balance. (Assume that the withdrawn amount is less than the balance.)
2. Revise your ATM program in #1. Add a last option, Q-Quit. The ATM menu should
reappear (hint: use loop) after each C,D or W option procedure displays the balance.
Except of course when option Q is selected. Add also an error-trapping message and
procedure which will ask for a new amount whenever an amount larger than balance is
entered to be withdrawn.
3. Ask for a string. Display its first letter.
e.g. Enter a string: hello
hello start with the letter h
4. Ask for a string. Display but reverse the order of the characters.
e.g. Enter a string: hello
olleh
5. Ask for a sentence from a user. Redisplay the sentence.
6. Ask for a string. Determine if the entered string is a palindrome.
Note: A palindrome is a word or group of words that can be read from left to right, and
vice versa. Examples are: dad, madam, level, radar, eye, a nut for a jar of tuna
7. Ask for 10 input numbers to a 1D integer array. Then call a function that will determine
the smallest and the largest from the entered values.
8. Ask for input values to a 1D integer array of size 10. Then call a function that will display
them in the reverse order.
9. Ask for input values to a 1D integer array of size 10. Sort the entered values in an
ascending order. Use bubble sorting.
10. Ask for the elements of two 3x2 matrices, A and B. Then add and display A + B.
e.g.

A= 3 4 0 B= 6 3 9
2 -1 5 -2 4 7

A + B = 9 7 9
0 3 12

11. Ask for a string. Display how many letters.


12. Ask for an alphanumeric (letters and/or numbers) password. Display whether correct or
not correct. Choose your password.
13. Ask for 2 countries. Display them in an alphabetical order.
14. Ask for 2 words. Search whether the second word is found inside the first word.
e.g. Enter a word : interesting
Enter word to search: rest
Found!
15. Ask for the user’s 5 names. Display them alphabetically in descending order.

You might also like