0% found this document useful (0 votes)
16 views60 pages

8 Lecture FoP Arrays

Arrays C++

Uploaded by

bilalasim1020
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)
16 views60 pages

8 Lecture FoP Arrays

Arrays C++

Uploaded by

bilalasim1020
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/ 60

CS-114 Fundamentals of Programming

Arrays

Dr Ayesha Zeb
Email: [email protected]
Lecture Contents

• Introduction to arrays
• Multidimensional arrays
• C strings
• Passing arrays to functions
Visualizing Variables and Arrays

• Arrays are just a collection of variables bundled together

Variable X

X= 5

Array A

A[0] = 55 A[1]=65 A[2]=34 A[3] = 12


Arrays

• An array is a collection of variables of similar type,


placed contiguously in memory.
• Arrays are used to avoid the inconvenience of giving
each data element a unique variable name.
• One data structure having more than one data members
of the same type
• Arrays are statically sized unless specified otherwise.
– Size is constant and can’t be changed after
allocation/declaration
Array Definition

• Array declaration tells the compiler about


• the type of array.
• the name of array.
• the size of array.
type arrayName [ arraySize ];

• Example:
float arr[ 20 ];

Array Array Array


type name size
Referring to Individual Elements in an Array

• All the array elements are numbered, starting at 0 ->


arr[0], arr[1], arr[2], etc

• The last array element is one less than the size of the
array.
– If array size is 20, ie. arr[20] array subscripts would be from

arr[0] to arr[19]
Referring to Individual Elements in an Array

• Individual elements of the array are referred to with


subscripts, the number in brackets following the array
name
– To use the 2nd element of the array -> arr[1]
– To use the 1st element of the array -> arr[0]
– To use the 9th element of the array ->
arr[8]
Example

Integer Type
Array

Size of Array = 12

Each element in the array


is an integer

(Deitel and Deitel)


Initializing Arrays

• /* integer type array */


int rooms [5] = { 50, 49, 20, 1, 17};

• /* float type array */


float length [4] = { 12.39, 16.5,
15.3, 0.23};

• /* character type array */


char name [4] = { ‘a’, ‘A’, ‘z’, ‘Z’};
Initializing Arrays

• /*declared but uninitialized


int n[10];

• /* initialize elements of array n with 0


int n[ 10 ] = {}; OR
int n[ 10 ] = { 0 };

• /*creates a five-element array.


int n[ ] = { 1, 2, 3, 4, 5 };
Initializing Arrays

• If the array size and an initializer list are specified in an


array declaration and the number of initializers are
greater than the array size.

• For example the array declaration


int n[5] = { 32, 27, 64, 18, 95, 14 };

➢ causes a compilation error, because there are six initializers


and only five array elements.
Initializing Arrays

• If the array size and an initializer list are specified in an


array declaration and the number of initializers is lesser
than the array size.

• For example the array declaration


int n[5] = { 32, 27, 64 };

it will fill the remaining array positions with 0

3 2 6 0 0
2 7 4
Entering Data into an Array

• Data can be entered into individual elements of an array using


a loop
• Enter marks of five students into an array
int marks[5];
for ( int i = 0; i < 5; i++ )
{
cout << "Enter marks of " <<i+1 <<" student = ";
cin >> marks [i] ;
}
Reading Data from an Array

Reading data from the array “marks” and calculating the


average.

sum = 0;
for ( i = 0; i < 5; i++ )
sum += marks [i];
cout<<"Average is "<<sum/5<<endl;
Summing the Elements of an Array
int main()
{
const int Size = 10; //variable indicating
size of array
int a[Size] = {87,68,94,100,83,78,85,91,76,87};
int total = 0;
// sum contents of array a
for ( int i = 0; i < Size; i++ )
total += a[ i ];

cout << "Total of array elements: " << total <<


endl;
return 0;
Total of array elements:
}
849
Caution!

• Referring to an element outside the array bounds is an


semantic error. It is not a syntax error.
– i.e. it is not caught by the compiler

• When looping through an array, the array subscript


should never go below 0 and should always be less
than the total number of elements in the array (one
less than the size of the array).

• Make sure that the loop-termination condition prevents


accessing elements outside this range.
Example
// Program to copy the contents of one array to another
int main()
{
int oldMarks[4] = {78, 92, 56, 67};
int newMarks[4];

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


newMarks[i] = oldMarks[i];

cout<< "New array is : "<< endl;

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


cout<<"new Marks ["<<i<<"] :
"<<newMarks[i]<<endl;

return 0;
}
Checking Size of an Array

int x[5]={1,2,3,4,5};
cout << sizeof(x);

• Would return 20
Multi Dimensional Arrays (Matrices)

• An array can have two or more dimensions. This


permits them to model multidimensional objects, such
as graph paper or the computer display screen.

• They are often used to represent tables of values


consisting of information arranged in rows and
columns.
Multi Dimensional Arrays (Matrices)

• To identify a particular element, we must specify two


subscripts. By convention,
array_name[row_number][col_number]

• For example,
arr[i][j]
2-D Array (Matrix)
Images are multidimensional arrays

• Black/White Images are 2D arrays


• Color Images are 3D arrays
255 255 255 255 255
255 0 0 0 0
255 255 255 255 255 255 0 0 0 0
255 255 255 255 255 255 0 0 0 0
255 255 128 128 128 255 0 0 0 0
255 255 128 128 128 255 255 255 255 255
255 255 128 128 128 255 255 255 255 255
255 255 255 255 255
255 255 255 255 255
255 255 255 255 255

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Initializing a 2D Array

• int matrix [10] [2] = { {59 , 78},


{14 , 17},
{68 , 28},
{32 , 45},
{ 5 , 14},
{12 , 15},
{ 6, 2},
{ 22, 1},
{14 , 16},
{ 2, 58} };

• The values used to initialize an array are separated by


commas and surrounded by braces.
2-D Array (Matrix)

int matrix [4] [4] = { {59, 78,14, 17},{68, 28,32, 45},


{5, 14,12, 15} ,{6, 2, 22, 1} };

59 78 14 17
(0,0) (0,1) (0,2) (0,3)
68 28 32 45
(1,0) (1,1) (1,2) (1,3)
(row = 2, col
5 14 12 15
= 0)
(2,0) (2,1) (2,2) (2,3)
6 2 22 1
(3,0) (3,1) (3,2) (3,3)

4x4
Matrix
Reading a 2D Array

int matrix [4][4]={{59,78,14,17},{68,28,32,45},


{5, 14,12,15},{6,2, 22, 1}};

for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
cout<<matrix[i][j]<<"\t";
}
cout<<endl;
}
Example

• Write a matrix with following entries

12 12

54 34

16 3

12 6

43 23

1 2
Class Activity!!

• Device a code for filling a 2-D matrix


int main(void)
{
int matrix[5][2];
for(int i=0;i<5;i++)
for(int j=0;j<2;j++)
{
cout<<"enter value for row "<<i<<" and col“<<j<<": ";
cin>>matrix[i][j];
}

cout<<"the input matrix is \n";

for(int i=0;i<5;i++)
{
for(int j=0;j<2;j++)
cout<<matrix[i][j]<<"\t";
cout<<endl;
}
}
C Strings

• A C string is an array of characters


• Its is used in programming for storing and manipulating
text, such as words, names and sentences.
• Strings can be variable or constant.
C String Constants

• Another Example,

cout << “Hello!” ;

• Here, “Hello!” is a string constant. This means that the


string itself is stored someplace in memory, but it cannot
be changed.
C String Constants
• A string can be initialized when it is defined. For example,
char str[ ] = “ String is a series of characters ” ;

• Alternatively, strings can also be initialized like arrays


char str[ ] = {'S','t','r','i','n','g','
','i',....,‘s'};

• However, the 2nd method is tedious and error-prone.


C String Example

Terminating
zero or “null”
character ‘\0’

String constant stored in memory


C String Characteristics

• Each character of string occupies one byte in the


memory.
• All strings must end with a null character, ‘\0’, which
has a numeric value of 0.
• A string not terminated by a ‘\0’ character, is not really a
string at all, but merely a collection of characters.
• In case of a string constant, the compiler places the null
itself at the closing brace ‘}’.
C String Variable

• Like all other variables and arrays


char name[5];
cin >> name;
cout<< "you entered " << name;

• The << operator displays the output until it encounters a


null character.
• In case of a string variable, the cin operator places the
null automatically.
C String Variable
char name[5];
cin >> name;

String variable stored in memory


Problem with cin
• The cin >> function, has some limitations when it comes to handling
the strings. It enters a null at the first whitespace character it
encounters and terminates the string.
• So,
char name[15];
cin >> name;

cout<< "you entered " << name;

Anything after the blank will disappear.


Solution to the cin>> problem
• Another way to avoid this problem is using

cin.get(str_name,str_size);

For example,

int main()
{
const int MAX = 20;// max characters in
string
char str[MAX];
cout<< "Enter a string :" ;
cin.get(str,MAX);
cout<< "You entered: " << str;
}
Multi-Dimensional Strings (Array of Strings)

• char stu_lists [5] [10] = {“Ali”,


“Abbas”,
“Alina”,
“Ayesha”,
“Bano”
};
2D String

2D array of characters
String Library

• C++ has provided some functions to carry out certain


basic operations on strings.
String Functions
String Functions
String Functions
Built in String Class

• c++ has a built-in string class


• Instead of using a char array a string type variable can
be created
• No need to put ‘/0’ or give size
– it manages the memory itself

string str = “Hello”


Passing Elements of an Array to a Function

• There are 3 ways of passing an array to a function


– By value – element by element
– By reference
– By pointers

• Arrays are normally passed element by element between


functions.
Passing Arrays by Value

• In passing by value a copy of each of the element of the


array being passed is made. This copy is then used by
the function.
– The elements of the original array can’t be modified
– In case of very large arrays this method is inefficient as it would
require a lot of processing and would take up a considerable
amount of space.
Passing Elements of an Array to a Function

void display ( int m );


int main ( )
{
int i;
int marks [5] = {23,43,56,34,32};
for (i=0; i<5; i++)
display ( marks[i] );
}

void display ( int m )


{
cout << m ;
}
Passing Arrays by Reference

• Function prototype or declaration

void somefunct( int [], int);

• Function call
somefunct(elem, size)

• Function Header
void somefunct( int array[], int
size_of_elem)
Passing an Array to a Function
#include <iostream>
using namespace std; • When passing an
void displayArray(int arr[], array to a function:
int arrSize) – Pass the size of the
{cout << endl; array
for (int i = 0; i < arrSize; – Any changes you
i++) make to the array are
cout << arr[i] << " "; reflected in your
code.
cout << endl;}
int main()
{int arr[10] = { 5,6,10 };
displayArray(arr, 10);
return 0; }
Passing an Array to a Function
#include <iostream> {
for (int i = 0; i < arrSize;
using namespace std; i++)
arr1[i] += i;
void displayArray(int arr[], }
int arrSize) int main()
{ {
cout << endl; const int arrSize = 10;
for (int i = 0; i < arrSize; int arr[arrSize] = { 5,6,10
i++) };
cout << arr[i] << " "; displayArray(arr, arrSize);
cout << endl; modifyArray(arr, arrSize);
} displayArray(arr, 10);
void modifyArray(int arr1[], return 0;
int arrSize) }
Activity!!

• Write a function cubed_sum() which calculates the cube


of 10 integers in an array defined by the user, passed
from the main and returns the cubed sum.
int cubed_sum(int);
Solution int main()
{
int arr[10];
int x, sum=0;
cout <<"input 10 integers to be cubed and summed
";
for ( int i = 0; i <10 ; i++ )
{
cin>>arr[i];
x = cubed_sum(arr[i]);
}
cout << "sum of cubed elements = " << x << endl;
return 0;
}
int cubed_sum(int r)
{ static int b=0;
int a=0;
a = (r*r*r);
b = b+a;
return b;
}
Home Assignment!

• Write a program that calculate the cube and square.


Your program should consist of the following:
– A function called “sq_cube” to calculate the square as well as
cube (one function for both calculations).
– Call the function (sq_cube) from the main.
– In main, take two inputs from user.
– First input is the number whose square or cube is to be
calculated
– Second input should be either 2 or 3. If 2, function should
calculate square and if 3, calculate cube.
– Pass both inputs to the function.
– Function to return calculated value back to the main.
– Main should print the answer on the screen.
– Overload for different var types
float sq_cube(float,int);

int main()
{
float no, ans;
int select;
cout <<" enter number for calc of sq or cube
=";
cin >> no;
cout <<"\nenter 2 for sq 3 for cube =";
cin >> select;
ans=sq_cube (no,select);
if (select == 2)
cout<<"Sq of " <<no<<" is
="<<ans<<endl;
else
cout<<"Cube of "<<no<<" is
="<<ans<<"\n\n";
cout <<"\n\n";
}
float sq_cube(float x, int y)
{
if (y == 2)
return x*x;
else return x*x*x;
}
Passing Strings to Functions

void printABC(char []);


const int SIZEOFSTRING = 255;

int main()
{
char str[SIZEOFSTRING];
cin>>str;
printABC(str );
return 0;
}

void printABC(char ch[])


{
cout<<ch;
}
Home Assignment!

• Write a program that declares a


character array initialized to “the
quick brown fox” and counts the
number of times each vowel is
encountered. Use a separate
function.
int spaces(char);
const int MAX = 100;
int main()
{
char str[MAX];
int spcs;
cout<<"Enter a phrase: ";
cin.get(str,MAX);
for (int i=0;str[i]!='\0';i++)
spcs=spaces(str[i]);
cout<<"The total number of spaces is
"<<spcs<<endl;
}

int spaces(char str)


{
static int count=0;
if(str==' ')
count++;
return count;
}
Acknowledgement/References
• Slides contents taken from Ma’am Fatima Faruq

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like