Cc103 Miterm Reviewer PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Lesson Proper for Week 7

C++ ARRAYS
In this tutorial, we will learn to work with arrays. We will learn to declare, initialize, and access array
elements in C++ programming with the help of examples.
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 grade[27];
Here, grade is an array that can hold a maximum of 27 elements of double type.
In C++, the size and type of arrays cannot be changed after its declaration.

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.
// syntax to access array elements
array[index];
Consider the array x we have seen above.
C++ Elements of an array in
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,
// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};

C++ Array elements and their data


Another method to initialize array during declaration:
// declare and initialize an array
int x[] = {19, 10, 8, 17, 9, 15};
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,
// store only 3 elements in the array
int x[6] = {19, 10, 8};

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.

Empty array members are automatically assigned the value 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 numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements


// using range based for loop
for (const int &n : numbers) {
cout << n << " ";
}

cout << "\nThe numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}
Run Code
Output
The numbers are: 7 5 6 12 35
The numbers are: 7 5 6 12 35
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed numbers[i].
We again used a range based for loop to print out the elements of the array. To learn more about this
loop, check C++ Ranged for Loop.
Note: In our range based loop, we have used the code const int &n instead of int n as the range
declaration. However, the const int &n is more preferred because:
1. Using int n simply copies the array elements to the variable n during each iteration. This is not
memory-efficient.
&n, however, uses the memory address of the array elements to access their data without copying them
to a new variable. This is memory-efficient.
2. We are simply printing the array elements, not modifying them. Therefore, we use const so as not
to accidentally change the values of the array.

Example 2: Take Inputs from User and Store Them in an Array


#include <iostream>
using namespace std;

int main() {
int numbers[5];

cout << "Enter 5 numbers: " << endl;

// store input from user to array


for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

// print array elements


for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}

return 0;
}
Run Code
Output
Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15
Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an input from
the user and stored it in numbers[i].
Then, we used another for loop to print all the array elements.

Example 3: Display Sum and Average of Array Elements Using for Loop
#include <iostream>
using namespace std;

int main() {

// initialize an array without specifying size


double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;

cout << "The numbers are: ";

// print array elements


// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";

// calculate the sum


sum += n;

// count the no. of array elements


++count;
}

// print the sum


cout << "\nTheir Sum = " << sum << endl;

// find the average


average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}
Run Code
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
In this program:
1. We have initialized a double array named numbers but without specifying its size. We also declared
three double variables sum, count, and average.
Here, sum =0 and count = 0.
2. Then we used a range based for loop to print the array elements. In each iteration of the loop, we
add the current array element to sum.
3. We also increase the value of count by 1 in each iteration, so that we can get the size of the array
by the end of the for loop.
4. After printing all the elements, we print the sum and the average of all the numbers. The average of
the numbers is given by average = sum / count;
Note: We used a ranged for loop instead of a normal for loop.
A normal for loop requires us to specify the number of iterations, which is given by the size of the array.
But a ranged for loop does not require such specifications.
Lesson Proper for Week 8
C++ Multidimensional Arrays
In this tutorial, we'll learn about multi-dimensional arrays in C++. More specifically, how to declare them,
access them, and use them efficiently in our program.

In C++, we can create an array of an array, known as a multidimensional array. For example:
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.

Elements in two dimensional array in C++ Programming


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


Like a normal array, 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.

Initializing a two-dimensional array in C++

2. Initialization of three dimensional arrays


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 initialise 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}, {3, 1, 4, 9} }
};

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;
}
Run Code
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
In the above example, we have initialized a two-dimensional int array named test that has 3 "rows" and 2
"columns".
Here, we have used the nested for loop to display the array elements.
· the outer loop from i = 0 to i = 2 access the rows of the array
· the inner loop from j = 0 to j = 1 access the columns of the array
Finally, we print the array elements in each iteration.

Example 2: Taking Input for Two Dimensional Array


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];
cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}

return 0;
}
Run Code

Output
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
Here, we have used a nested for loop to take the input of the 2d array. Once all the input has been taken,
we have used another nested for loop to print the array members.

Example 3: Three Dimensional Array


// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream>
using namespace std;

int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};

// Displaying the values with proper index.


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
}
}
}

return 0;
}
Run Code

Output
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
The basic concept of printing elements of a 3d array is similar to that of a 2d array.
However, since we are manipulating 3 dimensions, we use a nested for loop with 3 total loops instead of
just 2.
As we can see, the complexity of the array increases exponentially with the increase in dimensions.
Lesson Proper for Week 9
Defining a Function
The general form of a C++ function definition is as follows −

return_type function_name( parameter list )

body of the function

A C++ function definition consists of a function header and a function body. Here are all the parts of a
function −
· Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
· Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
· Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
· Function Body − The function body contains a collection of statements that define what the
function does.

Example:
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and return the biggest of both −

// function returning the max between two numbers

int max(int num1, int num2) {

// local variable declaration


int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so following is also
valid declaration −

int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in
another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you
will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example −

#include <iostream>

using namespace std;

// function declaration

int max(int num1, int num2);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

int ret;

// calling a function to get max value.

ret = max(a, b);

cout << "Max value is : " << ret << endl;

return 0;

// function returning the max between two numbers

int max(int num1, int num2) {

// local variable declaration

int result;

if (num1 > num2)


result = num1;

else

result = num2;

return result;

I kept max() function along with main() function and compiled the source code. While running final
executable, it would produce the following result −

Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −

Sr.No Call Type & Description


1 Call by Value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
2 Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function and above mentioned example while calling max()
function used the same method.
Default Values for Parameters
When you define a function, you can specify a default value for each of the last parameters. This value
will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default given value is
used, but if a value is specified, this default value is ignored and the passed value is used instead.
Consider the following example −

#include <iostream>

using namespace std;

int sum(int a, int b = 20)

int result;

result = a + b;

return (result);

int main ()

// local variable declaration:

int a = 100;

int b = 200;

int result;

// calling a function to add the values.

result = sum(a, b);

cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);

cout << "Total value is :" << result << endl;

return 0;

When the above code is compiled and executed, it produces the following result −

Total value is: 300

Total value is: 120


Lesson Proper for Week 10
PASS-BY-REFERENCE
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is
initialized with a variable, either the variable name or the reference name may be used to refer to the
variable.

References vs Pointers
References are often confused with pointers but three major differences between references and pointers
are −
· You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
· Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers
can be pointed to another object at any time.
· A reference must be initialized when it is created. Pointers can be initialized at any time.

Creating References in C++


Think of a variable name as a label attached to the variable's location in memory. You can then think of a
reference as a second label attached to that memory location. Therefore, you can access the contents of
the variable through either the original variable name or the reference. For example, suppose we have
the following example −

int i = 17;

We can declare reference variables for i as follows.

int& r = i;

Read the & in these declarations as reference. Thus, read the first declaration as "r is an integer
reference initialized to i" and read the second declaration as "s is a double reference initialized to d.".
Following example makes use of references on int and double −

#include <iostream>

using namespace std;


int main () {

// declare simple variables

int i;

double d;

// declare reference variables

int& r = i;

double& s = d;

i = 5;

cout << "Value of i : " << i << endl;

cout << "Value of i reference : " << r << endl;

d = 11.7;

cout << "Value of d : " << d << endl;

cout << "Value of d reference : " << s << endl;

return 0;

When the above code is compiled together and executed, it produces the following result −

Value of i : 5

Value of i reference : 5

Value of d : 11.7

Value of d reference : 11.7

References are usually used for function argument lists and function return values. So following are two
important subjects related to C++ references which should be clear to a C++ programmer −

Sr.No Concept & Description


1 References as Parameters
C++ supports passing references as function parameter more safely than
parameters.
2 Reference as Return Value
You can return reference from a C++ function like any other data type.

RETURN VALUES
The void keyword, used in the previous examples, indicates that the function should not return a value. If
you want the function to return a value, you can use a data type (such as int , string , etc.) instead
of void , and use the return keyword inside the function:

Example:
#include <iostream>
using namespace std;
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}

This example returns the sum of a function with two parameters:


#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}

You can also store the result in a variable:


#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
Lesson Proper for Week 11
C++ CLASSES/OBJECTS
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.
Attributes and methods are basically variables and functions that belong to the class. These are often
referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object constructor,
or a "blueprint" for creating objects.

C++ Class Definitions


When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed
by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.
For example, we defined the Box data type using the keyword class as follows −

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};
The keyword public determines the access attributes of the members of the class that follows it. A public
member can be accessed from outside the class anywhere within the scope of the class object. You can
also specify the members of a class as private or protected which we will discuss in a sub-section.

Define C++ Objects


A class provides the blueprints for objects, so basically an object is created from a class. We declare
objects of a class with exactly the same sort of declaration that we declare variables of basic types.
Following statements declare two objects of class Box −

Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members


The public data members of objects of a class can be accessed using the direct member access operator
(.). Let us try the following example to make the things clear –

#include <iostream>

using namespace std;

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

int main() {

Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box


double volume = 0.0; // Store the volume of a box here

// box 1 specification

Box1.height = 5.0;

Box1.length = 6.0;

Box1.breadth = 7.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;

Box2.breadth = 13.0;

// volume of box 1

volume = Box1.height * Box1.length * Box1.breadth;

cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2

volume = Box2.height * Box2.length * Box2.breadth;

cout << "Volume of Box2 : " << volume <<endl;

return 0;

When the above code is compiled and executed, it produces the following result −

Volume of Box1 : 210

Volume of Box2 : 1560

It is important to note that private and protected members cannot be accessed directly using direct
member access operator (.). We will learn how private and protected members can be accessed.

Classes and Objects in Detail


So far, you have got very basic idea about C++ Classes and Objects. There are further interesting
concepts related to C++ Classes and Objects which we will discuss in various sub-sections listed below –

Sr.No Concept & Description


1 Class Member Functions
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable.
2 Class Access Modifiers
A class member can be defined as public, private or protected. By default members
would be assumed as private.
3 Constructor & Destructor
A class constructor is a special function in a class that is called when a new object of
the class is created. A destructor is also a special function which is called when
created object is deleted.
4 Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously.
5 Friend Functions
A friend function is permitted full access to private and protected members of a class.
6 Inline Functions
With an inline function, the compiler tries to expand the code in the body of the
function in place of a call to the function.
7 this Pointer
Every object has a special pointer this which points to the object itself.
8 Pointer to C++ Classes
A pointer to a class is done exactly the same way a pointer to a structure is. In fact a
class is really just a structure with functions in it.
9 Static Members of a Class
Both data members and function members of a class can be declared as static.

You might also like