C++ Programming Second Course
C++ Programming Second Course
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
49 Mohannad Al-Kubaisi
C++ Programming
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto statement
in your program.
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
50 Mohannad Al-Kubaisi
C++ Programming
Here, key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.
50 Mohannad Al-Kubaisi
C++ Programming
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
51 Mohannad Al-Kubaisi
C++ Programming
52 Mohannad Al-Kubaisi
C++ Programming
Example
#include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
53 Mohannad Al-Kubaisi
C++ Programming
54 Mohannad Al-Kubaisi
C++ Programming
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
55 Mohannad Al-Kubaisi
C++ Programming
C++ Functions
A function is a group of statements that together perform a task. Every C++ program has
at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that each
function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can
call. For example, function strcat() to concatenate two strings, function memcpy() to
copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure
etc.
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.
56 Mohannad Al-Kubaisi
C++ Programming
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
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 −
57 Mohannad Al-Kubaisi
C++ Programming
#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;
return 0;
}
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
–
58 Mohannad Al-Kubaisi
C++ Programming
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.
59 Mohannad Al-Kubaisi
C++ Programming
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
60 Mohannad Al-Kubaisi
C++ Programming
Now, let us call the function swap() by passing actual values as in the following example
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
When the above code is put together in a file, compiled and executed, it produces the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside
the function.
61 Mohannad Al-Kubaisi
C++ Programming
To check the more detail about C++ pointers, kindly check C++ Pointers chapter.
For now, let us call the function swap() by passing values by pointer as in the following
example −
#include <iostream>
using namespace std;
// function declaration
void swap(int *x, int *y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b. */
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
62 Mohannad Al-Kubaisi
C++ Programming
For now, let us call the function swap() by passing values by reference as in the following
example −
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
63 Mohannad Al-Kubaisi
C++ Programming
C++ Recursion
The process in which a function calls itself is known as recursion and the
corresponding function is called the recursive function. The popular example to
understand the recursion is factorial function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t
worry we wil discuss what is base condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling
itself until the function reaches to the base condition.
64 Mohannad Al-Kubaisi
C++ Programming
Output:
Enter a number: 5
Factorial of entered number: 120
Base condition
In the above program, you can see that I have provided a base condition in the
recursive function. The condition is:
if (n <= 1)
return 1;
The purpose of recursion is to divide the problem into smaller problems till the
base condition is reached. For example in the above factorial program I am
solving the factorial function f(n) by calling a smaller factorial function f(n-1), this
happens repeatedly until the n value reaches base condition(f(1)=1). If you do not
define the base condition in the recursive function then you will get stack
overflow error.
65 Mohannad Al-Kubaisi
C++ Programming
Indirect recursion: When function calls another function and that function calls
the calling function, then this is called indirect recursion. For example: function A
calls function B and Function B calls function A.
120
66 Mohannad Al-Kubaisi
C++ Programming
Numbers in C++
Normally, when we work with Numbers, we use primitive data types such as int, short,
long, float and double, etc. The number data types, their possible values and number
ranges have been explained while discussing C++ Data Types.
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
67 Mohannad Al-Kubaisi
C++ Programming
1 double cos(double);
This function takes an angle (as a double) and returns the cosine.
2 double sin(double);
This function takes an angle (as a double) and returns the sine.
3 double tan(double);
This function takes an angle (as a double) and returns the tangent.
4 double log(double);
This function takes a number and returns the natural log of that number.
7 double sqrt(double);
You pass this function a number and it gives you the square root.
8 int abs(int);
This function returns the absolute value of an integer that is passed to it.
9 double fabs(double);
This function returns the absolute value of any decimal number passed to it.
10 double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
68 Mohannad Al-Kubaisi
C++ Programming
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
69 Mohannad Al-Kubaisi
C++ Programming
int main () {
int i,j;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
70 Mohannad Al-Kubaisi
C++ Programming
C++ Arrays
C++ provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and
..., numbers[99] to represent individual variables. A specific element in an array is
accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare a
10-element array called balance of type double, use this statement −
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as
follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements
that we declare for the array between square brackets [ ]. Following is an example to
assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with
4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first
element which is also called base index. Following is the pictorial representaion of the
same array we discussed above −
71 Mohannad Al-Kubaisi
C++ Programming
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When the above code
is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
72 Mohannad Al-Kubaisi
C++ Programming
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are following few
important concepts, which should be clear to a C++ programmer −
1 Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the multidimensional array is
the two-dimensional array.
2 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array
name, without any index.
73 Mohannad Al-Kubaisi
C++ Programming
74 Mohannad Al-Kubaisi
C++ Programming
int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is
likely that most of the arrays you create will be of one or two dimensions.
75 Mohannad Al-Kubaisi
C++ Programming
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
return 0;
}
76 Mohannad Al-Kubaisi
C++ Programming
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50
In the above example, p is a pointer to double which means it can store address of a
variable of double type. Once we have address in p, then *p will give us value available
at the address stored in p, as we have shown in the above example.
77 Mohannad Al-Kubaisi
C++ Programming
Way-1
Formal parameters as a pointer as follows −
void myFunction(int *param) {
.
.
.
}
Way-2
Formal parameters as a sized array as follows −
void myFunction(int param[10]) {
.
.
.
}
Way-3
Formal parameters as an unsized array as follows −
void myFunction(int param[]) {
.
.
.
}
Now, consider the following function, which will take an array as an argument along with
another argument and based on the passed arguments, it will return average of the
numbers passed through the array as follows −
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
78 Mohannad Al-Kubaisi
C++ Programming
// function declaration:
double getAverage(int arr[], int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following result
−
Average value is: 214.4
As you can see, the length of the array doesn't matter as far as the function is concerned
because C++ performs no bounds checking for the formal parameters.
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
79 Mohannad Al-Kubaisi
C++ Programming
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}
1
4
9
16
25
36
80 Mohannad Al-Kubaisi
C++ Programming
return a;
}
k = print();
return 0;
}
When the above code is compiled together and executed, it produces result something
as follows −
1 2 3 4 5
81 Mohannad Al-Kubaisi
C++ Programming
C++ Strings
C++ provides following two types of string representations −
Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
Let us try to print above-mentioned string −
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
82 Mohannad Al-Kubaisi
C++ Programming
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C++ supports a wide range of functions that manipulate null-terminated strings −
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
83 Mohannad Al-Kubaisi
C++ Programming
When the above code is compiled and executed, it produces result something as follows
−
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
The String Class in C++
The standard C++ library provides a string class type that supports all the operations
mentioned above, additionally much more functionality. Let us check the following
example −
#include <iostream>
#include <string>
int main () {
return 0;
}
When the above code is compiled and executed, it produces result something as follows
−
str3 : Hello
str1 + str2 : HelloWorld
[Link]() : 10
84 Mohannad Al-Kubaisi
C++ Programming
1 ofstream
This data type represents the output file stream and is used to create files and to write
information to files.
2 ifstream
This data type represents the input file stream and is used to read information from files.
3 fstream
This data type represents the file stream generally, and has the capabilities of both ofstream
and ifstream which means it can create files, write information to files, and read information
from files.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file
should be opened.
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
85 Mohannad Al-Kubaisi
C++ Programming
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if
you want to open a file in write mode and want to truncate it in case that already exists,
following will be the syntax −
ofstream outfile;
[Link]("[Link]", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
[Link]("[Link]", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using
the stream insertion operator (<<) just as you use that operator to output information to
the screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.
86 Mohannad Al-Kubaisi
C++ Programming
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
When the above code is compiled and executed, it produces the following sample input
and output −
87 Mohannad Al-Kubaisi
C++ Programming
$./[Link]
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function
to read the line from outside and ignore() function to ignore the extra characters left by
previous read statement.
88 Mohannad Al-Kubaisi