0% found this document useful (0 votes)
8 views

PF Lecture 20 22 Arrays

Uploaded by

fahadnae123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PF Lecture 20 22 Arrays

Uploaded by

fahadnae123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

CS 1002 Programming Fundamentals

Lecture 21 Oct 2022

Arrays
Data types

Single pieces of information


• one integer – int
• one symbol – char
• one truth value – bool
Multiple pieces of information
• group of characters – string
• group of a single type – array

2
Array Declaration
An array is a list containing
• a fixed number of entries AND
• all entries are the same type
Syntax:
type name [ numelements ];
Examples:
int grades[5]; // declares an array of 5 ints
float hoursWorked[7]; //An array of 7 floats

3
More on Arrays, proper C++
• An array can be made from ANY type.
bool answers[5];
• An array has a positive upper bound.
char alphabet[26];
• An array upper bound must be a constant.
int arrayOfOne[1];
• An array lower bound always starts at 0.

4
Zero-indexing

• To access an element, we use an index in [ ].


• An array with n elements is accessed with indices
0 through n-1
float dailyTemperatures[365];

• So…
cout << dailyTemperatures[4] ;

Actually accesses fifth element of the


dailyTemperatures array!
5
Example Array and Terms
int grades[5]; // subscripts 0..4

Entries: 87 81 75 93 46
Index: 0 1 2 3 4

Synonyms: index = subscript


entry = element = cell

The first entry is at index 0.


Now you know why my for loops start with 0.

6
Example Array and Terms
int grades[5]; // subscripts 0..4

Entries: 87 81 75 93 46
Index: 0 1 2 3 4

One entry: grades[ 2 ] = 88; // overwrites 75

Commonly said: 'grades sub 1'


which means grades[1]
(also sometimes said: 'grades of 1')

7
Example Array Initialization
int grades[5]; // subscripts 0..4

Entries: 87 81 75 93 46
Index: 0 1 2 3 4

Initializing inside a program:

for (int j=0; j < 5; j++)


grades[ j ] = 100; // everyone gets 100!

8
Other Array Initializations
• Initializing an array when declared:
char LetterGrades[3]={'A', 'B', 'C'};

int scores[6]={84,91,98,57,72,85};
• Array declared larger than #values:
float heights[26]={5.5, 4.9, 6, 4.5};
//Un-filled slots will default to zero
• Implicit Array sizing:
float heights[ ]={5.5, 4.9, 6, 4.5};

9
Other Array Initializations
• Implicit Array sizing:
int grades[ ]={92,89,75,60,92,-1};
System knows # elements. Do you?

How to make a loop if you don't?


Have a special terminating value as the last
element also known as sentinel value.
Example: Grades are 0 to 100
Value = -1
10
Array Initialization from User
• Read from the user:
// read into nextval but can read into myIntArray[x]
int nextval;
for(int x=0; x< MAXENTRIES; x++)
{
cout << "Next Number? " ; // optional
cin >> nextval;
myIntArray [x] = nextval;
}
11
Print & Format
cout << "grades[" << i << "]=" << grades[i] << endl;
grades[4]=92
#include <iomanip> // necessary to use setw
Print Spacing : setw(N) // set width for next value
printed (not just array elements)

Example:
cout << 'X' << setw(5) << grades[4] << 'X' << endl;
X 92X //3 spaces between the X and 9
12
Memory allocation
int scores[10];
Variable Byte Address Value
Declaration of array with scores[0] 4902340 87

n elements takes scores[1] 4902344 93


contiguous* chunks of scores[2] 4902348 62
memory to hold each of scores[3] 4902352 87
the n elements scores[4] 4902356 83
scores[5] 4902360 91
scores[6] 4902364 78
* contiguous: sharing a
common border; touching. In scores[7] 4902368 50
computers, typically sequential scores[8] 4902372 95
as well scores[9] 4902376 85
13
Declaration Examples

Array must* be declared with constant number


of entries

const int classSize=26;


char grades[classSize];
float heights[50];
char greeting[]= "How are you?"

14
Find the Errors
int measurements[-5]; // is this legal?

float readings[4.5]; // how about this?

int size;
string names[size]; // what happens here?

double array[0]; // how about here?

15
Arrays and loops

'for loops' are well-structured to handle arrays

const int classSize=26;


char grades[classSize];
for(int i=0; i< classSize; i++){
cout << grades[i] << endl;
}

16
Can print less than the whole array

What if we only want to print the first half of the


class?

const int classSize=26;


char grades[classSize];
int sizeToPrint = classSize/2;
for(int i=0; i< sizeToPrint; i++){
cout << grades[i] << endl;
}
17
What does this code do?
int a[5]={1,3,6,4,2};
cout << a[3] << endl;

int i=1;
while(i<4) {
cout << a[i+1]-a[i] << endl;
i++;
}
18
What does this code do?
int a[5]={1,3,6,4,2};
int b[5], bNextFreeIndex=0;

int i=0;
while(i<4) {
if (a[i]>3) {
b[bNextFreeIndex]=a[i];
bNextFreeIndex++;
}
i++;
} 19
Out-of-range indexing
• An index value not allowed by array declaration
is “out of range”
char a[10];
cin >> a[10]; // out of range!

• Out-of-range index produces no compiler error,


but can cause serious program problems
– Reading/writing incorrect memory locations

20
Out-of-range indexing

int scores[4]={1,2},
idNum;
idNum=34253; ???
scores[5]=12; ???
scores[0] 1
cout << idNum; scores[1] 2
scores[2] 0
scores[3] 0
???
idNum 34253 12
??? 21
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

22
Review
• What is an Array?
• What is the syntax for declaring an array?
• What is required to define the upper bound?
• Define element, index, subscript, entry?
• How can we initialize arrays at time of
declaration?
• What is initialization doesn’t have enough
elements?
• What happens if an array index is negative or
above the upper bound?

23
Array Task:
Defining and Printing an Array
How to read the instructions?

• Create an array called myArray with 10 elements


• Store a value which is 10 plus the index in each
element.
• Print out the array elements so you see the index
and the value of the array elements.

24
Search an array for all
• What kind of statements are needed?

– Look at every value in the array


– Compare it to a value that was read from the
keyboard.

25
• Remaining CS1 Topics?
– Array elements as parameters in functions
– Arrays as parameters in functions
– Partially filled arrays (big arrays that are not full)
– string object is an object containing an array
– 2 D arrays (tables)
– Companion (parallel) arrays
– Vectors
– Recursion (not arrays but we need to cover this!)

26
Accessing Array Components

VLA(s) and Flexible Arrays are supported


by some compilers, Dev C++ one of them

27
Some Restrictions on Array Processing
• Consider the following statements:

• C++ does not allow aggregate operations on


an array:

• Solution:

28
Some Restrictions on Array Processing
(continued)
• The following is illegal too:

• Solution:

• The following statements are legal, but do not


give the desired results:

29
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

30
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

31
Functions Cannot Return a Value of
the Type Array
• C++ does not allow functions to return a value
of the type array

33
Array elements in functions
• Array element accepted as normal function
argument
Similar to…
int my_function(int n);
int a[10], b;
We can use array elements:
b=my_function(a[2]);
b=my_function(a[5]);

34
Array elements in Functions
• The base type of the array is the type of the
element: what does this do?
void swap(int &a, int &b);

int main() {
int array[] = { 1, 3, 5, 7, 9 }; // base type is int
for (int i = 0, j = 4; i < j; i++, j--)
swap(array[i], array[j]);
for (int i = 0; I < 5; i++)
cout << array[i] << endl;
}

35
Arrays in functions
We can pass (access to) the full array in a function
• Function declaration
void printArray(int myArray[], int size2print);

• This is how it is called


• const int DAYS_PER_WEEK =5;
int workHours[DAYS_PER_WEEK];
printArray(workHours, DAYS_PER_WEEK );

Important:
Just the name. No []s and no number

36
Array parameter syntax
• Array parameter declaration
type function( type array_name[], int size);

• Notice the empty [].


• Need both array and size.
– Functions that work on array parameters take the size
as an argument, unless the array ends in a sentinel
value (ex. -1)
• Makes the function more general, but that’s why
we need to pass in size.
37
Array argument syntax
FunctionName(array_name, size);

• To pass in an array argument, just name it.


• The name of the array refers to the beginning
of the memory for the array.
– It’s the same as the name of any variable…
Except, it can be changed in the function without
explicitly saying &.

38
Roughly “pass by reference”

• By default, elements of input array can be


changed by function (a[ ] is an address,
actually it’s the name that is the address)

void fillArray(char a[],int size);


// Precondition: Receives blank list
// of chars and size of list
// Postcondition: list of chars is
// filled by user

39
Roughly “pass by reference”

• Function will see variable type and memory


location of first element
• Notice formal parameter reporting array size

void fillArray(char a[],int size);


// Precondition: Receives blank list
// of chars and size of list
// Postcondition: list of chars is
// filled by user
40
How to pass an array to a function
void fillArray(int myArray[], int myArraySize) // Array and size passed in
{
// srand(time(NULL)); // remove if using mimir
for (int i = 0; i<myArraySize; i++)
{
myArray[i] = rand() % 100;
}
}
void main()
{
const int arraySize = 20;
int RandArray[arraySize];
fillArray(RandArray, arraySize);
}

41
Programming with arrays
What are some things we do with arrays?
Spend some time thinking about the following.
Very common:
• Search – is number x in my array?
• Sort – arrange numbers from small to large
• Find max or min value – specific kind of search
• Compare two arrays, how would you do it?
• Use a partially filled array

42
Program with Partially Filled Array
• A program that reads a bunch of golf scores.
We’ll never have more than 100.
• It computes the average of the scores
• It finds the difference of each score and the
average score.

43
Program to show score difference
const int MAX_SIZE=100;

void fill_array(int a[], int max_size, int& number_used);


// precondition: a is an array with capacity equals max_size.
// postcondition: a has number_used elements <= capacity.

double compute_average(const int a[], int number_used);


void show_difference(const int a[], int number_used);
int main() {
int scores[MAX_SIZE], number_used = 0;
cout << “Program reads golf scores and shows how much each “;
cout << “differs from the average\n”;
fill_array(scores, MAX_SIZE, number_used);
show_difference(scores, number_used);
return 0;
}

44
fill_array

// Precondition: a is an array of max_size capacity.


// Postcondition: a has num_used elements <= max_size.
// reads either max_size integers or fewer ending with 0.
void fill_array(int a[], int max_size, int& num_used) {
cout << “Enter up to “ << max_size << “ scores “
<< “or end by entering 0\n”;
for (num_used = 0; num_used < max_size; num_used++) {
cin >> a[num_used];
if (num_used == 0)
break;
}
}

45
Compute_average
// precondition: a is an array of number_used golf scores.
// returns the average of the golf scores.
double compute_average(const int a[], int number_used)
{
double sum = 0;
for (int i = 0; i < number_used; i++)
{
sum += a[i];
}
return sum / number_used;
}

46
Show_difference

// Precondition: a is an array of golf scores


// Call function compute_average and show the difference
void show_difference(const int a[], int number_used)
{
double average = compute_average(a, number_used);
cout << “The average of the scores is “ << average <<
endl;
for (int i = 0; i < number_used; i++) {
cout << a[i] << “ differs from average by “
<<(a[i] - average) << endl;
}
}

47
Exercise – 02 Arrays (01)
Q1- Write a program that reads 10 integers in
an array, and calculates the Min, Max and Sum
of all array elements.

48
Arrays (01)
Q2 - Write a program that finds a given integer
“n” in an array of 10 integers (read the values of
array in main). If the value n is found, the
program should display found, else display “not
found”.

49
Array (01)
• Q-3 Change the previous program so that you
have function that tells you if a number is
present in array or not

bool isFound(int a[ ], int n, int size)


{
// implement your code here
}
50
Array (01)
• Q4 Write a function that accepts two arrays
and displays the common elements of the
arrays.

51
Array (01) - Sorting
• Q-5 Write a program to Sort a given array of
integers 10 integers.

• Q-6 Write a C++ program to find the most


occurring element in an array of integers

• Q-7 Write a C++ program to find and print


all unique elements of a given array of
integers
52
An Object
What is an object?

A collection of data, called 'members'

Member functions (also called methods) that


operate on them

54
String – your first object
#include <string>

String data:

A string is essentially an array of characters,


ending with a '\0'

55
String – data
string name = "hannah";
Really looks like this in memory:
h a n n a h \0
Value [0] [1] [2] [3] [4] [5] [6]
[Index]

String data:
A string is essentially an array of characters, ending
with a '\0'
56
String – Member Functions
h a n n a h \0
[0] [1] [2] [3] [4] [5] [6]
length() - returns the length of the string
cout << name.length(); // actual chars (not \0)
6
[i] - returns the character at location I
cout << name[4];
a
http://www.cplusplus.com/reference/string/string/

57
More string functions
How to read a full line (spaces included)

string s;
getline(cin, s); // reads the string
//until the 'end of line'

s.at(5); // returns the character at index 5

58
More string functions
s.length() // total COUNT of characters

Can access elements in a string like an array:

s[5] ='q'; OR s.at(8)='q';

NOTE: array A cannot be accessed with A.at(5)


You must use A[5]

59
More string functions
How to read a full line (spaces included)

string s = "Fordham University";


getline(cin, s); // reads the string
//until the 'end of line'

cout << s.at(5); // returns the character at index 5


a
cout << s[5]; // also returns the character at index 5
a

60
More string functions
s.length() // total COUNT of characters

Can access elements in a string like an array:

s[5] ='q'; OR s.at(8)='q';

61
More string related functions
#include <cstdlib>

int x = atoi("657"); // ASCII to integer

double price = atof("12.30");

string FullName = firstname + " " + lastname;

62
Thank you

You might also like