Chapter Four
Chapter Four
Chapter Four
double
Here,
grade[27];
is an array that can hold a maximum of 27 elements of
grade type.
double
In C++, the size and type of arrays cannot be changed after its declaration.
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 ]
• This declares a variable called <array-name> which
contains <size> elements of type <type>
The elements of an array can be accessed as: array-
name[0],…array-name[size-1
C++ Array Declaration
dataType arrayName[arraySize];
For example, int x[6];
Here,
•int - type of element to be stored
•x - name of the array
•6 - size of the array
Access Elements in C++ Array
• In C++, each element in an array is associated with a number.
• The number is known as an array index.
• We can access elements of an array by using those indices.
• array[index]; // syntax to access array elements
• Consider the array x we have seen above.
Few Things to Remember:
•The array indices start with 0. Meaning x[0] is the first element stored at
index 0.
•If the size of an array is n, the last element is stored at index (n-1).
•In this example, x[5] is the last element.
•Elements of an array have consecutive addresses. For example,
suppose the starting address of x[0] is 2120d. Then, the address of the
next element x[1] will be 2124d, the address of x[2] will be 2128d and so
on.
Here, the size of each element is increased by 4. This is because the
size of int is 4 bytes.
C++ Array Initialization
• In C++, it's possible to initialize an array during declaration. For
example,
int x[6] = {19, 10, 8, 17, 9, 15}; // declare and initialize and array
Here, we have not mentioned the size of the array. In such cases, the compiler automatically
computes the size.
C++ Array With Empty Members
In C++, if an array has a size n, we can store upto n number of
elements in the array. However, what will happen if we store
less than n number of elements.
For example,
int x[6] = {19, 10, 8}; // store only 3 elements in the array
Here, the array x has a size of 6. However, we have initialized it with
only 3 elements.
In such cases, the compiler assigns random values to the remaining
places. Oftentimes, this random value is simply 0
How to insert and print array elements?
int mark[5] = {19, 10, 8, 17, 9} // change 4th element to 9
mark[3] = 9;
// take input from the user // store the value at third position
cin >> mark[2]; // take input from the user
// insert at ith position
cin >> mark[i-1]; // print first element of the array
cout << mark[0];
// print ith element of the array
cout << mark[i-1];
Example 1: Displaying Array Elements
• #include<iostream>
• using namespace std;
• int main()
•{
• int num[5]= {7,5,6,12,35};
• cout<<"\n numbers are ";
• for(int i=1; i<=5;i++)
•{
• cout<<num[i]<<" ";
•}
• return 0;
•}
Strings In Array
• String is a collection of characters.
• There are two types of strings commonly used in C++ programming
language:
• Strings that are objects of string class (The Standard C++ Library string
class)
• C-strings (C-style Strings)
• C-strings are arrays of type char terminated with null character, that is, \0
(ASCII value of null character is 0)
How to define a C++-string?
• char str[] = "C++";
• str is a string and it holds 4 characters.
• Although, "C++" has 3 character, the null character \0 is added to the end
of the string automatically.
Alternative ways of defining a string
• char str[4] = "C++";
• char str[] = {'C','+','+','\0'};
• char str[4] = {'C','+','+','\0’};
• Like arrays, it is not necessary to use all the space allocated for the
string. For example:
• char str[100] = "C++";
Example 1: C++ String to read a word
• C++ program to display a string entered by user.
• #include <iostream>
• using namespace std;
• int main()
• {
• char str[100];
• cout << "Enter a string: ";
• cin >> str;
• cout << "You entered: " << str << endl;
• cout << "\nEnter another string: ";
• cin >> str;
• cout << "You entered: "<<str<<endl;
• return 0;
• }
Example 2: C++ String to read a line of text
• C++ program to read and display an entire line entered by user.
• #include <iostream>
• using namespace std;
• int main()
• { char str[100];
• cout << "Enter a string: ";
• cin.get(str, 100);
• cout << "You entered: " << str << endl;
• return 0;
•}
Continue…
• To read the text containing blank space, cin.get function can be used.
• This function takes two arguments.
• First argument is the name of the string (address of first element of
string) and second argument is the maximum size of the array.
• In the above program, str is the name of the string and 100 is the
maximum size of the array.
C++ Multidimensional Arrays
• int x[3][4];
• Here, x is a two-dimensional array. It can hold a maximum of 12
elements.
• We can think of this array as a table with 3 rows and each row has 4
columns as shown below.
Continue…
• Three-dimensional arrays also work in a similar way. For example:
• float x[2][4][3];
• This array x can hold a maximum of 24 elements.
• We can find out the total number of elements in the array simply by
multiplying its dimensions:
• 2 x 4 x 3 = 24
Multidimensional Array Initialization
• We can find out the total number of elements in the array simply by
multiplying its dimensions:
• 2 x 4 x 3 = 24
• we can initialize a multidimensional array in more than one way.
• 1. Initialization of two-dimensional array
• int test[2][3] = {2, 4, 5, 9, 0, 19};
• The above method is not preferred. A better way to initialize this array
with the same array elements is given below:
• int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
• This array has 2 rows and 3 columns, which is why we have two rows
of elements with 3 elements each.
Continue…
Continue…
• Initialization of three-dimensional array
• int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};
• This is not a good way of initializing a three-dimensional array. A
better way to initialize this array is:
• int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
• };
• Notice the dimensions of this three-dimensional array.
Example 1: Two Dimensional Array
• // C++ Program to display all elements
• // of an initialised two dimensional array
• #include <iostream>
• using namespace std;
• int main() {
• int test[3][2] = {{2, -5},
• {4, 0},
• {9, 1}};
• // use of nested for loop
• // access rows of the array
• for (int i = 0; i < 3; ++i) {
• // access columns of the array
• for (int j = 0; j < 2; ++j) {
• cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
• }
• }
• return 0;
• }
Structures in C++
• Unlike Arrays, Structures in C++ are user defined data types which
are used to store group of items of non-similar data types.
• In C++, classes and structs are blueprints that are used to create the
instance of a class.
• Structs are used for lightweight objects such as Rectangle, color,
Point, etc.
• Unlike class, structs in C++ are value type than reference type.
• It is useful if you have data that is not intended to be modified after
creation of struct.
• C++ Structure is a collection of different data types.
• It is similar to the class that holds different types of data.
The Syntax of Structure
Tag or structure tag
struct keyword
Members of
Fields of
structure
• Pointer Example
Continue…
Functions
• A function is block of code which is used to perform a particular task,
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Create a Function
• C++ provides some pre-defined functions, such as main(), which is
used to execute code.
• But you can also create your own functions to perform certain actions.
• To create (often referred to as declare) a function, specify the name of
the function, followed by parentheses ():
Continue…
Example
•myFunction() is the name of the function
•void means that the function does not have a return value.
•inside the function (the body), add code that defines what the function
should do
Call a Function
• Declared functions are not executed immediately.
• They are "saved for later use", and will be executed later, when they are
called.
• To call a function, write the function's name followed by two
parentheses () and a semicolon ;
• In the following example, myFunction() is used to print a text (the action),
when it is called:
Continue…
A function can be called multiple times:
Call by Value and Call by Reference
• Consider the following example, which have two functions that add
numbers of different type:
Continue…
C++ Files and Streams
• we have been using the iostream standard library,
• which provides cin and cout methods for reading from standard input
and writing to standard output respectively.
• The fstream library allows us to work with files.
• To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:
Continue…
Continue…
• here are three classes included in the fstream library, which are used to
create, write or read files:
Create and Write To a File
• To create a file, use either the ofstream or fstream class, and specify
the name of the file.
• To write to the file, use the insertion operator (<<).
• Why do we close the file?
• It is considered good practice, and it can clean up unnecessary
memory space.
Read a File
• To read from a file, use either the ifstream or fstream class, and the
name of the file.
• Note that we also use a while loop together with the getline() function
(which belongs to the ifstream class) to read the file line by line, and
• to print the content of the file:
Continue…
How to Open Files
• Before performing any operation on a file, you must first open it.
• If you need to write to the file, open it using fstream or ofstream
objects. If you only need to read from the file, open it using the
ifstream object.
• The three objects, that is, fstream, ofstream, and ifstream, have the
open() function defined in them. The function takes this syntax:
Continue…
• The file_name parameter denotes the name of the file to open.
• The mode parameter is optional. It can take any of the following
values:
Continue…
Continue…