Nothing Special   »   [go: up one dir, main page]

Chapter Four

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

Chapter Four

Arrays, Structures, Functions, Pointers, and Files in


C++
• In C++, an array is a variable that can store multiple values of the same type.
• For example, Suppose a class has 27 students, and we need to store the grades
of all of them.
• Instead of creating 27 separate variables, we can simply create an array:

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

Another method to initialize array during declaration:


int x[] = {19, 10, 8, 17, 9, 15}; //declare and initialize an 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

• a structure is declared by preceding the struct


keyword followed by the identifier(structure
name). Inside the curly braces, we can declare
the member variables of different types.
Continue….
• Student is a structure contains three variables name, id, and age.
• When the structure is declared, no memory is allocated.
• When the variable of a structure is created, then the memory is allocated.
• How to access structure elements?
• Structure members are accessed using dot (.) operator.
• #include <iostream>
• using namespace std;
• struct Point {
• int x, y;
• };
• int main()
• { struct Point p1 = { 0, 1 };

• // Accessing members of point p1


• p1.x = 20;
• cout << "x = " << p1.x << ", y = " << p1.y;
• return 0;
• }
C++ Pointers
• The pointer in C++ language is a variable,
• it is also known as locator or indicator that points to an address of a
value.
• a pointer points to some variable, that is, it stores the address of a
variable. E.g.- if 'a' has an address 0xffff377c, then the pointer to 'a'
will store a value 0xffff377c in it.
• So, if 'b' is pointer to 'a' and the value of 'a' is 10 and address is
0xffff377c, then 'b' will have a value 0xffff377c and its address will be
different.
Continue…
Advantage of Pointer
• 1) Pointer reduces the code and improves the performance,
• it is used to retrieving strings, trees etc. and used with arrays, structures and
functions.
• 2) We can return multiple values from function using pointer.
• 3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
• There are many usage of pointers in C++ language.
• 1) Dynamic memory allocation
• In c language, we can dynamically allocate memory using malloc() and calloc()
functions where pointer is used.
• 2) Arrays, Functions and Structures
• Pointers in c language are widely used in arrays, functions and structures.
• It reduces the code and improves the performe
Symbols Used in Pointer
Declaring a Pointer
• The pointer in C++ language can be declared using ∗
(asterisk symbol).

• 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

• In programming languages, functions can be invoked in two ways: which is known as


Call by Value and Call by Reference.
• Call by value method copies the value of an argument into the formal parameter of
that function. Therefore, changes made to the parameter of the main function do not
affect the argument.
• Call by reference method copies the address of an argument into the formal
parameter. In this method, the address is used to access the actual argument used in
the function call. It means that changes made in the parameter alter the passing
argument.
• In this method, the memory allocation is the same as the actual parameters. All the
operation in the function are performed on the value stored at the address of the
actual parameter, and the modified value will be stored at the same address.
Continue…
Continue…
Call by reference example
Function Declaration and Definition
• A C++ function consist of two parts:
• Declaration: the function's name, return type, and parameters (if any)
• Definition: the body of the function (code to be executed)

• Note: If a user-defined function, such as myFunction() is declared


after the main() function, an error will occur.
• It is because C++ works from top to bottom; which means that if the
function is not declared above main(), the program is unaware of it:
Continue…
C++ Function Overloading
• With function overloading, multiple functions can have the same
name with different parameters:

• 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…

You might also like