100% found this document useful (1 vote)
236 views45 pages

C++ Arrays and Strings Overview

The document discusses arrays and strings in C++. It begins by defining arrays as groups of elements of the same type in contiguous memory locations that can be accessed via an index. It then covers initializing, accessing, and performing operations on array elements. The document also discusses strings as arrays of characters terminated by a null character. It provides examples of initializing, accessing, and operating on strings using standard library functions.

Uploaded by

Anas Muhammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
236 views45 pages

C++ Arrays and Strings Overview

The document discusses arrays and strings in C++. It begins by defining arrays as groups of elements of the same type in contiguous memory locations that can be accessed via an index. It then covers initializing, accessing, and performing operations on array elements. The document also discusses strings as arrays of characters terminated by a null character. It provides examples of initializing, accessing, and operating on strings using standard library functions.

Uploaded by

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

Chapter 1 - Arrays & Strings

• Learning outcomes:

- Describe the idea of an array


- Apply declaration & initialization of arrays
- Perform accessing elements of an array
- Discuss & create multi-dimensional arrays

- Describe C++ string representation


- Apply declaration & initialization of string
- Practice reading strings from the keyboard
- Evaluate C++ standard library for string

1
Introduction
• Array

– a group of elements of the same type placed in contiguous memory


locations,

• under one common name or (same name).

– e.g., array mark to contain 5 integer values:


index
mark
int

• First: index=0, Last: index=N-1, where N is the array size.

– an array must be declared before it is used.

2
Cont’d…
• “Regular” arrays are blocks of non-dynamic memory:
– static entity (or have the same size throughout the program)

• its size must be determined when declared (before execution)

• Regular arrays (“arrays of known constant size”):


– size can be specified by a constant integer variable

• e.g., const int size=20; //size cannot be changed


int x[size];

• constant variables must be initialized when declared

4
Cont’d…
• To read or write to/from an array,
– often use for loop control structure

• E.g., for reading values from array mark[5]


for(int i=0; i<5; i++)
cout<<mark[i]; // to write cin>>mark[i];

• Often format I/O stream,


– using stream manipulators in <iomanip>

• e.g., setw() // for setting field widths

• Note: (i) no array to array assignments (ii) no bounds checking


8
Example 2

11
Multi-dimensional Arrays
• One dimensional (1D) arrays
– e.g., int x[10], char y[5]…etc.

• Multidimensional arrays (“arrays of arrays”)


– e.g., int a[3][4], … a[i][j]…[n]

• Most common: two dimensional (2D) arrays


– e.g., a[i][j] // have two subscripts

– can be considered as a table: rows & columns

• i specify row, j specify column


12
Cont’d…
• Trying to access mark[5], you may encounter
– “undefined behavior” (program can crash, freeze, random output …etc.)

• Like other variables, array elements can be:


– assigned or printout values

• e.g., mark[1]=75; cout<<mark[1];

– or perform operations (inside the subscript)

• e.g., int a=1; mark[a]=75;

int b; b=mark[a+2]; // same as b=mark[3]

mark [mark[a]]= mark[2] + 5;


7
Example 4

16
Activity 0 - Watch videos!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 9
Example 1

10
Example 2

11
Multi-dimensional Arrays
• One dimensional (1D) arrays
– e.g., int x[10], char y[5]…etc.

• Multidimensional arrays (“arrays of arrays”)


– e.g., int a[3][4], … a[i][j]…[n]

• Most common: two dimensional (2D) arrays


– e.g., a[i][j] // have two subscripts

– can be considered as a table: rows & columns

• i specify row, j specify column


12
Cont’d…

• To declare
– e.g., int x[3][4];
Column 0 Column 1 Column 2 Column 3

Row 0 a[0][0] a[0][1] a[0][2] a[0][3]

Row 1 a[1][0] a[1][1] a[1][2] a[1][3]

Row 2 a[2][0] a[2][1] a[2][2] a[2 ][3]

Column subscript

Array name
Row subscript

– referred as a “3 by 4” integer array

– the size of array x will be 3*4=12 elements

13
Cont’d…
• To initialize

– initializers are grouped by row in braces


a
1 2
• e.g., int a[2][2]={{1,2},{3,4}};
Row 0 Row 1 3 4

int b[][2]={{1},{3,4}};
b
1 0
• Referenced like array variable
3 4

– cout<<b[0][1]; // the default is 0; outputs 0


– cout<<b[][1]; // error message

14
Example 3

15
Cont’d…

• Input from keyboard,


– e.g., char str[5]; // declare char array str
cin>>str; // accept 5 characters

• cin>> stops at the first whitespace (or blank space)


• add NULL ('\0') character implicitly

• Input string exceed array size,


– modern C++: cin>> accept string above 5 char
• i.e., by getting some memory overwritten
– solution: cin>>setw(5)>>str; // setw()discard extra chars

25
Cont’d…

17
Activity 1 – Live poll!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 18
Discussion forum 1 – Hands-on exercise!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 19
Assignment 1 – Individual assignment!
Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 20
Cont’d…
char *strcpy(char *s1, const Copies the string s2 into the character
char *s2); array s1. The value of s1 is returned.
char *strncp(char *s1, const Copies at most n characters of the string s2
char *s2, size_t n); into the character array s1. The value of s1 is
returned.

char *strcat(char *s1, const Appends the string s2 to the string s1. The
char *s2); first character of s2 overwrites the
terminating null character of s1. The value of
s1 is returned.

char *strncat(char *s1, const Appends at most n characters of string s2 to


char *s2, size_t n); string s1. The first character of s2 overwrites
the terminating null character of s1. The value
of s1 is returned.

int strcmp(const char *s1, Compares the string s1 with the string s2.
const char *s2); The function returns a value of zero, less than
zero or greater than zero if s1 is equal to, less
than or greater than s2, respectively.

31
Cont’d…
int strncmp(const char *s1, const Compares up to n characters of the string
char *s2, size_t n); s1 with the string s2. The function returns
zero, less than zero or greater than zero if
s1 is equal to, less than or greater than s2,
respectively.
char *strtok(char *s1, const char A sequence of calls to strtok breaks
*s2); string s1 into “tokens”—logical pieces such
as words in a line of text—delimited by
characters contained in string s2. The first
call contains s1 as the first argument, and
subsequent calls to continue tokenizing the
same string contain NULL as the first
argument. A pointer to the current token is
returned by each call. If there are no more
tokens when the function is called, NULL is
returned.
size_t strlen(const char *s); Determines the length of string s. The
number of characters preceding the
terminating null character is returned.

32
String Initialization

• Initialization
– e.g., char color[5]="blue";
• create char array color with 5 elements
• add NULL ('\0') character at the end (color[4])

• Alternatively,
– e.g., char color[]={‘b’, ‘l’, ‘u’, ‘e’, ‘\0’};

• String
– an array of characters, NULL ('\0’) terminated.

23
Accessing Strings

• Individual element,
– e.g., color[0]=‘c’; // assign c to color[0]
cout<<color[2]; // output u

• Entire string
– e.g., cout<<color; // output clue

• print the characters until NULL is found


• No need to use for loop
– caution: do not work on other array types (e.g., int)

24
String Concatenation
• char *strcat(char *s1, const char *s2)
– append the copy of s2 to s1, plus the NULL character
• the first character of s2 replaces the NULL character of s1
• s1 must be large enough to hold s2, plus the NULL character
– return the value of s1

• char *strncat(char *s1, const char *s2, size_t n)


– append the first n number of characters of s2 to s1
• plus append NULL character at the end s1
– return the value of s1

35
Example 3

36
Activity 0 - Watch videos!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 27
Cont’d…
• int strcmp(const char *s1, const char *s2)
– compare string s1 against s2, character by character
• performs a binary comparison of the characters
– Return:
• zero (0), if s1 = s2
• negative value (-ve), if s1 < s2
• positive value (+ve), if s1 > s2

• int strncmp(const char *s1, const char *s2, size_t n)


– compare up to n number of characters of s1 against s2

38
Activity 2 – Live poll!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 29
Standard Library Functions for String

• Modern C++ also support C standard library functions,


– defined in <cstring>, for string manipulation

• Most commons, e.g.,


– strcpy() // copy string
– strcat() // concatenate strings
– strcmp() // compare strings
– Strtok() // tokenize string
– strlen() // get string length

30
Cont’d…
char *strcpy(char *s1, const Copies the string s2 into the character
char *s2); array s1. The value of s1 is returned.
char *strncp(char *s1, const Copies at most n characters of the string s2
char *s2, size_t n); into the character array s1. The value of s1 is
returned.

char *strcat(char *s1, const Appends the string s2 to the string s1. The
char *s2); first character of s2 overwrites the
terminating null character of s1. The value of
s1 is returned.

char *strncat(char *s1, const Appends at most n characters of string s2 to


char *s2, size_t n); string s1. The first character of s2 overwrites
the terminating null character of s1. The value
of s1 is returned.

int strcmp(const char *s1, Compares the string s1 with the string s2.
const char *s2); The function returns a value of zero, less than
zero or greater than zero if s1 is equal to, less
than or greater than s2, respectively.

31
String Length

• size_t strlen(const char *s)


– return the number of characters in a string (i.e., an integer value)

– length not include the NULL character

• Examples:
– char name[]="abebe";

• name has a length of 5 (chars)

– char str[100]="test string";

• str has a length of 11 (chars) // do not confuse with size of str


42
Example 6

43
Example 2

34
String Concatenation
• char *strcat(char *s1, const char *s2)
– append the copy of s2 to s1, plus the NULL character
• the first character of s2 replaces the NULL character of s1
• s1 must be large enough to hold s2, plus the NULL character
– return the value of s1

• char *strncat(char *s1, const char *s2, size_t n)


– append the first n number of characters of s2 to s1
• plus append NULL character at the end s1
– return the value of s1

35
Example 3

36
String Comparison

• Characters are represented as numeric codes


– strings are compared using numeric codes of characters

• Character codes (character sets)


– ASCII (American Standard Code for Information Interchange)1
• e.g., ASCII code for 'z’ is 122, and 90 for ‘Z’ (in decimal)
– EBCDIC (Binary Coded Decimal Interchange Code)2
– Both represent a character by 8-bits (i.e., 1 byte of memory)

1 https://theasciicode.com.ar/
2 https://en.wikipedia.org/wiki/EBCDIC
37
Cont’d…
• int strcmp(const char *s1, const char *s2)
– compare string s1 against s2, character by character
• performs a binary comparison of the characters
– Return:
• zero (0), if s1 = s2
• negative value (-ve), if s1 < s2
• positive value (+ve), if s1 > s2

• int strncmp(const char *s1, const char *s2, size_t n)


– compare up to n number of characters of s1 against s2

38
Example 4

39
String Tokenizing

• Tokenizing (uses char pointer, next chapter)


– break a string into tokens, separated by delimiting characters
– tokens usually are logical units, e.g., words separated by “ ”
• "This is my string“ = has 4 word-tokens

• char *strtok(char *s1, const char *s2)


– requires multiple function calls:
• 1st call, strtok(s1, delimiter)
• replace the first delimiter character of string s1 by NULL
• subsequent calls, strtok(NULL, delimiter)
– continue tokenizing the rest of string s1
40
Example 5

41
String Length

• size_t strlen(const char *s)


– return the number of characters in a string (i.e., an integer value)

– length not include the NULL character

• Examples:
– char name[]="abebe";

• name has a length of 5 (chars)

– char str[100]="test string";

• str has a length of 11 (chars) // do not confuse with size of str


42
Example 6

43
Discussion forum 2 – Homework!

Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 44
Quiz 1 – Self-evaluation!
Instruction:

– Please login to your Moodle1 course page to complete this activity.

1 https://elearning.amu.edu.et/ 45

You might also like