You are on page 1of 127

CSC 315: Programming in C++

Lecture Hours: Tuesday, 8:05-10:10


Friday, 1:30-2:30----Lab session

1
Course outline
Introduction to programming in C++: Keywords, identifiers, operators
(pre & post increment & decrement operators);
variables, objects and declarations; Data types;
Control structures; Pointers and references; arrays;
Functions (definition, declaration and calls);
Object-Oriented Programming (Classes, Objects, Inheritance,
Polymorphism).

2
Lecture 1, 2Hrs

09/10/2017 3
09/10/2017 4
Review
•What is a computer?
•What is information processing cycle?
• Input, Process, Output, Storage, Communication
•Hardware and Software
•What is a computer program?
• Program:
•A program is a sequence of instructions, written to perform a specified task with a computer.
•set of instructions that can be interpreted by a computer
• Instructions: well-formed sequences of characters (syntax)
• Interpretation: sequence of operations performed by the computer hardware according to an
instruction or set of instruction (semantics)

5
•Types of Computer Programs
•System Software (OS, Device drivers)
•Application software (MS Office, Games)
•variant called the programming languages

•Programming language: set of rules used to form valid instructions (Programs)


•procedural/structural, object-oriented programming languages
•Java, Microsoft Visual basic, C Sharp, C++, etc.

•Mode of Usage: GUI, Console/command prompt (C, C++)

09/10/2017 6
Introduction to C++
•C++ pronounced see-plus-plus is the object oriented extension of the C
programming language.
•It is one of the newest and most powerful programming languages that allow
programmers to create efficient, structured, and object oriented programs.
•Flavours of compilers:
Microsoft Visual C++ (part of Microsoft Visual Studios).
GNU license based compilers – g++.
•Difference between compliers is the origin and nature of programming
environment (IDE).
•They all share the same syntax, semantics, and standard library files.
•C++ programs are portable (run on any platform)
•Programmers master how to write the program itself and how to use standard
7
•Good programming requires mastering how to write the
program itself and how to use standard library files. What are
SLFs?

Elements of a C++ program

09/10/2017 8
Explanation
•#include
•The #include is a preprocessor directive, which is a message to the C++
preprocessor to make available to the program unit the standard library file
defined in-between the < > symbols.
•In this case the input/output stream header iostream.
•The input/output stream header iostream must be included in all
programs.
•I/O is not available in the kernel of the language. It is made available by the
inclusion of iostream header file.
•Other standard library files, such as the cmath library are included using
this same method. 9
•The std namespace
•The statement using namespace std; brings the std namespace into visibility.

•The purpose of a namespace is to localise the names of identifiers to avoid name


collision.

•For instance, content of the iostream header (cout, cin, and cerr) are place in
the std namespace.

•The statement must be included in every program that uses the I/O stream names
(cout, cin, and cerr) and other library functions.

• Programs that do not include the statement using namespace std; can however,
use cout, cin, and cerr by prefixing them with the std name as follows:
•std::cin>>s;
•std::cout<<"Welcome to see-plus-plus\n"; 10
•int main() {…}
•Every C++ program must contain this function.
•It marks the start of the program itself and all executable code must be entered
within the curly brackets.
•Except the definition of other functions that can be done outside it.
•There may be several other functions in a C++ program, but they will always
be called and executed within the main() function.
•The keyword int before main indicates that main will always “return” an
integer (whole number) value.
•The left brace, { indicates the start of the main() function’s body and the
corresponding right brace }indicates the end of the body.
•The body of every function in C++ begins with { and ends with }. 12
•Output/input streams
•The name cin is called an input stream and >> is the input stream operator.
•The statement cin>>s; is an input statement and is used to accept input from
the keyboard. cin stands for console input.
•In the above program it accepts the value of s, which is the name, Moses.

•cout is the standard output stream, which represent the computer display
screen.
•The symbol << is the stream insertion or output operator. cout stands for
console output.
•The statement cout<<s<<"! welcome to see-plus-plus\n"; prints
the value of s and the welcome message to the screen. 13
return (0); or return 0;
•The return statement indicates that the end of the main function is reached
• and thus, terminates the program or exits the function and return control to the operating
system.
•It also shows that the program was successfully executed by outputting a return value on the
console. This statement is however, not required by all compilers.
Comments
•Comments are used to document the various sections of a program so as to help other people to
read and understand our code.

•Comments that begin with // are single-line comments because they terminate at the end of the
current line.

•These comments are referred to as the C++ style comments.

•Comments that spans multiple lines begins with /* and with */. These are called C style
14
comments.
Statements
•The actual C++ program resides in the statements.
•Each statement can span multiple lines of texts.
•cout<<"Welcome to see-plus-plus\n";
•cin>>s;
•string s;
•are all statements.
•All statements in C++ must end or be terminated by a semicolon ‘;’.

15
Good Programming Guidelines
● Always adhere to good code (text) formatting.
● Use indentation: it makes code readable, hence easy to understand.
#include <iostream>
using namespace std;

int main()
{
declaration 1;
declaration 2;
.
.
execution statement 1;
execution statement 2;
.
.
return (0);
}
C++ Data Types
●The need always arise for us to use data in our programs.
●Each type of data requires different size of memory allocation and

●also possess different characteristics.


Fundamental Data Types in C++
● They are summarised in the table below:
Name Description Size Range

char Character or small integer 1 byte Signed: -128 to 127


unsigned: 0 to 255
short int Short integer 2bytes Signed: -32768 to 32767
unsigned: 0 to 65535
(short)
int integer 4bytes

long int (long) Long integer 4bytes

Bool Boolean value. It is either true or false. 1byte True or false

float Floating point number 4bytes

double Double precision floating point number 8bytes

long double Long double precision floating point number 8bytes

wchat_t Wide character 2 or 1 wide character


4bytes
The string data type (string, character string, or string literal)
● The string data type is a non-numeric data type.
● is a collection or sequence of characters between double quotation marks.
● E.g. “see plus-plus”, “programming 4 u” are strings.
●White-space characters in strings are not ignored (are counted as characters) by
the compiler.
● string is not a fundamental data type,
● therefore access to the string data type is provided in the <string> header file.
● Functions:
–determinethe length of strings, insert/delete characters/strings , concatenated
two or more string literals, among others.
09/10/2017 20
Variables; Declaration and Initialisation
Variables
•A variable is a symbol that represents a storage location in the computer’s
memory.
•The information stored in that location is the value of the variable.
•Every variable in C++ must be declared before it can be used.
Syntax: data_type variable_name=expression;

22
● Declaration
● Initialisation
•Identifiers
•An identifier is a series of characters consisting of letters, digits, and
underscores (_) that does not begin with a digit and is not a reserved word.
•A variable name is any valid identifier.
•That is, any valid variable name is also called an identifier.
•For example, variable names such as x, y, number1, _Fname,
num_3, and your_age_1 are valid identifiers.
•Remember that C++ is case sensitive, so _fname and _Fname are two
different identifiers.

09/10/2017 25
Keywords
●Reserved words: these are words that are kept by the programming language for
special purposes and cannot be redefined for use as variables or for any other
purpose.
●Keywords are a subset of reserved words that can be mandatorily used when the
need arises.
●For example, words such as using, int, double, char, namespace
are keywords and cannot be used for any other purpose.
●C++ is case sensitive and thus, keywords must always appear in all lowercase
letters.
●The keyword using cannot be written as Using and int is not the same as
Int.
27
Declaring String variables and String Manipulation

29
•The table below provides a summary of some basic string functions:
String function Explanation
int s.length( ) Returns length of string s.
string s.substr (int start, int Returns substring of s that starts at position
len) start and has length len.
s.insert (int start, string s2) Inserts string s2 into s at starting position start.
s.erase (int start, int len) Deletes the substring from s starting at position
start of length len.
int s.find (string s2, int start) Returns starting position of substring s2 in s,
starting search from position start of s.

•Write down the output of the following statements


i.cout<<s.substr(1,3);
09/10/2017 30
•Declaring numeric data type variables

•The output of this program is:


45.45
45.45+20.40=65.85
09/10/2017 32
Keywords and identifiers
•Every program is comprised of individual syntactic elements called tokens.
•These include constants, variable names, operators, keywords and punctuation
marks.
•Just like in natural spoken languages, there are rules and regulation governing
the creation and use of syntactic elements (words) in C++ programming
language.
•Reserved words: these are words that are kept by the programming language
for special purposes and cannot be redefined for use as variables or for any other
purpose.
•Keywords are a subset of reserved words that can be mandatorily used when
the need arises.
•For example, words such as using, int, double, char,
33
34
•Identifiers
•An identifier is a series of characters consisting of letters, digits, and
underscores (_) that does not begin with a digit and is not a reserved word.
•A variable name is any valid identifier.
•That is, any valid variable name is also called an identifier.
•For example, variable names such as x, y, number1, _Fname,
num_3, and your_age_1 are valid identifiers.
•Remember that C++ is case sensitive, so _fname and _Fname are two
different identifiers.

09/10/2017 35
Lecture 3, 2Hrs

09/10/2017 36
C ++ OPERATORS

Arithmetic operators
•An operator is a symbol that “operates” on one or more expressions or
operands, producing a value that can be assigned to a variable.
•Arithmetic operators are some of the simplest operators in C++.
•These arithmetic operators include +, *, /, -, and %.
•Arithmetic operators are binary operators, i.e., operators that take two
operands.
•E.g. the expression x+y contains the binary operator + and two operands x
and y.

37
•These operators are summarised below:

C++ operation C++ arithmetic C++ expression


operator
Addition + f+8
Subtraction - p-c
Multiplication * b*m
Division / x/y
Modulus % r%s

09/10/2017 38
•The example below illustrates how arithmetic operators can be used:

39
•Adding, multiplying, subtracting, dividing integer and floating-point yields floating
point.
•Integer division yields an integer quotient if both the numerator and denominator are
integers,
•e.g. 7/4 evaluates to 1 and 17/5 evaluates to 3.
•Any fractional part in integer division is discarded or truncated (i.e. no rounding up
occurs).
•Use Typecasting

•Modulus operator %, this operator in C++ yields the remainder after integer division.
•This operator can only be used with integer operands.
•The expression 7%4 yields 3 and 17%5 yields 2.

•Arithmetic expressions in C++ must be entered in straight-line form. E.g. is not


40
Precedence of arithmetic operators
•This refers to the magnitude attached to one operator over the others.
• That is, if an expression contains more than one operator, which operator would be
executed first, second, …, in that order?
Operator(s Operations Order of evaluation
)
() Parentheses Evaluated first. If the parentheses are nested in the
expression inner most pair is evaluated first
*, /, % Multiplication, Evaluated second. If there are several, they’re evaluated
Division, from left to right.
Modulus
+ Addition Evaluated last. If there are several, they’re evaluated from
•For
- example, how would the expression
Subtraction left to right.2*4-8/2+3 be executed in C++?

09/10/2017 41
Assignment (=) and Compound Assignment Operators
•C++ provides several compound assignment operators for abbreviating assignment
expressions.
•E.g., the statement m=m*2; can be rewritten as m*=2; using the multiplication compound
assignment operator *=.
•This statement adds the value of the expression on the operator’s right to the current value of
the variable on the operator’s left and stores the final value back on the left-side variable.
•*=, -=, /=, and %= are all compound assignment operators.

09/10/2017 42
•Increment and Decrement operators
•Another set of operators provided by C++ are the two unary operators (++ and --) that are used
to either add 1 to a numeric variable or subtract 1 from the value of a numeric variable.

•++ is called the unary increment operator and -- decrement operator.


•These operators are summarised below.

Operator Called Expression Explanation


++ Preincrement ++a Increment a by 1, then use the new value of a in the expression in
which a resides
++ Postincrement a++ Use the current value of a in the expression in which a resides,
then increment a by 1.
-- Preincrement --b Decrement b by 1, then use the new value of b in the expression
in which b resides
-- Postincrement b-- Use the current value of b in the expression in which b resides,
then decrement b by 1.
43
Output
5
5
6

5
6
6

44
Equality and Relational operators
•These operators are mainly used to compare two items in order to make a correct
decision.
•For instance, to compare the age of two individuals to determine who is older in order
to compute their age allowance.
Standard algebraic equality and C++ equality and Sample C++ Meaning of C++ condition
relational operator relational operator condition
Relational operators
> > x>y x is greater than y
< < x<y x is less than y
≥ >= x>=y x is greater than or equal to y
≤ <= x<=y x is less than or equal to y
Equality operators
= == x==y x is equal to y
≠ != x!=y x is not equal to y
45
Caution:
•Reversion the order of the pair of symbols in the operators !=, >= and <= (by
writing them as =!, => and =< respectively) will normally result to a syntax error.
•In some cases, writing != as =! may not be interpreted by the compiler as a
syntax error but will most definitely be a logical error that can affect the program
at execution time.
•Care must also be taken not to confuse the equality operator == with the
assignment operator =.

46
Control Structures/statements
•Normally, statements in a C++ program execute one after the other in the order
in which they are written. As in examples considered so far.
•These are called sequential statements.
•However, this is always not the case in most real-life programs.
•There is always the need for more flexible programs in which the execution of
some statements depend on conditions that change while the program is running.
•To meet this flexibility demand of programs, control structures are normally
used.
•These include the conditional/selection control structures and repetition control
structures or statements.
09/10/2017 47
Selection statements/control structures
•C++ provides three types of selection statements namely:
•if, if…else, and switch statements.

•The if statement
•The if selection statement is a single-selection statement that allows conditional
execution by either selecting or ignoring a single action or a single group of
actions.
•The syntax of the if statement is:
if(condition)
statement(s);

48
•Where condition is a Boolean expression and statement is any executable
•This program used the if statement to evaluate the exams score of a student and
prints Passed if the score is greater than or equal to 60 or exits if false.

49
•The program below compare two numbers using six independent if statements. If any of the
if statements is satisfied the output statement associated to it is executed.

Number1=3,
number2=7
3!=7
3<7
3<=7
Number1=22,
number2=12
22!=12
22>12
22>=12
50
•The if…else selection statement
•The if…else statement is called a double-selection statement
•because it selects between two different actions (or group of actions) depending
on the value of a condition.
•That is, it performs an action if the condition is true and a different action if the
condition if false.
•The syntax of the if…else statement is
if(condition)
statement1;
else
statement2;

51
•The program below uses the if…else control structure,
•it evaluates a student’s grade and if it is greater than or equal to 60 (condition
is true) it prints Passed and
•if it is less than 60 (condition is false) it prints Failed.

09/10/2017 52
Compound statements
•This is a sequence of statements that is treated as a single statement.
•Compound statements in C++ are enclosed in curly braces. E.g.
{
int temp=x;
x=y;
y=temp;
} //is a compound statement.

•The following program uses compound statements to sort two integers in


increasing order.

53
54
Nested if…else statements (conditions)
•Nesting if…else statements simply means placing some if…else statements
inside another if…else statement in order to test multiple cases.
•For example, the following code evaluates a student’s exams score and prints out
the corresponding grade using nested if...else statements.

55
•Revisit the example that finds the maximum of three integers. Below is an
implementation of this problem using nested if…else statements:

56
Logical Operators
•So far, we have treated only simple conditions, such as counter<=10,
total>150, and number!=value.
•These conditions are expressed in terms of relational operators >, <, >=, and
<=, and equality operators == and !=.
•Using these operators each condition is tested precisely once.
•As a result multiple conditions are tested in separate statements or in nested if
or if…else statements.
•Testing multiple conditions using several statements can be avoided by
combining these simple conditions to form compound or more complex
conditions using logical operators such as &&(AND), ||(OR), and !(NOT).
57
•To ensure that two conditions are both true before choosing a certain path of
execution, the && (logical AND) operator is used as follows:
if(gender==’F’ && age>=65)
cout<<“Senior female citizen”;
•In this if statement the simple condition to the left of && operator evaluates first
and the condition to right evaluates next if and only if the first condition is true.
•The output statement is then executed if both conditions are true.
•Also, to ensure that either or both of two conditions are true before choosing a certain
path of execution, the || (logical OR) operator is used. E.g.
if((semesterAverage>=90)||(finalExam>=90))
cout<<“Student grade is A”<<endl;
09/10/2017 58
•C++ provides the ! (logical NOT) operator to “reverse ” a condition’s meaning.

•These 3 logical operators are defined by the truth tables below.

&& truth table || truth table ! truth table


p q p&&q p q p||q p !p
1 1 1 1 1 1 1 0
1 0 0 1 0 1 0 1
0 1 0 0 1 1
0 0 0 0 0 0

• The program below finds the maximum of three integers using the && operator.
59
Output: Enter three integers : 4 5 1
5 60
•The program below uses the logical OR operator to enable a student input
either a Y or y for “yes”

Output: Are you a student? N


You are not a student 61
Common Pitfall using if statements
● Forgetting that C++ comparisons are case sensitive
● Adding an unwanted semicolon
● Forgetting curly braces
● Using = instead of ==
● Making unnecessary comparisons
● Creating unreachable code
● Forgetting that C++ comparisons are case sensitive
● Adding an Unwanted Semicolon, and Forgetting Curly Braces
09/10/2017
● Making unnecessary comparisons
● Creating unreachable code
The switch selection statement
•Its objective is to check several possible constants against the value of an expression for a
possible match.
•It is similar to the concatenation of several if and else if instructions, but has only one value to
which all constants are compared to.
switch (expression){
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;

default:
default group of statements
} 69
•Note that the case constants must be integers or expressed in integer equivalent.
•In the case of characters, they must be declared as integers (see ASCII char set)
•The table below shows a switch example and its if-else equivalent

switch (x) { if (x == 1) {
case 1: cout << "x is 1"; cout << "x is 1";
break; }
case 2: cout << "x is 2"; else if (x == 2) {
break; cout << "x is 2";
default: cout << "value of x }
unknown"; else {
} cout << "value of x unknown";

70
•Conditional operator (?:)
•C++ provides the conditional operator, which is closely related to the if …
else control structure.
•The conditional operator takes three operands, the operands together with the
conditional operator form a conditional expression.
•It has the following syntax:
(condition ? “action if true” : “action if false”)
•The 1st operand is a condition, the 2nd is the action to be taken if the condition is
true and the 3rd operand is the action to be taken if the condition is false.
•E.g. cout<<(grade>=60 ? “Passed” : “Failed”);
•contains a conditional statement (grade>=60 ? “Passed”
71 :
Iteration structures (loops)
•In programming, a situation may arise that requires us to repeatedly execute a set
of statements a defined number of times.
•E.g. to calculate the salary of employees, the factorial of integers, the sum of
integers, etc.
•Main iteration structures include: while, do…while, and for loops.

•The while loop


•The format of the while loop is:
while (condition)
statement(s);
•First the condition is evaluated, if it’s true the statement is executed and the
condition is evaluated again.
•These two steps are repeated until the condition evaluates to zero or false. 72
•The following program implements a countdown using a while loop

09/10/2017 73

74
•The do…while statement
•The do…while statement is similar to the while statement.
•The difference however, is on the structure of the do…while statement.
•In the while statement, the loop-continuation condition test occurs at the
beginning of the loop before the body of the loop executes,
•but in the do…while statement, the loop-continuation test comes after the loop
body, therefore, the loop body always executes at least once.
•Syntax of the do…while statement is as follows:
do
statement
while(condition);

•To avoid confusion the last line, while(condition); as the header of a


while statement, it is advisable to always write a do…while statement as,75
•The following program uses a do…while statement to print integers from 1-10.

76

77
•The for statement
•The for repetition statement, uses a counter-controlled repetition whose details
are specified in a single line. The syntax is as follows:
for(initialization; condition; increment/decrement)
{
Statement(s);
}
•The for statement works in the following manner.
1. initialization: Generally it is an initial value setting for a counter
variable and is executed only once.
2. condition is checked for each iteration, if it is true the loop continues,
otherwise it ends and exits.
3. statement is executed if condition is true. As usual, it can be either
78 a
•The countdown program above is implemented using for loop as follows.

79
•The sum of squares program above implemented using a for loop is as follows:

80
09/10/2017 81
Functions
•Most computer programs that solve real-world problems are much larger and
complex than the programs presented so far.
•The best way to develop and maintain a larger program is to construct it from
small, simple pieces, or components.
•This technique is called “divide and conquer” or more formally, program
modularization.
•Functions allow us to modularize a program by separating its tasks into self-
contained units.
•Each function in a program is written only once, called and used from several
locations in the program and are hidden from other functions.
82
•A few motivations for modularizing a program with functions include; to
1. enable software reuse,
2. avoid repeating code,
3. make programs easier to debug and maintain.
•There are two main types of functions in C++
•the predefined functions and
•user-defined or programmer-defined functions.

09/10/2017 83
•Predefined Functions
•Predefined functions are those that have already been implemented and added to
the C++ compiler and are made available in groups as standard library files.
•Use of these functions require the inclusion of a header file,
•which contains function prototypes, constant definitions and macros.
•E.g. <iostream> header file used in all of the examples so far.
•Also, the <cmath> or <math.h> header files provides a collection of
predefined functions that enable us to perform common mathematical
calculations.
•Function arguments may be constants, variables or complex expressions.
•E.g. sqrt((a+b)/(c*d+b)).

84
•The program below illustrate how to use trigonometric functions in the cmath
library.

85
•User-defined functions
•A user –defined function is a group of statements created by the user to perform a
specific task and can be called and used from any part of the program.
•User –defined functions have the following syntax:
type name(parameterl, parameter2, ...) {
statement(s)
}
•type is the data type of the data to be accepted or returned by the function.
•name is the identifier by which it will be possible to call the function (i.e. the
name given to the function).
86
•parameters (as many as needed) specifies the number of and type of data to
s

87
•A parameter refers to a variable declared in the prototype of a function. For
instance in the program above, the addition () and subtraction ()
functions are defined as follows:
int addition (int a, int b)
and
double subtraction (double a, double b)
•in these functions a and b are called parameters.
•An argument is the value that is passed to the function in place of a parameter
when the function is called.
•The statement: z=addition (5, 3); on line 20, the values 5 and 3 are
arguments passed to the function addition ().
•Also, in the statement: cout<<”The third result is
“<<subtraction(x, y)<<’\n’; x and y are arguments passed to the88
•The use of void
•The keyword void is used in place of function type if we do not want our
function to return a numeric results.
•E. g. if our function is just to print a message on the screen.

89
•Function Overloading
•Is a technique in which two or more functions in a program are given the same
name.
•This is however, possible if:
1. their parameter types are different or
2. the number of parameters are different.

90
09/10/2017 91
Passing Arguments to Functions
•by value and
•by reference

•By default, arguments in C++ are passed by value.


•When an argument is passed by value, a copy of the argument’s value is made
and passed to the called function.
•Changes to the copy do not affect the original value of the variable.
•So far, in all the examples considered the arguments are passed by value.

09/10/2017 92
•By reference
•It is the variable itself that is passed to the function
•Any modification that is made to the function’s local variables will have an
effect on the variables passed as arguments to the function.
•To pass variables by reference they are preceded by ampersand sign in the
function definition as follows:
void operate(int &num, int &num1, …)

93
94

● x=1, y=3, z=7 x=2, y=6, z=14. 95


Advantage of passing by value
✔Arguments passed by value can be variables (e.g. x, y, z), literals (e.g. 5, 3), or
expressions (e.g. x+1).
✔Arguments are never changed by the function being called, which prevents
inadvertent modification of values of variables.

Disadvantages of passing by value:


✔Copying large structs or classes can take a lot of time to copy, and this can
cause a performance penalty, especially if the function is called many times.

96
Advantages of passing by reference:
✔Itallows us to have the function change the value of the argument, which is
sometimes useful.
✔Because a copy of the argument is not made, it is fast, even when used with large
structs or classes.
✔We can pass by const reference to avoid unintentional changes.
✔We can return multiple values from a function.

Disadvantages of passing by reference:


✔Because a non-const reference cannot be made to a literal or an expression,
reference arguments must be normal variables.
✔It’s impossible to tell from the function call that the argument may be changed.
Default Arguments
When declaring a function, a default value can be specified for each of the
parameters. This value will be used if the corresponding argument is left blank
when the function is called.
To do that, values are assigned to 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 the default value is ignored and the passed value is used
instead. For example:
99
•Inline Function
 functions are good from the software engineering standpoint, but function call
involve execution-time overhead.
 inline functions reduce function call overheads especially for small functions.
By generating copies of the function’s body code in place where appropriate
Trade-off: The program becomes larger due to multiple copies of fucntion’s
code
The compiler can ignore the inline qualifier and typically does so for all but
the smaller functions.
It is a best practice to place all reusable inline functions in the headers.

100
101
Recursion.
•Recursion is the property that functions have to be called by themselves.
•It is useful for many tasks, like sorting or calculating the factorial or Fibonacci
series of numbers.
•For example, to obtain the factorial of a number (n!) the mathematical formula
would be: n! = n * (n-1) * (n-2) * (n-3) ... * 1
•more concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
•Recursive function to calculate this in C++ could be:

102
103
•Arrays
 An array is a series of elements of the same type placed in a consecutive group
of memory locations that can be individually referenced by adding an index or
subscript to a unique identifier or array name.
That is, an index or subscript is the position number of a particular element in an
array.
Declaring Arrays
To specify the type of the elements and the number of elements required by an
array use a declaration of the form:
type arrayName[arraySize];
The arraySize must be an integer constant greater than zero. E.g., to tell the
compiler to reserve 12 elements for integer array c, use the declaration
int c[12]; // c is an array of 12 integers 105
Initializing Arrays
When declaring a regular array of local scope (within a function, for example),
if we do not specify otherwise, its elements will not be initialized to any value by
default, so their content will be undetermined until we store some values in them.
The elements of global and static arrays, on the other hand, are automatically
initialized with their default values, which for all fundamental types this means
they are filled with zeros.
In both cases, local and global, when we declare an array, we have the
possibility to assign initial values to each one of its elements by enclosing the
values in braces { }. For example:
int age[6]={24, 12, 35, 76, 2, 12};
int age[]={24, 12, 35, 76, 2, 12};
In the second case, the number of elements is omitted, this is allowed and the
106
compiler will assume a size for the array that matches the number of values
An array initialized with empty braces {} will have zeroes as its elements.
Arrays are zero indexed, that is the first element in an array has an index of 0.
the second element thus has index 1, third index 2 and the nth index n-1.
To access an element in an array, the name of the array is specified followed by
the index of the element in square brackets as. int x=age[3] this assigns the
fourth element (76) in array age to x.
The index of an element in an array should not be confused with the number of
elements in an array specified during its declaration as in the declaration of array
age above.

107
The following example illustrates how to
–declare,

–initialize,

–access and
–use
elements in arrays.
The example declares and initializes an array age
–with the current age of six individuals,
–computes their age in ten years' time and
–assigns the resulting ages to the respective locations in array age10yrs
109
●The next program uses arrays to summarize the results of data collected in a
survey using the following problem statement:

●Twenty students were asked to rate on a scale of 1 to 5 the quality of food in a


student’s cafeteria, with 1 being awful, 2 somehow, 3 good, 4 very good, and 5
excellent. The 20 responses are placed in an integer array as follows:
● const int responses[20]={1, 2, 5, 4, 3, 5, 2, 1, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 2, 5}.

●Write a program to determine the frequency of each rating (the number of


times each rating occurred in the array).
112
114
115
09/10/2017
•Passing Arrays to Functions
For a function to receive an array through a function call, the function’s
parameter list must specify that the function expects to receive an array. E.g., the
function header for function modifyArray might be written as
void modifyArray(int b[], int arraySize)
Indicating that modifyArray expects to receive the address of an array of
integers in parameter b and the number of array elements in the parameter
arraySize.
The array’s size is not required in the array brackets, []. If it’s included the
compiler ignores it. Thus, arrays of any size can be passed to the function.
C++ passes arrays to functions by reference, when the called function uses the
array, in this case named b, it refers to the actual array in the caller. Thus, the
called functions can modify the element values in the caller’s original arrays.
However, individual array elements may be passed by value exactly as simple 117
To pass an array argument to a function, specify the name of the array without
any brackets. E.g., if the array hourlyTemperatures has been declared as
int hourlyTemperatures[24];
the function call
modifyArray(hourlyTeperatures, 24);
Passes array hourlyTemperatures and its size to function modifyArray.
When passing an array to a function, the array size is normally passed as well,
so the function can process the specific number of elements in the array.

The following program passes an array to function called linearSearch that


searches through the array to find a particular array element given a search key.
The searching technique used is called Linear Search.
118
(35) // Linear search of an array
#include <iostream>
using namespace std;

int linearSearch(const int [], int, int); //prototype


int main()
{
const int arraySize=100;
int a[arraySize]; //create array a
int searchKey; //value to locate in array

for(int i=0; i<arraySize; ++i) 119


//attempt to locate searchKey in array a
int element=linearSearch(a, searchKey, arraySize);

//display results
if(element!=-1)
cout<<“Found value in element ”<<element<<endl;
else
cout<<“value not found”<<endl;
} //end main
//compare the key to every element of array until
location is found or //end of array. Return index of
//element if key is found or -1 if key is //not found.
120
int linearSearch(const int array[], int key, int
Using 2d arrays as arguments
This example looks at several functions, each of which takes a 2 dimensional
array as an argument.
(36) #include <iostream>
using namespace std;

void readdata(int a[][5],int n, int m);


int sum(int a[][5],int n, int m);
void printdata(int a[][5],int n, int m);

void readdata(int a[][5],int n, int m){


for (int i=0; i<n; ++i) 121
int sum(int a[][5], int n, int m){
int s=0;
for (int i=0; i<n; ++i)
for (int j=0; j<m; ++j)
s+= a[i][j];
return(s);
}

void printdata(int a[][5],int n, int m){


for (int i=0; i<n; ++i){
for (int j=0; j<m; ++j)
cout << a[i][j] << “ “; 122
int main()
{
int n=5;
int m=5;
int a[5][5];
int s=0;

readdata(a,n,m);
s=sum(a,n,m);
printdata(a,n,m);

cout << " sum is " << s << endl; 123


•Pointers: Reading Assignment
Read about pointers;
What they are,
How they are used and
Why they are used in C++

124
•Object Oriented Programming (OOP)
Procedural/structured programming provides tools to solve a broad variety of
problems in engineering and technology. It’s efficiency is however, significantly
decreased it is used in large and complex programs.
OOP technology is much more efficient than procedural technology when
dealing with large and complex programming problems.
Its approach to problem solving is similar to the logic applied when solving
real-life problems and is quite different from artificial procedural logic.
Procedural programming techniques is focused on program’s functionality, i.e.
functions to be followed in order to solve a problem. How to represent data is not
of primary concern. Thus PP is a collection of functions or procedures with an
open flow of data among them.
Hence applying PP in a large, complex program may lead to a variety of
problems such as 125
Difficulty in debugging the program and following its logic.
Creation of logic errors such as inadvertent data modification.
OOP provides the tools to overcome these problems. Its concepts are based on
the use of objects.
An object is a single entity that groups together related data and functions that
operate on that data.
Objects can be found everywhere in real life. They may be physical objects such
as a computer or a spacecraft, or nonphysical objects such as an e-mail message or
a vector in mathematics.
An OOP program can therefore be described as a collection of objects that
communicate with each other through their interface functions.
OOP technology implements the following important concepts:
Encapsulation, Inheritance, and Polymorphism. 126
•Encapsulation is the concept of binding together data and functions into one
capsule or object. This concept is also known as data abstraction. Its
implementation enables data hiding, which means an object can hide its data
from the rest of the program and provide access to the data only through its
interface functions.
This reduces the possibility of inadvertent data modification and various kinds
of logic errors.
•Inheritance is one of the most important OOP tools in the implementation of
code reusability. When using inheritance, new code can be derived or inherited
from existing code.
This reduces the amount of coding and the size of the program.
•Polymorphism is the concept of using the same functions on different types of
objects.
This enables C++ programmers to reduce program development time.
127

You might also like