C++ Module
C++ Module
C++ Module
Institute of Technology
School of Electrical and Computer engineering
For 1st year
Computer Programming (ECEg-1052)
Contents page
Chapter one ..................................................................................................................................... 1
Basics of computer system .......................................................................................................... 1
1.1 What is computer? ........................................................................................................... 1
1.2 Benefits of Computers ..................................................................................................... 1
1.3 Hard ware component ...................................................................................................... 2
1.4 Software component ........................................................................................................ 2
1.3.1 Data representation in a computer ............................................................................ 3
1.3.2 Integer representation................................................................................................ 4
1.3.3 Decimal (base 10) number system ............................................................................ 7
1.3.4 Binary (base 2) number system................................................................................. 7
1.3.5 Hexadecimal (base 16) number system .................................................................... 7
Chapter two ................................................................................................................................... 12
Fundamentals of C++ programming ......................................................................................... 12
2.1 Introduction to computer program ................................................................................. 12
2.2 Algorithm....................................................................................................................... 14
2.3 Flowchart ....................................................................................................................... 14
2.3.1 Flowchart Symbols ................................................................................................. 14
2.2.2 Type of Algorithms and flowchart .......................................................................... 15
2.4 Variables ........................................................................................................................ 17
2.5 Simple input/output ....................................................................................................... 18
2.6 Names ............................................................................................................................ 20
Chapter three ................................................................................................................................. 24
Control structure........................................................................................................................ 24
3.1 Sequential structure ....................................................................................................... 24
3.2 Selective structure.......................................................................................................... 24
3.3 Looping structures (iteration) ........................................................................................ 35
3.4 Unconditional control structure ..................................................................................... 41
Chapter four .................................................................................................................................. 46
Functions ................................................................................................................................... 46
Chapter One
1. Speed
2. Accuracy
3. Capacity to take large amount of work.
Computer work at a very high speed and are much faster than humans. The human equivalent of
an average computer would be more than one million mathematicians working 24 hours a day.
In addition to being fast, computers are very accurate. If the input and the instructions are accurate
the output will also be accurate.
Unlike humans, computers do not get bored or tired. The monotony of repetitive work for long
hours do not affect the computers.
Applications of Computers
Computers are used in various fields ranging from making cartoon films to space research. Some
applications of computers are:
1. Railway reservations
2. Banking and Accounts
3. Weather Forecasts
4. Space Research
5. Medical Diagnoses
6. Chemical Analyses
Generally, computer was developed from two parts, i.e. from hardware and software.
1. System Unit
2. Peripheral devices
3. Input devices i.e. keyboard, mouse etc.
4. Output devices i.e. Display Unit, printer etc.
5. Storage devices like hard disk, floppy disks etc.
Applications Software
Software especially suited for specific applications for example, railway and airline reservation,
billing, accounting or software which enables creation and storage of documents are termed as
application software.
System software
System software In the above airline reservation example, the clerk types your name and
other details through the keyboard. But how does this go to the system unit? This activity is done
by a set of instructions called the Operating Systems.
System software is a set of instructions that serves primarily as an intermediary between computer
hardware and application programs, and may also be directly manipulated by knowledgeable users.
1. Sign-Magnitude representation
Unsigned integers can represent zero and positive integers, but not negative integers. The value of
an unsigned integer is interpreted as "the magnitude of its underlying binary pattern".
Example 1: Suppose that n=8 and the binary pattern is 0100 0001B, the value of this unsigned
integer is 1×2^0 + 1×2^6 = 65D.
Example 2: Suppose that n=16 and the binary pattern is 0001 0000 0000 1000B, the value of
this unsigned integer is 1×2^3 + 1×2^12 = 4104D.
Example 3: Suppose that n=16 and the binary pattern is 0000 0000 0000 0000B, the value of
this unsigned integer is 0.
An n-bit pattern can represent 2^n distinct integers. An n-bit unsigned integer can represent
integers from 0 to (2^n)-1, as tabulated below:
Signed integer
signed integers can represent zero, positive integers, as well as negative integers. Three
representation schemes are available for signed integers:
1. Sign-Magnitude representation
• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive
integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:
o For positive integers, the absolute value of the integer is equal to "the magnitude of the
(n-1)-bit binary pattern".
o For negative integers, the absolute value of the integer is equal to "the magnitude of
the complement (inverse) of the (n-1)-bit binary pattern" (hence called 1's complement).
Example 1: Suppose that n=8 and the binary representation 0 100 0001B.
Sign bit is 0 ⇒ positive
Absolute value is 100 0001B = 65D
Hence, the integer is +65D
Example 2: Suppose that n=8 and the binary representation 1 000 0001B.
Sign bit is 1 ⇒ negative
Absolute value is the complement of 000 0001B, i.e., 111 1110B = 126D
Hence, the integer is -126D
• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive
integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:
o for positive integers, the absolute value of the integer is equal to "the magnitude of the
(n-1)-bit binary pattern".
o for negative integers, the absolute value of the integer is equal to "the magnitude of
the complement of the (n-1)-bit binary pattern plus one" (hence called 2's complement).
Example 1: Suppose that n=8 and the binary representation 0 100 0001B.
Sign bit is 0 ⇒ positive
Absolute value is 100 0001B = 65D
Hence, the integer is +65D
Example 2: Suppose that n=8 and the binary representation 1 000 0001B.
Sign bit is 1 ⇒ negative
Absolute value is the complement of 000 0001B plus 1, i.e., 111 1110B + 1B = 127D
Hence, the integer is -127D
Hexadecimal system is used as a compact form or shorthand for binary bits. Each hex digit is
equivalent to 4 binary bits, i.e., shorthand for 4 bits, as follows:
Starting from the right-most bit (least-significant bit), replace each group of 4 bits by the equivalent
hex digit (pad the left-most bits with zero if necessary), for examples,
Given a n-digit base r number: dn-1 dn-2 dn-3 ... d3 d2 d1 d0 (base r), the decimal equivalent is
given by:
For examples,
The above procedure is actually applicable to conversion between any 2 base systems. For
example,
2. For the integral part, divide by the target radix repeatably, and collect the ramainder in
reverse order.
3. For the fractional part, multiply the fractional part by the target radix repeatably, and collect
the integral part in the same order.
Example 1:
Example 2:
Binary addition
Binary subtractions
The first number (the augend) is negative because its sign bit is set to 1. The second number (the
addend) is positive. What we are asked to do is in fact a subtraction. First, we determine which of
the two numbers is larger in magnitude and use that number for the augend. Its sign will be the
sign of the result.
Chapter Two
• A computer program is also called a computer software, which can range from two
lines to millions of lines of instructions.
• Computer program instructions are also called program source code and computer
programming is also called program coding.
• A computer without a computer program is just a dump box; it is programs that
make computers active.
There are hundreds of programming languages, which can be used to write computer programs
and following are a few of them:
• C • PHP
• C++ • Perl
• Java • Ruby
• Python
Compiler
Actually, the computer cannot understand your program directly given in the text format, so we
need to convert this program in a binary format, which can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler
and this process of conversion from text formatted program to binary format file is called
program compilation. Finally, you can execute binary file to perform the programmed task.
Interpreter
Compilers are required in case you are going to write your program in a programming
language that needs to be compiled into binary format before its execution. There are other
programming languages such as Python, PHP, and Perl, which do not need any compilation
into binary format, rather an interpreter can be used to read such programs line by line
and execute them directly without any further conversion. So, if you are going to write your
programs in PHP, Python, Perl, Ruby, etc., then you will need to install their interpreters before
you start programming.
2.2 Algorithm
An algorithm is an effective method of step by step procedure which expressed as a finite set
of well-defined instructions.
2.3 Flowchart
The flowchart is a diagram which visually presents the flow of data through processing systems.
This means by seeing a flow chart one can know the operations performed and the sequence
of these operations in a system. Algorithms are nothing but sequence of steps for solving
problems. So a flow chart can be used for representing an algorithm.
1. Sequence
The sequence is exemplified by sequence of statements place one after the other – the one above
or before another gets executed first. In flowcharts, sequence of statements is usually contained in
the rectangular process box.
Example 1: Write an algorithm and draw flowchart to read two numbers and find their sum.
Second num2
Expected output:
Algorithm:
Step1: Start
2. Branching (Selection)
It refers to a binary decision based on some condition. If the condition is true, one of the two
branches is explored; if the condition is false, the other alternative is taken. This is usually
example1: write algorithm and draw flowchart to find the greater number between two numbers
Step1: Start
Step5: Print C
Step6: End
3. Loop (Repetition)
Example1: An algorithm and draw flowchart to calculate even numbers between 9 and 99
1. Start 6. End
2. I ← 10
4. I ← I+2
2.4 Variables
A variable is a symbolic name for a memory location in which data can be stored and subsequently
recalled. Variables are used for holding data values so that they can be utilized in various
computations in a program. All variables have two important attributes:
• A type which is established when the variable is defined (e.g., integer, real, character).
Once defined, the type of a C++ variable cannot be changed.
• A value which can be changed by assigning a new value to the variable. The kind of values
a variable can assume depends on its type. For example, an integer variable can only take
integer values (e.g., 2, 100, - 12).
Example
{
workHours = 7.5;
Example
#include <iostream> cout << "What is the hourly pay rate? ";
Integer numbers
An integer variable may be defined to be of type short , int , or long . For example, on the author’s
PC, a short uses 2 bytes, an int also 2 bytes, and a long 4 bytes.
A literal integer (e.g., 1984 ) is always assumed to be of type int , unless it has an L or l and U
or u suffix, in which case it is treated as a long . For example:
92 // decimal
Real number
A real variable may be defined to be of type float or double . The latter uses more bytes and
therefore offers a greater range and accuracy for representing real numbers. For example, on the
author’s PC, a float uses 4 and a double uses 8 bytes.
double pi = 3.141592654;
A literal real (e.g., 0.06 ) is always assumed to be of type double , unless it has an F or f suffix,
in which case it is treated as a float , or an L or l suffix, in which case it is treated as a long double
.
Characters
A character variable is defined to be of type char. A character variable occupies a single byte
which contains the code for the character. For example, the character A has the ASCII code 65,
and the character a has the ASCII code 97.
char ch = 'A';
A litera l character is written by enclosing the character between a pair of single quotes (e.g., 'A'
). Nonprintable characters are represented using escape sequences. For example:
Single and double quotes and the backslash '\'' // single quote (')
character can also use the escape
'\"' // double quote (")
notation:
'\\' // backslash ( \)
Strings
A string is a consecutive sequence (i.e., array) of characters which are terminated by a null
character. A string variable is defined to be of type char* (i.e., a pointer to character). For example,
consider the definition:
2.6 Names
Programming languages use names to refer to the various entities that make up a program. We
have already seen examples of an important category of such names (i.e., variable names). Other
categories include: function names, type names, and macro names.
C++ imposes the following rules for creating valid names (also called identifiers). A name should
consist of one or mor e characters, each of which may be a letter (i.e., 'A'- 'Z' and 'a'- 'z'), a digit
(i.e., '0' - '9'), or an underscore character ('_'), except that the first character may not be a digit.
Upper and lower case letters are distinct. For example:
Reserved words
In C++ there are called reserved words or keywords and are summarized in Table.
Expressions in C++
C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side effects, such as assignment,
increment, and decrement. C++ provides five basic arithmetic operators. These are summarized
in Table.
C++ provides six relational operators for comparing numeric quantities. These are summarized
in Table.
C++ provides three logical operators for combining logical expression. These are summarized in
Table.
C++ provides six bitwise operators for manipulating the individual bits in an integer quantity.
These are summarized in Table.
The next table illustrates bit sequences for the sample operands and results in the above Table. To
avoid worrying about the sign bit (which is machine dependent), it is common to declare a bit
sequence as an unsigned quantity:
The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, a dding and subtracting 1 from a numeric variable. These are summarized in Tabl e
suppose K=5.
The assignment operator is used for storing a value at some memory location (typically denoted
by a variable). Its left operand should be left value, and its right operand may be an arbitrary
expression. The latter is evaluated and the outcome is stored in the location denoted by the left
value.
Any number of assignments can be concatenated in this fashion to form one expression. For
example:
int m, n, p;
Chapter Three
Control Structure
C++ provides control structures that serve to specify what has to be done by our program, when
and under which circumstances. With the introduction of control structures we are going to have
to introduce a new concept: the compound statement or block. A block is a group of statements
which are separated by semicolons (;) like all C++ statements, but grouped together in a block
enclosed in braces: { } :
{statement1;
statement2;
statement3 ;}
1. Selective
2. Sequential
3. Looping
4. Unconditional
Syntax
if(boolean_expression)
If the Boolean expression evaluates to true, then the block of code inside the if statement will be
executed. If Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing curly brace) will be executed.
Example 1
#include <iostream> {
int main () cout << "a is less than 20;" << endl;
{ }
// local variable declaration: cout << "value of a is : " << a << endl;
if( a < 20 )
Value of a is: 10
if...else statement An ‘if’ statement can be followed by an optional ‘else’ statement, which
executes when the Boolean expression is false.
Syntax
if(boolean_expression)
else
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Example 1
{ if( a < 20 )
// if condition is true then print the following cout << "a is not less than 20;" << endl;
else return 0;
{ }
The output as follows:
value of a is : 100
An if statement can be followed by an optional else if...else statement, which is very usefull to
test various conditions using single if...else if statement.When using if , else if , else statements
there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax
if(boolean_expression 1)
else
Example 1
#include <iostream> {
{ }
int a = 100; {
}
{
else
// if condition is true then print the following
{
cout << "Value of a is 10" << endl;
// if none of the conditions is true
}
cout << "Value of a is not matching" << endl;
else if( a == 20 )
}
return 0;
Nested if statements You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else
if’ statement(s).
Syntax
if( boolean_expression 1)
if(boolean_expression 2)
You can nest else if...else in the similar way as you have nested if statement.
Example 1
if( a == 100 ) }
{ }
// if condition is true then check the following cout << "Exact value of a is : " << a << endl;
if( b == 200 ) cout << "Exact value of b is : " << b << endl;
{ return 0;
Switch statement a ‘switch’ statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
switch(expression){
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
default : //Optional
statement(s);
Example 1
case 'D' : }
cout << "You passed" << endl; cout << "Your grade is " << grade << endl;
break; return 0;
case 'F' : }
You passed
Your grade is D
Nested switch statements you can use one ‘switch’ statement inside another ‘switch’ statement(s).
Syntax
switch(ch1) {
case 'A':
switch(ch2) {
case 'A':
break;
break;
Example
#include <iostream> cout << "This is part of outer switch" << endl;
int a = 100; cout << "Exact value of a is : " << a << endl;
int b = 200; cout << "Exact value of b is : " << b << endl;
switch(a) { return 0;
case 100: }
The? : Operator
We have covered conditional operator “? :” in previous chapter which can be used to replace
if...else statements. It has the following general form:
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ Expression is determined like this: Exp1 is evaluated. If it is true, then Exp2
is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression.
1. while loop
2. do…while loop
3. fore loop
4. nested loop
while loop Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
Syntax
while(condition)
statement(s);
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
Example 1
#include <iostream>
using namespacestd;
intmain ()
intn;
cin >> n;
while(n>0) {
--n;
return0;}
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
for loop Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax
statement(s);
Example 1
#include <iostream> }
{ }
When the above code is compiled and executed, it produces the following result:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
do...while loop Like a ‘while’ statement, except that it tests the condition at the end of the
loop body.
Syntax
do
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.
Example 1
{ } while(n != 0);
do{ }
You entered: 0
nested loops You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop up to 256 times.
Syntax
statement(s);
Example 1
The following program uses a nested for loop to find the prime numbers from 2 to 100:
int main () if(j > (i/j)) cout << i << " is prime\n";
{ }
int i, j; return 0;
2 is prime 11 is prime
3 is prime 13 is prime
5 is prime 17 is prime
7 is prime 19 is prime
23 is prime 53 is prime
29 is prime 59 is prime
31 is prime 61 is prime
37 is prime 67 is prime
41 is prime 71 is prime
43 is prime 73 is prime
47 is prime 79 is prime
83 is prime
89 is prime
97 is prime
Syntax
break;
Example 1
#include <iostream> a = a + 1;
int main () {
int a = 10; }
do return 0;
{ }
When the above code is compiled and executed, it produces the following result:
value of a: 11 value of a: 14
value of a: 12 value of a: 15
value of a: 13
continue statement causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
Syntax
continue;
Example 1
#include <iostream> {
int main () a = a + 1;
{ continue;
// do loop execution a = a + 1;
do }while( a < 20 );
{ return 0;
if( a == 15) }
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 16
value of a: 11 value of a: 17
value of a: 12 value of a: 18
value of a: 13 value of a: 19
value of a: 14
goto statement Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.
Syntax
goto label;
..
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement
that is preceded by an identifier followed by a colon (:).
Example 1
#include <iostream> {
int main () a = a + 1;
{ goto LOOP;
// do loop execution a = a + 1;
{ return 0;
if( a == 15) }
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 16
value of a: 11 value of a: 17
value of a: 12 value of a: 18
value of a: 13 value of a: 19
value of a: 14
Chapter Four
Functions
For the above defined function max(), following is the function declaration:
Example 1:
voideven (inta); }
{ {
{ }
• 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.
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:
using namespace std; cout << "Max value is : " << ret << endl;
result = num2; }
Until now, in all the functions we have seen, the arguments passed to the functions have been
passed by value. This means that when calling a function with parameters, what we have passed
to the function were copies of their values but never the variables themselves.
Example 1:
#include <iostream> cout << "Before swap, value of a :" << a <<
endl;
using namespace std;
cout << "Before swap, value of b :" << b <<
// function declaration endl;
// local variable declaration: cout << "After swap, value of b :" << b << endl;
int a = 100; return 0;
int b = 200; }
Example 1:
#include <iostream> cout << "Before swap, value of a :" << a <<
endl;
using namespace std;
cout << "Before swap, value of b :" << b <<
// function declaration endl;
void swap(int &x, int &y); /* calling a function to swap the values using
variable reference.*/
int main ()
swap(a, b);
{
cout << "After swap, value of a :" << a << endl;
// local variable declaration:
cout << "After swap, value of b :" << b << endl;
int a = 100;
return 0;
int b = 200;
}
Example 2:
#include <iostream> {
{ }
When declaring a function we 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. To do
that, we simply have to use the assignment operator and a value for the arguments in the function
declaration. If a value for that parameter is not passed when the function is called, the default value
is used, but if a value is specified this default value is ignored and the passed value is used instead.
Example 1:
using namespacestd; {
r=a/b; return0;
return(r); }
For example:
#include <iostream> {
{ return0;
return(a/b); }
Chapter Five
Bill Index 0 1 2 3 4 5 6
Value 3 4 5 6 7 7 6
#include <iostream> }
using namespace std; cout << "Element" << setw( 13 ) << "Value" <<
endl;
#include <iomanip>
// output each array element's value
using std::setw;
C++
int main ()
100
{
for ( int j = 0; j < 10; j++ )
int n[ 10 ]; // n is an array of 10 integers
{
// initialize elements of array n to 0
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] <<
for ( int i = 0; i < 10; i++ ) endl;
{ }
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 5 105
1 101 6 106
2 102 7 107
3 103 8 108
4 104 9 109
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:
Multi-dimensional Arrays
C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];
Example: type arrayName [ x ][ y ]; Where type can be any valid C++ data type and arrayName
will be a valid C++ identifier. A two-dimensional array can be think as a table, which will
have x number of rows and y number of columns.
Multidimensional arrays may be initialized by specifying brackets values for each row. Following
is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
};
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example:
The above statement will take 4th element from the 3rd row of the array. You can verify
it in the above diagram.
#include <iostream> {
using namespace std; cout << "a[" << i << "][" << j << "]: ";
{ }
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0 a[2][1]: 4
a[0][1]: 0 a[3][0]: 3
a[1][0]: 1 a[3][1]: 6
a[1][1]: 2 a[4][0]: 4
a[2][0]: 2 a[4][1]: 8
double balance[50]; balance is a pointer to &balance[0], which is the address of the first element
of the array balance. Thus, the following program fragment assigns p the address of the first
element of balance:
When the above code is compiled and executed, it produces the following result:
105 *(balance + 1) : 2
*(p + 3) : 17 *(balance + 4) : 50
*(p + 4) : 50
{ cout << "Average value is: " << avg << endl;
5.8 Structure
C/C++ arrays allow you to define variables that combine several data items of the same
kind, but structure is another user defined data type which allows you to combine data items of
different kinds. Structures are used to represent a record, suppose you want to keep track
of your books in a library. You might want to track the following attributes about each
book:
• Title
• Author
• Subject
• Book ID
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; Here is the way you would declare the Book structure:
struct Books
char title[50];
char author[50];
char subject[100];
int book_id;
}book;
cout << "Book 2 author : " << Book2.author cout << "Book 2 id : " << Book2.book_id
<<endl; <<endl;
When the above code is compiled and executed, it produces the following result:
Book 1 id : 6495407
Book 2 id : 6495700
Exercise: write a c++ code for the above structure as a function and structure as a pointer?
Chapter Six
6.1 Strings
C++ provides following two types of string representations:
If you follow the rule of array initialization, then you can write the above statement as
follows:
Easy example
{ return 0;
When the above code is compiled and executed, it produces the following result:
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.
#include <iostream> {
int len ; cout << "strcat( str1, str2): " << str1 << endl;
cout << "strcpy( str3, str1) : " << str3 << endl; cout << "strlen(str1) : " << len << endl;
strlen(str1) : 10s
#include <string> cout << "str3 : " << str3 << endl;
string str3; cout << "str3.size() : " << len << endl;
When the above code is compiled and executed, it produces result something as follows:
str3 : Hello
str3.size() : 10
6.4 Pointers
A pointer is simply the address of a memory location and provides an indirect way of accessing
data in memory. A pointer variable is defined to ‘point to’ data of a specific type. For example:
The value of a pointer variable is the address to which it points. For example, given the definitions
The symbol & is the address operator; it takes a variable as argument and returns the memory
address of that variable. The effect of the above assignment is that the address of num is assigned
to ptr1. Therefore, we say that ptr1 points to num.
Given that ptr1 points to num, the expression *ptr1 dereferences ptr1 to get to what it points to,
and is therefore equivalent to num. The symbol * is the dereference operator; it takes a pointer as
argument and returns the contents of the location to which it points.
str++ advances str by one char (i.e., one byte) so that it points to the second character of
"HELLO" , whereas ptr++ advances ptr by one int (i.e., four bytes) so that it points to the second
element of nums . The following figure illustrates this diagrammatically.
Another form of pointer arithmetic allowed in C++ involves subtracting two pointers of the same
type. For example:
using namespace std; cout << "Address of var[" << i << "] = ";
int main () cout << "Value of var[" << i << "] = ";
When the above code is compiled and executed, it produces result something as follows:
Chapter Seven
7.1 Classes
C++ provides the following classes to perform output and input of characters to/from files:
These classes are derived directly or indirectly from the classes istream and ostream. We have
already used objects whose types were these classes: cin is an object of class istream and cout is
an object of class ostream. Therefore, we have already been using classes that are related to our
file streams. And in fact, we can use our file streams the same way we are already used to
use cin and cout, with the only difference that we have to associate these streams with physical
files. For example:
// basic file operations myfile.open ("example.txt");
#include <iostream> myfile << "Writing this to a
#include <fstream> file.\n";
using namespace std; myfile.close();
return 0;
int main () { }
ofstream myfile;
The output as follows:
[file example.txt]
Writing this to a file.
In order to open a file with a stream object we use its member function open:
open(filename,mode);
Where filename is a string representing the name of the file to be opened, and mode is an
optional parameter with a combination of the following flags:
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open:
1 ofstream myfile;
2 myfile.open ("example.bin", ios::out | ios::app | ios::binary);
myfile.close();
Text file: Text file streams are those where the ios::binary flag is not included in their opening
mode. These files are designed to store text and thus all values that are input or output from/to
them can suffer some formatting transformations, which do not necessarily correspond to their
literal binary value.
// writing on a text file using namespace std;
#include <iostream>
#include <fstream> int main () {
Reading from a file can also be performed in the same way that we did with cin:
// reading a text file {
#include <iostream> cout << line << '\n';
#include <fstream> }
#include <string> myfile.close();
using namespace std; }
Chapter Eight
8.1 Classes
A classis an expanded concept of a data structure: instead of holding only data, it can hold both
data and functions.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an
object would be the variable.
Classes are generally declared using the keyword class, with the following format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
All is very similar to the declaration on data structures, except that we can now include also
functions and members, but also this new thing called access specifier. An access specifier is one
of the following three keywords: private, public or protected. These specifiers modify the access
rights that the members following them acquire:
• Private members of a class are accessible only from within other members of the same
class or from their friends.
• Protected members are accessible from members of their same class and from their friends,
but also from members of their derived classes.
• Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its
members. Therefore, any member that is declared before one other class specifier automatically
has private access. For example:
classCRectangle {
int x, y;
public:
voidset_values (int,int);
intarea (void);
} rect;
#include <iostream> x = a;
class CRectangle { }
intx, y; intmain () {
return(x*y);} return0;
}; }
The most important new thing in this code is the operator of scope (::, two colons) included in the
definition of set_values(). It is used to define a member of a class from outside the class definition
itself.
One of the greater advantages of a class is that, as any other type, we can declare several objects
of it. For example, following with the previous example of class CRectangle, we could have
declared the object rectb in addition to the object rect:
#include <iostream> }
x = a;
rect area: 12
rectb area: 30
using namespacestd; }
CRectangle (int,int); cout << "rect area: "<< rect.area() << endl;
Int area () {return(width*height);} cout << "rectb area: "<< rectb.area() << endl;
}; return0;
rect area: 12
rectb area: 30
Destructor: It is automatically called when an object is destroyed, either because its scope of
existence has finished (for example, if it was defined as a local object within a function and the
function ends) or because it is an object dynamically assigned and it is released using the operator
delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and
it must also return no value. The use of destructors is especially suitable when an object assigns
dynamic memory during its lifetime and at the moment of being destroyed we want to release the
memory that the object was allocated. For example:
using namespacestd; }
CRectangle (int,int); }
CRectangle::CRectangle (inta, intb) { cout << "rectb area: "<< rectb.area() << endl;
rect area: 12
rectb area: 30
int area (void) {return(width*height);} cout << "rect area: "<< rect.area() << endl;
CRectangle::CRectangle () { return0;
width = 5; }
height = 5;