Cc103 Miterm Reviewer PDF
Cc103 Miterm Reviewer PDF
Cc103 Miterm Reviewer PDF
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.
Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
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.
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
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.
int main() {
int numbers[5];
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() {
double sum = 0;
double count = 0;
double average;
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.
#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) {
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.
int main() {
int numbers[2][3];
cout << "Enter 6 numbers: " << 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.
#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}
}
};
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 −
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 −
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 −
For the above defined function max(), following is the function declaration −
Parameter names are not important in function declaration only their type is required, so following is also
valid declaration −
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>
// function declaration
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
int result;
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 −
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 −
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>
int result;
result = a + b;
return (result);
int main ()
int a = 100;
int b = 200;
int result;
return 0;
When the above code is compiled and executed, it produces the following result −
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.
int i = 17;
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>
int i;
double d;
int& r = i;
double& s = d;
i = 5;
d = 11.7;
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
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 −
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;
}
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:
};
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.
Both of the objects Box1 and Box2 will have their own copy of data members.
#include <iostream>
class Box {
public:
};
int main() {
// 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 of box 2
return 0;
When the above code is compiled and executed, it produces the following result −
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.