0% found this document useful (0 votes)
26 views

Ch07-Arrays and Strings

The document discusses arrays and multidimensional arrays in C programming. It covers array declaration, initialization, accessing array elements, and notes about arrays. Examples are also provided to demonstrate using arrays.

Uploaded by

Vikrant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Ch07-Arrays and Strings

The document discusses arrays and multidimensional arrays in C programming. It covers array declaration, initialization, accessing array elements, and notes about arrays. Examples are also provided to demonstrate using arrays.

Uploaded by

Vikrant Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

Chapter 6

Arrays and Strings

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 2

Chapter Contents
 Arrays

 Multidimensional arrays

 Strings - arrays of characters

 Library functions manipulating strings

 Summary

 Exercises

An array is a data structure,


containing elements of the same type.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 3

Array Declaration
int arr[10];
float grades[6];
char string[18];
type of each # of
element elements

int arr[10]; declaration of an array, named arr.


consisting of 10 int elements.
name of
array

arr ? ? ? ? ? ? ? ? ? ?

arr[0] arr[4] arr[9]


© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 4

Array Declaration – cont’d


 float grades[6]; - declaration of an array, named grades,
consisting of 6 elements of type float.
sizeof(grades) == 6*sizeof(float).
grades
? ? ? ? ? ?

grades[0] grades[5]

 char string[18]; - declaration of an array,named string,


consisting of 18 elements of type
char.

sizeof(string) == 18*sizeof(char).
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

string[0] string[6] string[11] string[17]


© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 5

Notes about Arrays


 An array is also called a vector.

 The index of position number 1 is 0 (zero).

 C does not have any operator to work with an array “as a whole”.

 Upon declaration the initial values are not defined.

 Size (number of elements) must be constant – requested amount of


memory must be known at compilation time.
int a = 5;
int arr[a]; - wrong, not a constant !

 Memory is allocated consecutively.

 No boundary checks are performed by the computer.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 6

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;

 Within declaration (using an initialization list).


int arr[5] = {5,3,2,7};
automatically initialized to zero.
arr: 5 3 2 7 0

int arr[] = {5,3,2,7};

arr: 5 3 2 7
 If the size of array is not specified, size is determined by the number of
initializing values.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 7

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));

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 8

Example: array1.c – cont’d


16 /* initialization of the array’s elements */
17 for (i = 0 ; i < 10 ; i++)
18 {
19 printf("\nEnter a value for the element "
20 "in position %d=>",i);
21 scanf("%d", &arr[i]);
22 }
23
24 printf("Which element do you wish to access ?=> ");
25 scanf("%d", &index);
26
27 /* it is the user’s responsibility to perform
28 boundaries check !Check if the index is legal. */
29
30 if (index >= 0 && index <= 9)
31 printf("arr[%d] = %d\n", index, arr[index]);
32 else
33 printf("Illegal index, sorry !\n");
34 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 9

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

19 printf("Enter characters and then press "


20 "CTRL/Z and ENTER\n");

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 10

Example: counter.c – cont’d


21 while ( (c=getchar()) != EOF)
22 if (c >= '0' && c <= '9')
23 /* the character is a digit */
24 digits[c-'0']++;
25 /* increase the correct element of arr */
26 else
27 if (c==' '||c=='\n'||c=='\t')
28 /*the character is a white*/
29 nwhite++;
30 else /* the character is not a digit
31 nor a white */
32 nother++;
33 /* print how many times each digit was entered */
34 printf("digits: 0 1 2 3 4 5 6 7 8 9\n ");
35 for (i = 0 ; i < 10 ; i++)
36 printf("%3d", digits[i]);
37 /*print how many whites/other characters were entered */
38 printf("\nwhite spaces: %d", nwhite);
39 printf("\nothers: %d\n", nother);
40 }
© Copyright: Spymek Software Pvt. Ltd.
Multidimensional Array
C1 Ch03 - Operators and Expressions – 11

– Declaration
 Declaration: int myArr[4][3];
char TicTacToe[3][3];

 int myArr[4][3]; - Declaration of a two-dimensional array


named myArr, consisting of 12 integer elements
[0][0] [0][2] [1][1] [3][0] [3][2]

myArr

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


myArr
[0][0] [0][2]
two dimensional
representation is
[2][0] [2][2] for easier viewing
only.
[3][0] [3][2]
© Copyright: Spymek Software Pvt. Ltd.
Multidimensional Array
C1 Ch03 - Operators and Expressions – 12

– 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;

 Within declaration (using an initialization list).


int myArr [4][3]={1, 2, 3, 4, 5, 6, 7, 8, 10};
1 2 3
4 5 6
7 8 9
© Copyright: Spymek Software Pvt. Ltd.
10 0 0
C1 Ch03 - Operators and Expressions – 13
Multidimensional Array
– Initialization – cont’d
1 2 3
 int myArr [4] [3] = { 1, 2, 3,
4 5 6
4, 5, 6 ,
{ 7 }, 7 0 0
8, 9, 10 };
8 9 10

 int myArr [ ] [3] = { 1, 2, 3, 1 2 3


4, 5, 6,
4 5 6
7 };
7 0 0

 A two dimensional array is also called a matrix.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 14

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

Example: multiarr.c – cont’d


21 for ( i = 0 ; i < 3 ; i ++)
22 {
23 for ( j = 0 ; j < 3 ; j++)
24 {
25 printf("Enter a value for location"
26 "[%d][%d] => ", i, j);
27 scanf ("%d", &mat[i][j]);
28 }
29 }
30 /* check the sum of one diagonal. All sums will
31 be compared to it */
32 sum = mat[0][0] + mat[1][1] + mat[2][2];
33 /* if the sum of the other diagonal is
34 different,it is not a magic square. In that
35 case, put the value FALSE in flag */
36 if (sum != mat[0][2] + mat[1][1] + mat[2][0])
37 flag = FALSE;

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 16

Example: multiarr.c – cont’d


38 /* check each row and each column of the matrix.
39 If the sum of one of them is different, it is not magic square*/
40 for(i = 0 ; flag == TRUE && i < 3 ; i++)
41 {
42 if( mat[i][0] + mat[i][1] + mat[i][2] != sum )
43 flag = FALSE;
44 if( mat[0][i] + mat[1][i] + mat[2][i] != sum )
45 flag = FALSE;
46 }
47
48 /* check flag and print a message accordingly */
49 if(flag == TRUE)
50 printf("This is a magic square !\n");
51 else
52 printf("This is not a magic square !\n");
53 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 17

Strings
 C does not define a string type.

 By convention an array of characters (char) followed by a ‘\0’


(ASCII 0) represents a string.

 All standard library functions comply with this standard.

 Declaration: char s[15];

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'};

All the initializations above produce the following :


s t r i n g e x a m p l e \0

'\0’ is a string terminator (often called


“null terminator”).
It is a byte where all bits are zeros.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 19

Initialization of Strings – cont’d


 NOTE:
The assignment is good only during declaration. There is no
assignment operator between strings.

"a" is a constant string (containing 2 characters: 'a' and '\0').


however 'a' is a constant character (just 1 character).

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 20

Strings I/O
 Output: char s[30] = "Hello!";

Using library functions. s may be printed by :

One character at a time. 1) printf("%s", s);


2) puts(s);
3) for(i=0 ; s[i]!='\0’ ; ++i)
 Input: putchar(s[i]);

Looping through the elements and assigning them a value.


Initialization (as shown before). S may be give a value by :

Using library functions. 1) scanf("%s" ,s);


2) gets(s);
 Note:
All library functions assume '\0 ' at the end of the string.
gets() reads until ‘\n’ (as opposed to scanf()).

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 21

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");

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 22

Example: str-and-char.c – cont’d


21 /* first prompt before the while loop */
22 printf("Enter a string.\n");
23
24 /* get strings as long as the user doesn’t press
25 CTRL+z and ENTER.When he does,gets()
26 will return NULL(as opposed to getchar())*/
27
28 while (gets(str) != NULL)
29 {
30 if (str[0] == CH)
31 /* if the string starts with CH */
32 {
33 puts(str); /* print the string */
34 cnt++; /* increase the counter */
35 }
36 printf("Enter the next string.\n");
37 }
38 printf("\n\nThe number of strings beginning "
39 "with '%c' is : %d\n",CH, cnt);
40 }
© Copyright: Spymek Software Pvt. Ltd.
Library Functions for
C1 Ch03 - Operators and Expressions – 23

Manipulating Strings

 The library functions manipulating strings may be divided into


three groups.

 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.

© Copyright: Spymek Software Pvt. Ltd.


Library Functions for
C1 Ch03 - Operators and Expressions – 24

Manipulating Strings – cont’d

 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.

strncmp(s1, s2, maxlen)


Compares at most maxlen characters of one string with the
other(returned value as above).

© Copyright: Spymek Software Pvt. Ltd.


Library Functions for
C1 Ch03 - Operators and Expressions – 25

Manipulating Strings – cont’d

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

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 26

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);

© Copyright: Spymek Software Pvt. Ltd.


Example: inspect-strings.c
C1 Ch03 - Operators and Expressions – 27

– 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 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 28

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!

strncpy(s1, s2, max)


Copies at most max characters from s2 to s1.

strncat(s1, s2, max)


Appends at most max characters of s2 to s1.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 29

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

Physical Range vs. Logical Range


physical range
char str[10]; h e l l o \0 ? ? ? ?
strcpy(str, "hello"); str
logical range

 strcpy (str, “xyz”);

 strlen(str) is now 3 – the logical size. The physical size


remains 10.
str x y z \0 o \0 ? ? ? ?

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 */

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 32

Example: del-char.c – cont’d


17 printf("This program gets a string and acharacter.\n"
18 "It deletes all the occurrences of the character "
19 "from the string.\n");
20 /* get the string and the char from the user */
21 printf("Enter a string => ");
22 gets(s);
23 /*save the length of the string before the deletions*/
24 savelen = strlen(s);
25 printf("Enter a character => ");
26 ch = getchar();
27 for (i=j=0 ; s[i] ; i++) /*check every char in the
string*/
28 {
29 if (s[i] != ch)
30 {
31 s[j] = s[i];
32 j++;
33 }
34 } © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 33

Example: del-char.c – cont’d


35 s[j] = '\0'; /* if ch occurred in the s, s is now
36 shorter. j indicates the new end of the string s,
37 so we place a Null terminator there. */
38 /* if the length of the original string equals the
39 length of the string after the deletions, it means
40 that the character did not occur in the string */
41 if (savelen == strlen(s))
42 printf("The character '%c' does not occur "
43 "in the string \"%s\"\n", ch, s);
44 else
45 {
46 printf("The character '%c' was deleted from
"
47 "the string %d times.\nThe new string is :"
48 "\"%s\"\n",ch, savelen-strlen(s), s);
49 }
50 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 34

Summary – Arrays and Strings


 An array is a data structure that contains a number of elements of the
same type.
 The index of the first element in the array is 0 (zero).
 C does not have any operator to work with an array “as a whole”
 The size of an array must be a constant. It must be known at
compilation time.
 Memory is allocated consecutively.
 No boundary checks are performed by the computer.
 There is no string type in C. However, by convention an array of
characters (char) followed by '\0' represents a string.
 Library functions manipulating strings are prototyped in
<string.h>, except from those dealing with I/O, which
are prototyped in <stdio.h>.

© Copyright: Spymek Software Pvt. Ltd.

You might also like