0% found this document useful (0 votes)
47 views52 pages

Chapter 4-Arrays and Strings

The document discusses arrays in C++ including one and multi-dimensional arrays. It covers declaring, initializing, accessing elements and common operations like summing elements. Arrays allow storing multiple values of the same type and accessing via indices.

Uploaded by

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

Chapter 4-Arrays and Strings

The document discusses arrays in C++ including one and multi-dimensional arrays. It covers declaring, initializing, accessing elements and common operations like summing elements. Arrays allow storing multiple values of the same type and accessing via indices.

Uploaded by

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

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.

// array of 10 uninitialized ints


int Ar[10];

0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --

4
Subscripting

• Declare an array of 10 integers:


int Ar[10]; // array of 10 ints
• To access an individual element we must apply a subscript to
array named Ar.
• A subscript is a bracketed expression.
• The expression in the brackets is known as the index.
• First element of array has index 0.
Ar[0]
• Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
• Last element has an index one less than the size of the array.
Ar[9]
• Incorrect indexing is a common error.

5
Subscripting

// array of 10 uninitialized ints


int Ar[10];

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

int primes[ ] = {1, 2, 3, 5, 7, 11, 13};

9
Printing arrays

To print an array, you have to print each element in the array using a
loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)


{
cout << myList[i] << " ";
}

10
Copying Arrays

Can you copy array using a syntax like this?


list = myList;

This is not allowed in C++. You have to copy individual elements


from one array to the other as follows:

for (int i = 0; i < ARRAY_SIZE; i++)


{
list[i] = myList[i];
}
11
Summing All Elements
Use a variable named total to store the sum. Initially total is 0.
Add each element in the array to total using a loop like this:

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.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max) max = myList[i];
}

13
Finding the smallest index of the largest element

double max = myList[0];


int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
} 14
Array example
//Read 100 numbers from the user
#include <iostream.h>

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

• the average of the numbers


• the smallest number
• the largest number
• the range of the numbers (largest - smallest)

• 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

• If we have the statements:


double num[10];
int i;
• The component num[i] is a valid index if i = 0, 1,
2, 3, 4, 5, 6, 7, 8, or 9
• The index of an array is in bounds if the index >=0
and the index <= ARRAY_SIZE-1

17
Array Index Out of Bounds (continued)

• If either the index < 0 or the index > ARRAY_SIZE-1


• then we say that the index is out of bounds

• There is no guard against indices that are out of bounds


• C++ does not check if the index value is within range

18
Two-Dimensional Arrays

• Two-dimensional Array: a collection of a fixed


number of components arranged in two dimensions
• All components are of the same type
• The syntax for declaring a two-dimensional array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding
positive integer values

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

• Two-dimensional arrays are sometimes called


matrices or tables

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

int 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

• String - a sequence of zero or more characters enclosed in double


quote marks

• C++ stings are null terminated (‘\0’)

• The last character in a string is the null character

• Any array of character can be converted into string type in C++ by


appending this special character at the end of the array sequence.
32
C++ Strings (Character Arrays) (continued)
• There is a difference between 'A' and "A"
• 'A' is the character A
• "A" is the string A

• Because strings are null terminated, "A" represents two characters,


'A' and '\0‘
• Similarly, "Hello" contains six characters, 'H', 'e', 'l', 'l',
'o', and '\0'

33
C++ Strings (Character Arrays) (continued)
A string variable s1 could be declared as follows:
char s1[10];

• Consider the statement


char name[16];
• Because C++ strings are null terminated and name has sixteen components
• The largest string that can be stored in name is 15
• If you store a string of length, say 10 in name
• The first 11 components of name are used and the last 5 are left unused

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

cout << "The string s1 is " << s1 << endl;


would print
The string s1 is example
36
Reading and Writing Strings
• String Input
• Aggregate operations are allowed for string input

• cin >> name; stores the next input string in name

• Strings that contain blanks cannot be read using the


extraction operator >>

• The input stream cin reads a string up


space character.

• Forexample, using a signle cin we cannot


read the full name of a student(Abebe
Kebede)
37
#include <iostream>
using namespace std;

int main(int argc, char** argv) {


char fullname[20];
cout<<"Enter your name :";
cin>>name;
cout<<"your name is :"<<fullname<<endl;
return 0;
}

Enter your name: Abebe Kebede


Your name is :Abebe
38
Reading text containing blanks using cin.get() function

Sysntax:
cin.get(string_variable,max_size)

39
using namespace std;
system("pause") or input loop */

int main(int argc, char** argv) {


char fullname[20];
cout<<"Enter your name :";
cin.get(fullname,20);
cout<<"your name is :"<<fullname<<endl;
return 0;
}

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

• Stores the next m characters into str but the


newline character is not stored in str

• If the input string has fewer than m characters, the


reading stops at the newline character

41
• Reading multiple lines using:
• cin.get(string_variable,Max_size,terminator_character)
#include <iostream>
using namespace std;

int main(int argc, char** argv) {


char text[100];
cout<<"Enter some text and terminate with $ character :";
cin.get(text,100,'$');
cout<<"The text is:"<<text<<endl;
return 0;
}

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;

char str2[] = "xyz";


strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl; 48
• The function strncat is like strcat except that it copies only a specified
number of characters.
• strncat(destination, source, int n);
• It may not copy the terminating null character.

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 = &num;

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

You might also like