Program Chapt 5
Program Chapt 5
Program Chapt 5
2
Array
3
Introduction
An array is a collection of variables of the same type that are
the positive index into the array. The index is specified by square
brackets, [].
Arrays offer a convenient means of grouping together several
Student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4}
Characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};
Names:
{1, 0, 1},
{1, 0, 5},
7 {4, 7, 9}};
Initializing Arrays
When declaring an array of local scope
(within a function), if we do not specify
the array variable will not be initialized,
so its content is undetermined until we
store some values in it.
If we declare a global array (outside any
function) its content will be initialized
with all its elements filled with zeros.
Thus, if in the global scope we declare:
int day [5];
every0 element
0 0of day0 will0 be set
8
initially to 0:
Cont…
10
Cont…
12
Cont…
The previous examples where day had 5 elements
and each element is of type int, the name, which
we can use to refer to each element, is the
following one:
day(0) day(1) day(2) day(3) day(4)
day 16 22 77 40 12071
For example, to store the value 75 in the third element
of the array variable day a suitable sentence would
be:
day[2] = 75; //as the third element is found at
index 2
And, for example, to pass the value of the third
element of the array variable day to the variable a ,
we could write:
a = day[2];
13
Cont…
#include<iostream>
int main()
{
int numbers[5] ={10,20,30,40,50}; //array declaration & initialization
int sum, average; //declaring variables that store sum and average of
array elements
sum = 0,average=0; //initializing sum & average to 0
cout<<numbers[3]<<endl;
for (int i = 0; i <5; i++)
{
sum += numbers[i];
average = sum / 5;
} //end of for loop
cout<<"The Sum of Array Elements="<<sum<<endl;
cout<<"The Average of Array Elements="<<average;
return 0;
14 }
One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general
form of a one-dimensional array declaration is:
type variable_ name[size]
type: base type of the array, determines the data type of each element in the
array
variable_name: the name of the array
Examples:
float float_numbers[];
char last_name[40];
int sample[10]; 0 1 2 3 4 5 6 7 8 9
15 0 1 4 9 16 25 36 49 64 81
Cont…
Example: Loading and accessing the array sample with the numbers 0 through 9
#include<iostream>
using namespace std;
int main() {
int sample[10]; // reserves for 10 integers
int t;
for(t=0; t<10; t++) // initialize the array
{
cout << t <<" "; // display the index
}
cout<<endl;
for(t=0; t<10; t++)
{
sample[t] = t*t;
// display the array
cout << sample[t] << ' ';
}
return 0;
}
16
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
int test[3][4];
This corresponds to a table with 3 rows and 4 columns(for example).
17
Cont…
We can generate the array above by using this program:
#include<iostream>
int main()
{
int test[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
for(int i=0;i<3;i++) {
for(int j=0;j<4;j++)
{
cout<<"test["<<i<<"]["<<j<<"]="<<test[i][j]<<endl;
}
}
return 0;
}
18
Writing Format to Two -Dimensional Array Initialization
int squares[10][2] = { {1, 1},{2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7, 49},
{8, 64}, {9, 81}, {10, 100}};
20
Arrays of Strings in dimension
The size of the right index specifies the maximum length of each string.
maximum length of 80 characters (with one extra character for the null
terminator):
char string_array[30][81];
21
Character Array Initialization
Character arrays that will hold strings allow a shorthand
initialization that takes this form:
C++ will automatically create arrays large enough to hold all the
initializers present.
are needed.
24
Arrays as parameters
At some moment we may need to pass an
array to a function as a parameter.
In C++ it is not possible to pass by value
a complete block of memory as a
parameter, even if it is ordered as an array,
to a function,
but it is allowed to pass its address, which
has almost the same practical effect and is
a much faster and more efficient operation.
For example, the following function:
void procedure
(int arg [])
25
Cont…
In order to declare arrays as parameters the only
thing that we must do when declaring the function is
to specify in the argument the base type for the array
that it contains, an identifier and a pair of void brackets
[] .
String
28
Introduction
String in C++ is a sequence of character in which the last
element array (at least) to store it. Thus the character `a' is
characters since space is needed for the final null character. Strings can
initialized.
For example: char str1 [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "Hello";
For example:
char Str1[] = "Hello!";
char Str2[18] = "C++ Programming";
Str1
C + + P r o g r a m m i n g \0
Str2
30
String Output
31
String Input
When the input stream cin is used space characters, n
space, tab, newline etc. are used as separators and
terminators.
#include<iostream>
int main() {
const int max=80;
char str[max];
cout<<"Enter a string.\n";
cin>>str;
cout<<"You entered : "<<str;
}
33
Cont…
The cin>> considers a space to be a terminating
character & read strings of a single word.
36
Copying String
The strings copy performed using strcpy or strncpy
function. We assign strings by using the string copy
function strcpy. The prototype for this function is in
string.h.
strcpy(destination, source);
strcpy copies characters from the location specified
by source to the location specified by destination.
It stops copying characters after it copies the
terminating null character.
The return value is the value of the destination
parameter.
You must make sure that the destination string is large
enough to hold all of the characters in the source
string (including the terminating null character).
37
Cont…
Example:
#include <iostream>
#include <string.h>
int main() {
char me[20] = "David";
cout << me << endl;
strcpy(me, "Are You or Not?");
cout << me << endl ;
return 0;
}
41
Cont’d
The function strncat is like strcat except that it
copies only a specified number of characters.
strncat(destination, source, int n);
It may not copy the terminating null character.
Example:
cout << str1 << endl;
#include <iostream>
char str2[] = "xyz";
#include <string.h> strcat(str1, str2);
int main() { cout << str1 << endl;
char str1[30]; str1[4] = '\0';
strcpy(str1, "abc"); cout << str1 << endl;
cout << str1 << endl; }
strncat(str1, "def", 2);
str1[5] = '\0';
42
Comparing Strings
Strings can be compared using strcmp or
strncmp functions.
The function strcmp compares two strings.
strcmp(str1, str2);
43
Cont’d
Example:
#include <iostream>
#include <string.h>
void main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") <<
endl;
cout << strcmp("abc", "ABC") << endl;
}
44
Cont
The function strncmp is like strcmp except that it
compares only a specified number of characters.
strncmp(str1, str2, int n);
strncmp does not compare characters after a terminating
null character has been found in one of the strings.
Example:
#include <iostream.h>
#include <string.h>
int main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
45
Thank You
46