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

Array in C++ Programming Lecture

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. Arrays can be initialized using a for loop or initializer list. Elements are accessed using the array name and index within brackets. Strings are arrays of characters that end with a null terminator. Arrays can be passed to functions by specifying the array name without brackets and passing the size.

Uploaded by

Awais Arshad
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)
63 views

Array in C++ Programming Lecture

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. Arrays can be initialized using a for loop or initializer list. Elements are accessed using the array name and index within brackets. Strings are arrays of characters that end with a null terminator. Arrays can be passed to functions by specifying the array name without brackets and passing the size.

Uploaded by

Awais Arshad
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/ 22

COMPUTER PROGRAMMING

LECTURE # 8: ARRAY - A

BSE 1
Joddat Fatima
1
[email protected]

Department of C&SE
Bahria University Islamabad
BASICS

 In daily life we commonly group similar elements in units.


 Cans of pine juices
 Dozen bananas
 Cartoon of eggs

 In programming we need group of data items of same type as


well so to accomplish that most basic concept of arrays is
used in C++

2
INTRODUCTION

 Array
 Consecutivegroup of memory locations
 Same name and type (int, char, etc.)

 To refer to an element
 Specify array name and position number (index)
 Format: arrayname[ position number ]
 First element at position 0

An array is a series of elements of the same type placed in


contiguous memory locations that can be individually 3
referenced by adding an index to a unique identifier.
DECLARATION OF ARRAY

 When declaring arrays, specify


 Name
 Type of array
 Number of elements

type arrayName[ arraySize ];

Example:

int c[ 10 ]; // array of 10 integers


float d[ 3284 ]; // array of 3284 floats

4
INITIALIZING ARRAYS

 For loop
 Set each element
 Initializer list
 Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
 If not enough initializers, rightmost elements 0
 If too many syntax error

 To set every element to same value


int n[ 5 ] = { 0 };
 If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array 5
ARRAY VARIABLE TYPE
 An array can have indexed variables of any type
 All indexed variables in an array are of the same type
 An indexed variable can be used anywhere an ordinary variable
of the base type is used

ARRAY [] USAGE
 In an array declaration, [ ]'s enclose the size of the array
 When referring to one of the indexed variables, the [ ]'s enclose
a number identifying one of the indexed variables
 The value in the [ ]'s can be any expression that evaluates to one
6
of the integers
VARIABLES & DECLARATION

 Most compilers do not allow the use of a variable


to declare the size of an array

 Example:
cout << "Enter number of students: ";
cin >> number;
int score[number];

 This code is illegal on many compilers


7
ARRAY OUT OF RANGE

 A common error is using a nonexistent index


 Index values for int a[6] are the values 0 through 5
 An index value not allowed by the array declaration is out of range
 Using an out of range index value doe not produce an error message!

 Problems
 Array declared as int a[6]; int i=7; executing the statement a[i] = 238;
causes…
 The computer to calculate the address of the illegal a[7]
(This address could be where some other variable is stored)
 The value 238 is stored at the address calculated for a[7] 8
 No warning is given!
EXAMPLE-1

#include <iostream> OUTPUT


0
int main() 0
{ 0
int n[ 10 ]; // n is an array of 10 integers 0
0
// initialize elements of array n to 0 0
for ( int i = 0; i < 10; i++ ) 0
0
n[ i ] = 0; // set element at location i to 0 0
for ( int j = 0; j < 10; j++ ) 0

cout<<n[ j] <<endl; // print all elements


return 0;
}

9
EXAMPLE-2

#include <iostream>
int main() OUTPUT
32
{ 27
// use initializer list to initialize array n 64
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 18
95
for ( int i = 0; i < 10; i++ )
14
cout << n[ i ] << endl; 90
return 0; 70
60
}
37

10
ARRAY SIZE & EXAMPLE
 Array size
 Can be specified with constant variable (const)
 const int size = 20;

 Constants cannot be changed


 Constants must be initialized when declared

 Example OUTPUT
#include <iostream> 2
int main() 4
{ 6
8
const int arraySize = 10;
10
int s[ arraySize ]; 12
for ( int i = 0; i < arraySize; i++ ) 14
s[ i ] = 2 + 2 * i; 16
18
for ( int j = 0; j < arraySize; j++ )
20 11
cout << << s[ j ] << endl;
return 0;}
EXAMPLE
#include <iostream>
int main()
{
const int arrSize = 10;
int a[ arrSize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
for ( int i = 0; i < arrSize; i++ )
total += a[ i ];
cout << "Total of array element values is " << total <<
endl;
return 0;
12
} Total of array element values is 55
Element Value Histogram
0 19 *******************
1 3 ***
EXAMPLE 2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
#include <iostream> 6 13 *************
#include <iomanip> 7 5 *****
int main() 8 17 *****************
{ 9 1 *

const int arraySize = 10;


int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
cout << "Element" << setw( 13 ) << "Value"<< setw( 17 ) << "Histogram" << endl;

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


{
cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << setw( 9 );
for ( int j = 0; j < n[ i ]; j++ ) // print one bar
cout << '*';
cout << endl;
}
return 0; 13
}
STRING ARRAYS

 Strings
 Arrays of characters
 All strings end with null ('\0')
 Examples
 char string1[] = "hello";

 Null character implicitly added

 string1 has 6 elements

 char string1[] = { 'h','e','l','l','o','\0’ };

 Subscripting is the same

String1[ 0 ] is 'h'
string1[ 2 ] is 'l'

14
STRING ARRAYS
 Input from keyboard
char string2[ 10 ];
cin >> string2;
 Puts user input in string
 Stops at first whitespace character

 Adds null character

 If too much text entered, data written beyond array


 We want to avoid this (section 5.12 explains how)

 Printing strings
 cout << string2 << endl;
 Does not work for other array types

 Characters printed until null found

15
STRING ARRAYS EXAMPLE
Enter the string "hello there": hello there
string1 is: hello
#include <iostream>
string2 is: string literal
int main()
string1 with spaces between characters is:
{ hello
char string1[ 20 ];
char string2[] = "string literal";

cout << "Enter the string \"hello there\": ";


cin >> string1;
cout << "string1 is: " << string1 << "\nstring2 is: " << string2;
cout << "\nstring1 with spaces between characters is:\n";

for ( int i = 0; string1[ i ] != '\0'; i++ )


cout << string1[ i ] << ' ';
return 0; 16
}
ARRAY WITH FUNCTIONS

17
PASSING ARRAYS TO FUNCTIONS

 Specify name without brackets


 To pass array myArray to myFunction
int myArray[ 24 ];
myFunction( myArray, 24 );
 Array size usually passed, but not required
 Useful to iterate over all elements

18
PASSING ARRAYS TO FUNCTIONS

 Arrays passed-by-reference
 Functions can modify original array data
 Value of name of array is address of first element
 Function knows where the array is stored
 Can change original memory locations

 Individual array elements passed-by-value


 Likeregular variables
 square( myArray[3] );

19
PASSING ARRAYS TO FUNCTIONS

 Functions taking arrays


 Function prototype
 void modifyArray( int b[], int arraySize );
 void modifyArray( int [], int );

 Names optional in prototype

 Both take an integer array and a single integer

 No need for array size between brackets


 Ignored by compiler
 If declare array parameter as const
 Cannot be modified (compiler error)
 void doNotModify( const int [] );

20
EXAMPLE
#include <iostream>
void modifyArray( int [], int );
void modifyElement( int );
int main()
{
const int arraySize = 5;
int a[ arraySize ] = { 0, 1, 2, 3, 4 };
cout << "Effects of passing entire array by reference:" << "\n\nThe values of the original array are:\n";
for ( int i = 0; i < arraySize; i++ )
cout << a[ i ];
cout << endl;
modifyArray( a, arraySize );
cout << "The values of the modified array are:\n";
for ( int j = 0; j < arraySize; j++ )
cout << a[ j ];
cout << "\n\n\n"<< "Effects of passing array element by value:"<< "\n\nThe value of a[3] is " << a[ 3 ]
<< '\n';
modifyElement( a[ 3 ] );
cout << "The value of a[3] is " << a[ 3 ] << endl;
return 0; 21
}
EXAMPLE CONST..

void modifyArray( int b[], int sizeOfArray ) Effects of passing entire array by reference:

{  

for ( int k = 0; k < sizeOfArray; k++ ) The values of the original array are:
b[ k ] *= 2; 0 1 2 3 4
} The values of the modified array are:
0 2 4 6 8
void modifyElement( int e )  
{  
cout << "Value in modifyElement is “ Effects of passing array element by value:
<< ( e *= 2 ) << endl;  
} The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6

22

You might also like