Chapter 4-Arrays and Strings
Chapter 4-Arrays and Strings
Array
• Array stores a fixed-size sequential collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
• All arrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the highest address to the last
element.
• An array is a list of elements of the same type
• An array is declared by base type (the type of each until of data) and number of units of
memory (how much data).
• An array
• a single name for a collection of data values
• all of the same data type
• subscript notation to identify one of the values
• Accessing each of the values in an array
• Usually a for loop
1
Array Applications
• Given a list of test scores, determine the maximum and minimum scores.
• Read in a list of student names and rearrange them in alphabetical order
(sorting).
• Given the height measurements of students in a class, output the names of those
students who are taller than average.
2
One Dimensional Array
• Array Declaration
• Syntax:
type array-name[array_size];
• The array elements are all values of the type <type>.
• The size of the array is indicated by <array_size>, the number of elements in the array.
• <array_size> must be an int constant or a constant expression. Note that an array
can have multiple dimensions.
• This declares a variable called <array-name> which contains <size> elements of type <type>
• The elements of an array can be accessed as: array-name[0],…array-name[size-1]
Example:
int a[100]; //a is a list of 100 integers, a[0], a[1], …a[99]
double b[50];
char c[10];
3
Accessing Array Elements
• The first element in an array in C++ always has the index 0,
and if the array has n elements the last element will have the
index n-1.
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
4
Subscripting
5
Subscripting
Ar[3] = 1;
int x = Ar[3];
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8]Ar[9]
6
Subscripting Example 1
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
} 7
8
Array Initialization
int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1,
0};
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 6 5 4 3 2 1 0
Ar[3] = -1;
0 1 2 3 4 5 6 7 8 9
Ar 9 8 7 -1 5 4 3 2 1 0
9
Printing arrays
To print an array, you have to print each element in the array using a
loop like the following:
10
Copying Arrays
double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}
12
Finding the Largest Element
Use a variable named max to store the largest element. Initially max
is myList[0]. To find the largest element in the array myList, compare
each element in myList with max, update max if the element is
greater than max.
13
Finding the smallest index of the largest element
void main() {
int i, a[100], n;
i=0; n=100;
while (i<n) {
cout << “Input element “ << i << “: ”;
cin >> a[i];
i = i+1;
}
//do somehing with it ..
}
15
Problems
Write a C++ program to read a sequence of (non-negative) integers from the user ending with a negative
integer and write out
• Example:
• The user enters: 3, 1, 55, 89, 23, 45, -1
• Your program should compute the average of {3, 1, 55, 89, 23, 45} etc
16
Array Index Out of Bounds
17
Array Index Out of Bounds (continued)
18
Two-Dimensional Arrays
19
Two-Dimensional Arrays (continued)
• The two expressions intexp1 and intexp2
specify the number of rows and the number of
columns, respectively, in the array
20
21
Accessing Array Components
• The syntax to access a component of a two-dimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are expressions yielding
nonnegative integer values
• indexexp1 specifies the row position and indexexp2 specifies
the column position
22
23
Initialization
• Like one-dimensional arrays
• Two-dimensional arrays can be initialized when they
are declared
• To initialize a two-dimensional array when it is
declared
1. Elements of each row are enclosed within braces and
separated by commas
2. All rows are enclosed within braces
3. For number arrays, if all components of a row are not
specified, the unspecified components are initialized
to zero
24
Initialization
theArray[5][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
{13, 14,15}
};
25
Example of multidimensional array
#include<iostream.h>
void main(){
int SomeArray[5][2] = {{0,0},{1,2}, {2,4},{3,6},
{4,8}}
for ( int i=0; i<5; i++)
for (int j = 0; j<2;j++)
{
cout<<"SomeArray["<<i<<"]["<<j<<'']: '';
cout<<endl<<SomeArray[i][ j];
}
}
26
27
28
29
30
31
C++ Strings (Character Arrays)
• Character array - an array whose components are of type char
33
C++ Strings (Character Arrays) (continued)
A string variable s1 could be declared as follows:
char s1[10];
34
C++ Strings (Character Arrays) (continued)
• Strings can be initialized at the time of declaration just as other variables are initialized. For
example:
char s1[] = "example";
char s2[20] = "another example"
would store the two strings as follows:
s1 |e|x|a|m|p|l|e|\0|
s2 |a|n|o|t|h|e|r| |e|x|a|m|p|l|e|\0|?|?|?|?|
• The statement
char name[16] = "John";
declares a string variable name of length 16 and stores "John" in it
• The statement
char name[] = "John";
declares a string variable name of length 5 and stores "John" in it
35
Reading and Writing Strings
• String Output
• The statement cout << name; outputs the content of name on the screen
• The insertion operator << continues to write the contents of name until it
finds the null character
• If name does not contain the null character, then we will see strange output:
<< continues to output data from memory adjacent to name until '\0' is
found
Sysntax:
cin.get(string_variable,max_size)
39
using namespace std;
system("pause") or input loop */
40
Reading and Writing Strings (continued)
• To read strings with blanks, use the get function with
an input stream variable, such as cin:
cin.get(str, m+1);
41
• Reading multiple lines using:
• cin.get(string_variable,Max_size,terminator_character)
#include <iostream>
using namespace std;
42
43
String Comparison
• C-strings are compared character by character
using the collating sequence of the system
• If we are using the ASCII character set
1. The string "Air" is smaller than the string "Boat"
2. The string "Air" is smaller than the string "An"
3. The string "Bill" is smaller than the string
"Billy"
4. The string "Hello" is smaller than "hello"
44
45
• Concatenating strings
• In C++ the + operator cannot normally be used to concatenate string,
as it can in some languages such as BASIC; that is you can't say
• Str3 = str1 + str2;
• You can use strcat() or strncat
• strcat(destination, source);
• The first character of the source string is copied to the location of the
terminating null character of the destination string.
• The destination string must have enough space to hold both strings and a
terminating null character.
46
#include <iostream>
#include<cstring>
using namespace std;
int main(int argc, char** argv) {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
char str2[]="xyz";
strcat(str1,str2);
cout<<str1<<endl;
str1[4]='\0';
cout << str1 << endl;
return 0;
}
47
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
49
Pointers
• A pointer is simply the address of a memory location and provides an
indirect way of accessing data in memory. A pointer variable is defined to
‘point to’ data of a specific type. For example:
int *ptr1; // pointer to an int
char *ptr2; // pointer to a char
• The value of a pointer variable is the address to which it points. For
example, given the definitions
int num;
• we can write:
ptr1 = #
50
• Pointer Arithmetic
char *str = "HELLO";
int nums[] = {10, 20, 30, 40};
int *ptr = &nums[0]; // pointer to first element
51
int num[]={10,20,30,40};
cout<<"Sizeof
int :"<<sizeof(int)<<endl;
int *p1=&num[0];
cout<<"num[0]:"<<*p1<<endl;
for(int i=0;i<4;i++)
cout<<*p1++<<endl;
52