Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Arrays
◦ Array is data structure
◦ Array is collection of elements of same data type or
we can also say that array is collection of variables
of same type.
◦ Array stores the elements in the sequential manner
◦ Lowest address of an array corresponds to the first
element.
◦ Highest address of an array corresponds to the last
element.
◦ Static entity (same size throughout program)
2
Array
◦ Consecutive group 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
N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
◦ Nth element as position N-1
3
Array elements like other variables
◦ Assignment, printing for an integer array c
c[ 0 ] = 3;
cout << c[ 0 ];
Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]
4
Name of array (Note
that all elements of
this array have the
same name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
5
When declaring arrays, specify
◦ Name
◦ Type of array
Any data type
◦ Number of elements
◦ type arrayName[ arraySize ];
int c[ 10 ]; // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
6
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
7
#include <iostream> Declare a 10-element array of
void main() integers.
{
int n[ 10 ]; // n is an array of 10 integers
Initialize array to 0 using a
// initialize elements of array n to 0 for loop. Note that the array
for ( int i = 0; i < 10; i++ ) has elements n[0] to n[9].
n[ i ] = 0; // set element at location i to 0
8
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
9
#include <iostream> Note the use of the initializer
void main() list.
{
// use initializer list to initialize array n
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
10
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
11
Array size
◦ Can be specified with constant variable (const)
const int size = 20;
◦ Constants cannot be changed
◦ Constants must be initialized when declared
◦ Also called named constants or read-only variables
12
#include <iostream>
Note use of const keyword.
void main() Only const variables can
{ specify array sizes.
13
// output contents of array s in tabular format
for ( int j = 0; j < arraySize; j++ )
cout << j <<setw(15)<< s[ j ] << endl;
} // end main
Element Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
14
#include <iostream> Proper initialization of
void main() const variable.
{
const int x = 7; // initialized constant variable
15
void main()
{
const int x; // Error: x must be initialized
16
#include <iostream>
void main()
{
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int total = 0;
cout << "Total of array element values is " << total << endl;
} // end main
17
#include <iostream>
void main()
{
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
cout << "Element“ << "Value“<< "Histogram" <<
endl;
// for each element of array n, output a bar in
histogram
for ( int i = 0; i < arraySize; i++ ) {
cout << i << setw(15)<<n[ i ];corresponding
Prints asterisks
to size of array element,
for ( int j = 0; j < n[ in[i].
]; j++ ) // print one bar
cout <<setw(15)<< '*';
18
cout << endl; // start next line of output
19
One Dimensional Array
20
A one-dimensional array is a structured
collection of components (often called array
elements) that can be accessed individually
by specifying the position of a component
with a single index value.
21
DataType ArrayName [ConstIntExpression];
int number[5];
22
number[0] specifies the 1st component of the number array
number[1] specifies the 2nd component of the number array
number[2] specifies the 3rd component of the number array
number[3] specifies the 4th component of the number array
number[4] specifies the 5th component of the number array
.
.
.
number[48] specifies the 2nd last component of the number
array
number[49] specifies the last component of the number
array
23
#include<iostream.h>
#include<conio.h>
Void main()
{
clrscr();
int arr[5]={4,9,2,7,5};
int largest_num=arr[0];
for(int a=o;a<5;a++)
if(arr[a]>largest_num)
largest_num=arr[a];
cout<<“Largest Number: ”<<largest_num;
getch();
}
24
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[rowsize][colsize];
where rowsize and colsize are expressions
yielding positive integer values
25
The two expressions rowsize and colsize
specify the number of rows and the number
of columns, respectively, in the array
26
27
28
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
29
30
A two-dimensional array can be processed
in three different ways:
1. Process the entire array
31
Each row and each column of a two-
dimensional array is a one-dimensional
array
32
#include <iostream>
void main()
{
int 2DArray[5][6] = { { 1, 2, 3, 4, 5, 6},
{ 7, 8, 9, 0, 1, 2},
{ 3, 4, 5} };
33
1 2 3 4 5 6
7 8 9 0 1 2
3 4 5 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
34
C++ allows multidimensional arrays.
Syntax for declaring multidimensional array
is:
int arr[3][5][7];
Two dimensional array is also known as two
dimensional array.
35
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'
36
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
Printing strings
◦ cout << string2 << endl;
Does not work for other array types
◦ Characters printed until null found
37
#include <iostream> Two different ways to declare
void main() strings. string2 is
{ initialized, and its size
determined automatically .
char string1[ 20 ]; // reserves 20 characters
char string2[] = "string literal"; // reserves 15 characters
38
// output characters until null character is reached
for ( int i = 0; string1[ i ] != '\0'; i++ )
cout << string1[ i ] << ' '; Can access the characters in a
string using array notation.
cin >> string1; // reads "there“ The loop ends when the null
cout << "\nstring1 is: " << string1 << endl; character is found.
} // end main
39
Recall static storage
◦ If static, local variables save values between
function calls
◦ Visible only in function body
◦ Can declare local arrays to be static
Initialized to zero
static int array[3];
If not static
◦ Created (and destroyed) in every function call
40
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
41
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
◦ Like regular variables
◦ square( myArray[3] );
42
A sequence of zero or more characters
enclosed in double quote marks (e.g., “hello”)
43
There is a difference between 'A' and "A"
–'A' is the character A
–"A" is the string A
Because strings are terminated with null, "A"
represents two characters, 'A' and '\0‘
Similarly, "Hello" contains six characters, 'H',
'e', 'l', 'l', 'o', and '\0'
44
Similar to declaration of any array
char name[30];
// no initialization
char title [20] = "Le Grande Fromage";
// initialized at declaration
// with a string
char chList [10] = {'a', 'b', 'c', 'd'};
// initialized with list of char
// values
45
When a character array is declared, it is legal
to use the assignment operator to initialize
46
#include<iostream>
#include<conio.h>
int main()
{
const int MAX = 80; //maximum characters in a string
char str[MAX]; //string variable str
cout<< “Enter a string \n”;
cin>>str; //put string in str
cout<< “You entered: ” << str << endl; //display string from str
getch();
}
47
Strcpy();
Strcat();
Strlen();
Strcmp();
Strchr();
Strstr();
48
Copy string
Copies the string pointed by source into the
array pointed by destination, including the
terminating null character (and stopping at
that
point).
49
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char arr[50];
strcpy(arr,”Test Program”);
cout<<endl<<”Copied Text: ”<<arr;
getch();
}
Press ctrl + f9 to run the program.
Output:
Copied Text:TestProgram
50
Concatenate strings
Appends a copy of the source string to
the destination string. The terminating null
character in destination is overwritten by the
first character of source, and a null-character
is included at the end of the new string
formed by the concatenation of both
in destination.
51
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char arr[50]={“Shaheed Benazir Bhutto”};
strcat(arr,” University”);
cout<<endl<<arr;
getch();
}
Press ctrl + f9 to run the program.
Output:
Shaheed Benazir Bhutto University
52
Get string length
Returns the length of the string.
void main()
{
char arr[50]={“Shaheed Benazir Bhutto”};
int len = strlen(arr);
cout<<endl<<”Length: ”<<len;
getch();
}
Press ctrl + f9 to run the program.
Output:
Length: 33
53
Compare two strings
Compares the string str1 to the string str2.
54
void main()
{
char arr1[50]={“ABCD”};
char arr2[50]={“abcd”};
int comp=strcmp(arr1,arr2);
if(comp<0)
cout<<endl<<arr1<<” is less than ”<<arr2;
else if (comp>0)
cout<<endl<<arr2<<” is less than ”<<arr1;
else
cout<<endl<<arr1<<” is equal to ”<<arr2;
getch();
}
Press ctrl + f9 to run the program.
Output:
ABCD is less than abcd
55
Locate first occurrence of character in string
Returns a pointer to the first occurrence
of character in the string str.
56
void main()
{
char *s;
char arr[50]={“Test Program”};
s=strchr(arr,’T’);
if(s!=””)
cout<<endl<<”Found a ‘T’ in ”<<s;
getch();
}
Press ctrl + f9 to run the program.
Output:
Found a ‘T’ in Test program
57
Locate substring
Returns a pointer to the first occurrence
of str2 in str1, or a null pointer if str2 is not
part of str1.
58
void main()
{
char arr1[50]={“Java Programming”};
char arr2[50]={“Java Programming”};
char *subst;
subst=strstr(arr1,arr2);
cout<<endl<<”Substring is: ”<<subst;
getch();
}
Press ctrl + f9 to run the program.
Output:
Substring is: Java Programming
59
What is sorting? Discuss in details, different
sorting techniques.
Bubble sort
Quick sort
Merge sort
60