0% found this document useful (0 votes)
73 views42 pages

Fundamentals of Programming (In C++) BAIS4101

This document discusses arrays and strings in C++. It begins by defining arrays as collections of variables of the same type referred to by a common name. One-dimensional arrays are described as lists, with examples provided. Accessing array elements using indexes is explained. The representation of arrays in contiguous memory locations is also covered. The document then discusses strings as character arrays terminated by a null character. Functions for reading, comparing, concatenating and manipulating strings are provided as examples. Two-dimensional arrays are introduced as lists of one-dimensional arrays.

Uploaded by

sami damtew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views42 pages

Fundamentals of Programming (In C++) BAIS4101

This document discusses arrays and strings in C++. It begins by defining arrays as collections of variables of the same type referred to by a common name. One-dimensional arrays are described as lists, with examples provided. Accessing array elements using indexes is explained. The representation of arrays in contiguous memory locations is also covered. The document then discusses strings as character arrays terminated by a null character. Functions for reading, comparing, concatenating and manipulating strings are provided as examples. Two-dimensional arrays are introduced as lists of one-dimensional arrays.

Uploaded by

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

Fundamentals of Programming (in C++)

BAIS4101

Chapter :
Arrays and Strings

09/03/2020 1
Outline of Topics
Arrays
One-Dimensional Arrays
Accessing Array Elements
Representation of Arrays in Memory
Strings
Reading a String from the Keyboard
Some C++ Library Functions for Strings
Using the Null

09/03/2020 2
5.1. Array
Array is a collection of variables of the same type
that are referred to by a common name.
Arrays offer a convenient means of grouping together
several related variables, in one dimension or more
dimensions:
Ex: product part numbers:
int part_numbers[] = {123, 326, 178, 1209};
student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};
09/03/2020 3
5.1. Array
names:
char names[][40] =
{“Peter”, “Mary”, “Lisa”, “John”, "George-
Simon"};
3D coordinates:
vector coordinates[4][3] =
{{0, 0, 0},
{1, 0, 1},
{1, 0, 5}
{4, 7, 9}};

09/03/2020 4
5.1. Array
One-Dimensional Arrays

A one-dimensional array is a list of related variables.


The general form of a one-dimensional array
declaration is:
type variable_name[size];
type: base type of the array, determines the data type of
each element in the array.
size: how many elements the array will hold
variable_name: the name of the array

09/03/2020 5
5.1. Array
Examples:
int sample[10];
float float_numbers[100];
char last_name[40];

Accessing Array Elements


An individual element within an array is accessed by use of an
index.
An index describes the position of an element within an array.
Note : In C++ the first element has the index zero.

09/03/2020 6
5.1. Array
Example: Load the array sample with the numbers 02 through 92
#include <iostream.h>
int main()
{
int sample[10]; // reserves for 10 integers
int t;
// initialize the array
for(t=0; t<10; ++t) sample[t] = t*t;
// display the array
for(t=0; t<10; ++t)
cout << sample[t] << ‘ ‘;
return(0);
} 7
09/03/2020
5.1. Array
Representation of Arrays in Memory
In C++, any array is mapped to a contiguous memory
location.
All memory elements reside next to each other.
The lowest address corresponds to the first element,
and the highest address to the last element.

09/03/2020 8
5.1. Array
Example:
int a[8];
int j;
for(j=0; j<8; j++) a[j] = 7-j;
Then the memory representation of array a
looks like this:

09/03/2020 9
5.1. Array
Example: Finding the Maximum
#include <iostream.h>
int main()
{
int i, max = 0;
int list[100]; // initialize the array with random values
for(i=0; i<100; i++) list[i] = rand(); // find maximum value
for(i=0; i<100; i++)
if(max < list[i]) max = list[i];
cout << “Maximum value: “ << max;
return(0);
}
09/03/2020 10
5.1. Array
No Array-to-Array Assignments
You cannot assign one array to another in C++.
The following is illegal:
int a[10], b[10];
// do something
// assign all elements of array b to array a
a = b; // error -- illegal
Instead, you have to do the assignments for each element:
int i;
// assign all elements of array b to array a
for(i=0; i<10; i++) a[i] = b[i];

09/03/2020 11
5.1. Array
No Bounds Checking
C++ performs no bounds checking on arrays.
Nothing will stop you from overrunning the end of an
array:
You will assign values to some other variables´ data!!!
You might even write into a piece of the program
code!!!

09/03/2020 12
5.1. Array
For example, you can compile and run the following
program, even though the array crash is being
overrun:
// An incorrect program. Do not execute!
int main()
{
int crash[10], i;
for(i=0; i<100; i++) crash[i] = i;
return(1);
}

09/03/2020 13
5.2. String
Strings
The most common use for one-dimensional arrays is to
store strings of characters.
In C++, a string is defined as a character array
terminated by a null symbol (‘\0’).

To declare an array str that could hold a 10-character


string, one would write:
char str[11];
Specifying the size as11 makes room for the null at the
end of the string.
09/03/2020 14
5.2. String
Some examples of string constants in C++ are:
"hello there"
"I like C++."
"#$%§@@+*"
"\""
"\"\""
"\\"
""
The null string, ““, only contains the null terminator
and represents the empty string.

09/03/2020 15
5.2. String
Reading a String from the Keyboard
How to read a string entered from the keyboard?
Make an array, that will receive the string, the target of
a cin stream.
The following program reads (part of) a string entered
by the user:

09/03/2020 16
5.2. String
#include <iostream.h>
int main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return(0);
}
09/03/2020 17
5.2. String
Problem: Entering the string “This is a test”, the above
program only returns “This”, not the entire sentence.
Reason: The C++ input/output system stops reading a
string when the first whitespace character is
encountered.
Solution: Use another C++ library function,
gets().

09/03/2020 18
5.2. String
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: “;
gets(str); // read a string from the keyboard
cout << “Here is your string: “;
cout << str << endl;
return(0);
} 19
09/03/2020
5.2. String
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions.
The most common are:

09/03/2020 20
5.2. String
strcpy(to_string,from_string) — String Copy:
#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}
int main() 21
09/03/2020
5.2. String
strlen(string) — String Length strlen(str) returns the
length of the string pointed to bystr, i.e., the number
of characters excluding the null terminator.
#include <iostream.h>
#include <cstdio.h>
#include <cstring.h>
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str);
cout << “Length is: “ << strlen(str);
return(0);}
09/03/2020 22
5.2. String
strcat(string_1, string_2) — Concatenation of Strings
The strcat() function appends s2 to the end of s1. String s2 is
unchanged.
// includes ...
int main()
{
char s1[21], s2[11];
strcpy(s1, “hello”);
strcpy(s2, “ there”);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return(0); } 23
09/03/2020
5.2. String
strcmp( string_1, string_2) — Comparison of Strings
The strcmp(str_1, str_2) function compares two strings and
returns the following result:
• str_1 == str_2 : 0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
The strings are compared lexicographically (i.e., according to
dictionary order):
a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca <
abd < ...

09/03/2020 24
5.2. String
// Comparing strings
#include <iostream.h>
#include <cstring.h>
#include <cstdio.h>
int main()
{
char str[80];
cout << “Enter password: “;
gets(str);
if(strcmp(str, “password”)) {
// strings differ
cout << “Invalid password.\n”;}
else cout << “Logged on.\n”;
return(0);
} 25
09/03/2020
5.2. String
Using the Null Terminator
Operations on strings can be simplified using the fact that all strings
are null-terminated.
// Convert a string to uppercase
// ... includes ...
int main()
{
char str[80];
int i;
strcpy(str, “this is a test”);
for(i=0; str[i]; i++)
str[i] = toupper(str[i]);
cout << str; return(0); }

09/03/2020 26
5.3. Two Dimensional Array
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
To declare a two-dimensional integer array
two_dim of size 10,20 we would write:
int matrix[3][4];
This corresponds to a table with 3 rows and 4 columns (for
example).

09/03/2020 27
5.3. Two Dimensional Array
We can generate the array above by using this program:
#include <iostream.h>
int main()
{
int row=3, col=4;
int matrix[row][col];
for(row=0; row < 3; ++row) {
for(col=0; col < 4; ++col) {
matrix[row][col] = (row*4)+ col +1;
cout << matrix[row][col] << ‘ ‘;
}
cout << ‘\n’;
}
return(0);}

09/03/2020 28
5.3. Two Dimensional Array
Memory Allocation for Two-Dimensional Arrays
Storage for all array elements is determined at compile
time.
The memory used to hold an array is required the entire
time that the array is in existence.
The following formula determines the number of bytes
of memory that will be allocated:
bytes = rows * columns * number_of_bytes_in_type
For example, an integer array (with two-byte integers)
with
dimensions 100,100 would require 100 * 100 * 2 =
20,000 bytes.
09/03/2020 29
5.3. Two Dimensional Array
Multidimensional Arrays
C++ allows arrays with more than two dimensions.
The general form of an N-dimensional array declaration is:
type array_name[size_1] [size_2] … [size_N];
For example, the following declaration creates a 4 x 10 x 20
character array, or a matrix of strings:
char string_matrix[4][10][20];
This requires 4 * 10 * 20 = 800 bytes.
If we scale the matrix by 10, i.e. to a 40 x 100 x 20 array, then
80,000 bytes are needed.

09/03/2020 30
5.3. Two Dimensional Array
Array Initialization
The general form of array initialization is similar to that of other
variables:
type array-name[size] = {list-of-values};
The list-of-values has to be a comma-separated list of constants
that are type-compatible with the base type of the array.
In the following example, a 10-element float array is initialized
with the numbers 1.0 through 10.0:
float i[10] = {1.,2.,3.,4.,5.,6,7,8,9,10};
Therefore, i[0] will have the value1.0, and i[9] will have the
value10.0.
.

09/03/2020 31
5.3. Two Dimensional Array
Character Array Initialization
Character arrays that will hold strings allow a shorthand
initialization that takes this form:
char array-name[size] = “string”;
For example, the following code fragment initializes str to the
phrase “hello”:
char str[6] = “hello”;
This is the same as writing
char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
Remember that one has to make sure to make the array long
enough to include the null terminator.

09/03/2020 32
5.3. Two Dimensional Array
Multi-Dimensional Array Initialization
Multi-dimensional arrays are initialized the same way as one
dimensional arrays.
For example, the following code fragment initializes an array
squares with the numbers 1 through 10 and their squares:

09/03/2020 33
5.3. Two Dimensional Array
For better readability, especially for multi-dimensional arrays,
one can use subaggregate grouping by adding braces
accordingly. The same declaration as above can also be
written as:

09/03/2020 34
5.3. Two Dimensional Array
The following program uses the squares array to find the root of
a number entered by the user.
#include <iostream.h> // declaration of squares array goes here
int main()
{
int i, j;
cout << “Enter a number 1<=i<=100: “;
cin >> i; // look up i
for(j=0; j<10; j++)
if(squares[j][1] == i) {
cout << "Root: " << squares[j][0];
return(0);}
cout << "No integer root."; return(0);\
}
09/03/2020 35
5.3. Two Dimensional Array
Arrays of Strings
An array of strings is a special form of a two-dimensional array.
• The size of the left index determines the number of strings.
• The size of the right index specifies the maximum length of
each string.
For example, the following declares an array of 30 strings, each
having a maximum length of 80 characters (with one extra
character for the null terminator):
char string_array[30][81];

09/03/2020 36
5.3. Two Dimensional Array
For accessing an individual string, one simply specifies only the
left index:
firstString = string_array[0];
sixthString = string_array[5];
The following example calls the gets() function with the third
string in the array:
gets(string_array[2]);

09/03/2020 37
Lab Exercise(Mon)

1) What is the effect of pre and post increment operations in Arithmetic


operations? Explain the difference between the following codes.
 a)
int a=4, b=3, c;
c=++a - b;
cout<<a<<'\t'<<b<<'\t'<<c;
 
 b)
int a=4, b=3, c;
c = a++ - b;
cout<<a<<'\t'<<b<<'\t'<<c;
 

09/03/2020 38
Lab Exercise(Mon)

09/03/2020 39
Lab Exercise(Wed)

1) What is the effect of pre and post increment operations in Arithmetic


operations? Explain the difference between the following codes.
 a)
int a=5, b=4, c;
c = ++a - b;
cout<<a<<'\t'<<b<<'\t'<<c;
 
 b)
int a=5, b=4, c;
c = a++ - b;
cout<<a<<'\t'<<b<<'\t'<<c;
 

09/03/2020 40
Lab Exercise(Wed)

09/03/2020 41
Next Topic

Function

09/03/2020 42

You might also like