0% found this document useful (0 votes)
75 views56 pages

Lecture 6 - Arrays & Strings

This document discusses arrays and array programming in C++. It begins by defining simple and structured data types, with arrays given as an example of a structured type. It then covers one-dimensional arrays, including declaring and accessing array elements, common array operations using loops, and restrictions. Two-dimensional arrays and strings are also introduced. Key points covered include array initialization, searching and sorting arrays, and passing arrays to functions.

Uploaded by

abdi565453
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
0% found this document useful (0 votes)
75 views56 pages

Lecture 6 - Arrays & Strings

This document discusses arrays and array programming in C++. It begins by defining simple and structured data types, with arrays given as an example of a structured type. It then covers one-dimensional arrays, including declaring and accessing array elements, common array operations using loops, and restrictions. Two-dimensional arrays and strings are also introduced. Key points covered include array initialization, searching and sorting arrays, and passing arrays to functions.

Uploaded by

abdi565453
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/ 56

FACULTY OF TECHNOLOGY, ART AND DESIGN

Programming 2
MEK 3100

Instructor: Hadi Zahmatkesh


Email: hadi.zahmatkesh@oslomet.no

Lecture 6
Introduction

• A data type is called simple if variables of that type can store only
one value at a time

• A structured data type is one in which each data item is a collection


of other data items
Arrays
• Array: a collection of a fixed number of components wherein all of
the components have the same data type

• In a one-dimensional array, the components are arranged in a list


form

• Syntax for declaring a one-dimensional array:

intExp evaluates to a positive integer


Arrays (cont’d)
• Example:
int num[5];
Accessing Arrays Components
• General syntax:

where indexExp, called an index, is any expression whose value is


a nonnegative integer

• Index value specifies the position of the component in the array

• [] is the array subscripting operator

• The array index always starts at 0


Accessing Arrays Components
(cont’d)

int list[10];
Accessing Arrays Components
(cont’d)
Accessing Arrays Components
(cont’d)
Accessing Arrays Components
(cont’d)
Processing One-Dimensional
Arrays
• Some basic operations performed on a one-dimensional array are:
✓ Initializing
✓ Inputting data
✓ Outputting data stored in an array
✓ Finding the largest and/or smallest element

• Each operation requires ability to step through the elements of the


array

• Easily accomplished by a loop


Processing One-Dimensional
Arrays (cont’d)
• Consider the declaration
int list[100]; //array of size 100
int i;

• Using for loops to access array elements:


for (i = 0; i < 100; i++) //Line 1
//process list[i] //Line 2

• Example:
for (i = 0; i < 100; i++) //Line 1
cin >> list[i]; //Line 2
Processing One-Dimensional
Arrays (cont’d)
Processing One-Dimensional
Arrays (cont’d)
Array Index Out of Bounds
• If we have the statements:
double num[10];
int i;

• The component num[i] is valid 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
✓Otherwise, we say the index is out of bounds

• In C++, there is no guard against indices that are out of bounds


Array Initialization During
Declaration

• Arrays can be initialized during declaration


• In this case, it is not necessary to specify the size of the array
• Size determined by the number of initial values in the braces

• Example:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};
Partial Initialization of Arrays
During Declaration
• The statement:
int list[10] = {0};
declares list to be an array of 10 components and initializes all
of them to zero

• The statement:
int list[10] = {8, 5, 12};
declares list to be an array of 10 components, initializes
list[0] to 8, list[1] to 5, list[2] to 12 and all other
components are initialized to 0
Partial Initialization of Arrays
During Declaration (cont’d)
• The statement:
int list[] = {5, 6, 3};
declares list to be an array of 3 components and initializes
list[0] to 5, list[1] to 6, and list[2] to 3

• The statement:
int list[25]= {4, 7};
declares an array of 25 components; initializes list[0] to 4
and list[1] to 7; all other components are initialized to 0
Some Restrictions on Array
Processing
• Consider the following statements:

• C++ does not allow aggregate operations on an array:

• Solution:
Some Restrictions on Array
Processing (cont’d)
• The following is illegal too:

• Solution:

• The following statements are legal, but do not give the desired
results:
Arrays as Parameters to
Functions
• Arrays are passed by reference only
• The symbol & is not used when declaring an array as a formal
parameter
• The size of the array is usually omitted
• If provided, it is ignored by the compiler
Constant Arrays as Formal
Parameters
Base Address of an Array and
Array in Computer Memory
• The base address of an array is the address, or memory location of
the first array component

• If list is a one-dimensional array, its base address is the address


of list[0]

• When we pass an array as a parameter, the base address of the


actual array is passed to the formal parameter
Base Address of an Array and Array
in Computer Memory (cont’d)
Functions Cannot Return a
Value of the Type Array

• C++ does not allow functions to return a value of the type array
Searching an Array for a
Specific Item
• Sequential search or linear search
✓Searching a list for a given item

✓Starting from the first array element

✓Compare searchItem with the elements in the array

✓Continue the search until either you find the item or no more data
is left in the list to compare with searchItem
Searching an Array for a
Specific Item (cont’d)
Sorting
• Selection sort: rearrange the list by selecting an element in the list
and moving it to its proper position.

• This algorithm finds the location of the smallest element in the


unsorted portion of the list and moves it to the top of the unsorted
portion of the list.

• The first time, we locate the smallest item in the entire list. The
second time, we locate the smallest item in the list starting from the
second element in the list, and so on.
Sorting (cont’d)

First iteration Second iteration


C-Strings (Character Arrays)
• Character array: an array whose components are of type char

• C-strings are null-terminated ('\0') character arrays

• Example:
✓'A' is the character A
✓"A" is the C-string A
o "A" represents two characters, 'A' and '\0‘
C-Strings (Character Arrays)
(cont’d)
• Consider the statement
char name[16];

• Since C-strings are null terminated and name has 16 components,


the largest string that it can store has 15 characters

• If you store a string of length, say 10 in name


✓The first 11 components of name are used and the last five are
left unused
C-Strings (Character Arrays)
(cont’d)
• The statement
char name[16] = "John";

declares an array name of length 16 and stores the C-string


"John" in it

• The statement
char name[] = "John";

declares an array name of length 5 and stores the C-string


"John" in it
C-Strings (Character Arrays)
(cont’d)
String Comparison
• C-strings are compared character by character using the collating
sequence of the system

• If we are using the ASCII character set


✓ "Air" < "Boat"
✓ "Air" < "An"
✓ "Bill" < "Billy"
✓ "Hello" < "hello"
String Comparison (cont’d)
String Input
• cin >> name; stores the next input C-string into name
• To read strings with blanks, use get:
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
String Output
• cout << name; outputs the content of name on the screen
✓<< 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

o << continues to output data from memory adjacent to name until '\0'
is found
Two- and Multidimensional
Arrays
• Two-dimensional array: collection of a fixed number of
components (of the same type) arranged in two dimensions
• Sometimes called matrices or tables

• Declaration syntax:

where intexp1 and intexp2 are expressions yielding


positive integer values, and specify the number of rows and the
number of columns, respectively, in the array
Two- and Multidimensional
Arrays (cont’d)
Accessing Array Components
• Syntax:

where indexexp1 and indexexp2 are expressions yielding


nonnegative integer values, and specify the row and column position
Two-Dimensional Array
Initialization During Declaration
• Two-dimensional arrays can be initialized when they are declared:

• Elements of each row are enclosed within braces and separated


by commas

• All rows are enclosed within braces

• For number arrays, if all components of a row aren’t specified,


unspecified ones are set to 0
Two-Dimensional Array Initialization
During Declaration (cont’d)
Processing Two-Dimensional
Array
• Ways to process a two-dimensional array:
✓Process the entire array
✓Process a particular row of the array, called row processing
✓Process a particular column of the array, called column
processing

• Each row and each column of a two-dimensional array is a one-


dimensional array
✓To process, use algorithms similar to processing one-dimensional
arrays
Processing Two-Dimensional
Array (cont’d)
Initialization
• To initialize row number 4 (i.e., fifth row) to 0:

• To initialize the entire matrix to 0:


Print

• To output the components of matrix:


Input

• To input data into each component of matrix:


Sum by Row
• To find the sum of row number 4 of matrix:

• To find the sum of each individual row:


Sum by Column

• To find the sum of each individual column:


Largest Element in Each Row
and Each Column
Passing Two-Dimensional Arrays
as Parameters to Functions
• Two-dimensional arrays can be passed as parameters to a function
✓Pass by reference
o Base address (address of first component of the actual parameter) is
passed to formal parameter

• Two-dimensional arrays are stored in row order

• When declaring a two-dimensional array as a formal parameter, can


omit size of first dimension, but not the second
Passing Two-Dimensional Arrays as
Parameters to Functions (cont’d)
Arrays of Strings
• Strings in C++ can be manipulated using either the data type string
or character arrays (C-strings)

• On some compilers, the data type string may not be available in


Standard C++ (i.e., non-ANSI/ISO Standard C++)
Arrays of Strings and the
string Type

• To declare an array of 100 components of type string:


string list[100];

• Basic operations, such as assignment, comparison, and


input/output, can be performed on values of the string type

• The data in list can be processed just like any one-dimensional


array
Arrays of Strings and the C-String
Type (Character Arrays)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy