Ch07-Arrays and Strings
Ch07-Arrays and Strings
Chapter Contents
Arrays
Multidimensional arrays
Summary
Exercises
Array Declaration
int arr[10];
float grades[6];
char string[18];
type of each # of
element elements
arr ? ? ? ? ? ? ? ? ? ?
grades[0] grades[5]
sizeof(string) == 18*sizeof(char).
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
C does not have any operator to work with an array “as a whole”.
Array Initialization
Looping through the elements and assigning them a value.
example:
int arr[5], i;
for (i = 0 ; i < 5 ; ++i)
arr[i] = i;
arr: 5 3 2 7
If the size of array is not specified, size is determined by the number of
initializing values.
Example: array1.c
1 /* array1.c
2 This program illustrates an array.
3 An array of 10 elements will be declared, initialized,
4 accessed*/
5
6 #include <stdio.h>
7 void main(void)
8 {
9 int arr[10]; /* declaration of an array named arr,
10 consisting of 10 elements of type int */
11 int i; /* a counter for initializing the array elements
*/
12 int index;/* the user will choose which index to access
*/
13 /* arr holds 10 * sizeof(int) bytes in memory */
14 printf("arr holds %d consecutive bytes in memory\n"
15 ,sizeof(arr));
Example: counter.c
1 /* counter.c
2 This program asks the user to enter characters, and counts
3 them by three groups : digits, white spaces and others.
4 The digits are counted per digit, which means that the program
5 will know how many times you entered each digit.
6 This could be achieved by holding 10 counters, but the program
7 does it using an array, which is a lot more
8 elegant and simple. */
9
10 #include <stdio.h>
11
12 void main(void)
13 {
14 int i, nwhite = 0, nother = 0; /* counters */
15 int c; /* for input from the user */
16 int digits[10]= {0}; /*initializing the first element
17 (or more) automatically initializes the rest to 0*/
18
– Declaration
Declaration: int myArr[4][3];
char TicTacToe[3][3];
myArr
– Initialization
Initialization:
Looping through the elements and assigning them a value.
Example:
int myArr[4][3], i, j;
for (i = 0 ; i < 4; ++i)
for(j = 0 ; j < 3 ; ++j)
myArr[i][j]= i * j;
Example: multiarr.c
1 /* multiarr.c
2 This program asks the user to fill in the values
3 for a two dimensional array(3*3), and checks whether
4 it is a magic square */
5
6 #include <stdio.h>
7 #define TRUE 1
8 #define FALSE 0
9
10 void main()
11 {
12 int mat[3][3]; /* the two dimensional array */
13 int i, j; /* counters and indexes */
14 int sum; /* the sum of each row, column and diagonal */
15 int flag = TRUE; /* if the matrix turns out to be an
16 ordinary one, and not a magic square, flag will turn FALSE.
17 The program will stop checking the square the moment this
flag
18 becomes FALSE */
19 printf ("enter values for the matrix to "
20 "find out if it is a magic square:\n");
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 15
Strings
C does not define a string type.
An array consisting of 15
elements, each of type char.
Has a potential to be a string.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 18
Initialization of Strings
Initialization: char s[15] = "string example";
char s[] = "string example";
char s[] = {'s','t','r','i','n','g',
'
','e','x','a','m','p','l','e','\0'};
Strings I/O
Output: char s[30] = "Hello!";
Example: str-and-char.c
1 /* str-and-char.c
2 This program asks the user to enter strings, and counts
3 how many of these strings begin with the lower case
4 character CH (see below) or with the matching upper case
5 letter. These strings are also printed. Strings that begin
6 with other letters are ignored -they are neither printed
7 nor counted. */
8
9 #include <stdio.h>
10 #define CH 'a'
11 void main(void)
12 {
13 char str[128];
14 int cnt = 0; /* counts the number of strings
15 starting with CH */
16 printf("Enter strings (up to 127 characters in a"
17 " string).\n");
18 printf("End a string by pressing ENTER.\n");
19 printf("To stop entering strings press CTRL-z "
20 "and ENTER.\n\n");
Manipulating Strings
GROUP 1:
Functions for Input/Output.
We have already met these functions. They are prototyped
in <stdio.h>
All library functions assume ‘\0’ at the end of a string or
supply it when required.
GROUP 2:
Examining contents of strings - prototyped in <string.h>
strlen(s)
Returns the length of string s (not including the null terminator.)
strcmp(s1, s2)
Compares two strings (lexicographically); Returns:
0 - the strings are equal.
>0 - the first string is greater.
<0 - the second string is greater.
strchr(s, c)
Finds the first occurrence of the character c within the
string s.
Returns the address of this character or NULL if not found.
strstr(s1 ,s2)
Finds the first occurrence of the string s2 in the string s1.
Returns the address where s2 begins in s1, or NULL if not found
Example: inspect-strings.c
1 /* inspect-strings.c
2 This program illustrates the use of strlen() and
3 strcmp(). The user will enter 2 strings and the
4 program will print Their lengths and compares them
5 lexicographically. */
6
7 #include <stdio.h>
8 #include <string.h>
9
10 void main(void)
11 {
12 char str1[48], str2[48];
13 int cmp;
14 /* get two strings from the user */
15 printf("Enter a string => ");
16 gets(str1);
17 printf("Enter another string => ");
18 gets(str2);
– cont’d
19 /* print the lengths of the strings */
20 printf("The length of \"%s\" is : %d\n",
21 str1, strlen(str1));
22 printf("The length of \"%s\" is : %d\n\n",
23 str2, strlen(str2));
24
25 /* compare the strings lexicographically */
26 cmp = strcmp(str1, str2);
27 if ( !cmp )
28 printf("The strings are equal.\n");
29 else
30 if (cmp < 0)
31 printf("\"%s\" is greater "
32 "than \"%s\"\n", str2, str1);
33 else
34 printf("\"%s\" is greater "
35 "than \"%s\"\n", str1, str2);
36 }
String Manipulation
GROUP 3:
Manipulating contents of strings - prototyped in <string.h>
strcpy(s1, s2)
Copies s2 onto s1.
strcat(s1, s2)
Concatenates s2 to the end of s1. The result is placed in s1.
Note:
No direct assignment is allowed between strings
Remember, string is not a type in C - it is a convention!
Example: mutate-strings.c
1 /* mutate-strings.c
2 This program illustrates strcpy(),strncpy()and strcat(). */
3
4 #include <stdio.h>
5 #include <string.h>
6 void main(void)
7 {
8 char str1[7] = "hey ", /*sizeof(str1) is 7,strlen(str1) is 4*/
9 str2[]= "bye bye", /*sizeof(str2) is 8,strlen(str2)is 7
*/
10 dest[256] = ""; /* sizeof(dest) is 256, strlen(dest) is
0 */
11 printf("str1 is \"%s\"\n", str1);
12 printf("str2 is \"%s\"\n", str2);
13 printf("dest is \"%s\"\n\n", dest);
14
15 strcpy(dest, str1); /* dest is now "hey " */
16 strcat(dest, "world"); /* dest is now "hey world" */
17 printf("dest is \"%s\"\n\n", dest);
18
19 strncpy(dest, str2, 3); /* dest is now "bye world" */
20 printf("dest is \"%s\"\n\n", dest);
21 } © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 30
char hello[5];
What is the BUG? strcpy(hello,
"Hello");
printf("%s", hello);
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 31
Example: del-char.c
1 /* del-char.c
2 This program receives a string and a char from the user,
3 and deletes all the occurrences of the char from the
4 string. If the char does not occur in the string,
5 a message is printed */
6
7 #include <stdio.h>
8 #include <string.h>
9
10 void main(void)
11 {
12 char s[127]; /* the string will be entered by the user */
13 int ch; /* the char to delete from the string s */
14 int i, j; /* counters */
15 unsigned int savelen; /* will hold the length of the
16 original string */