0% found this document useful (0 votes)
37 views81 pages

CSC 202 C++

The document discusses several programming principles including DRY, KISS, YAGNI, SOLID, and others. It also covers basic C++ program structure and examples including printing text and calculating averages. Key principles are to avoid duplication, keep code simple, and only implement necessary features.

Uploaded by

sadiqaminu931
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views81 pages

CSC 202 C++

The document discusses several programming principles including DRY, KISS, YAGNI, SOLID, and others. It also covers basic C++ program structure and examples including printing text and calculating averages. Key principles are to avoid duplication, keep code simple, and only implement necessary features.

Uploaded by

sadiqaminu931
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Federal University Gusau, Zamfara State

Department of Mathematical Sciences


Faculty of Sciences

CSC 202
Computer Programming (CP) II
Complete lecture note

Prepared
By

Mal. Kabiru Usman

1
Principles of good programming

Overview
Programming principles have helped many developers over the years and they becoming a better
programmer, and I believe, this programming principles will help a developers to become more
efficient and able to produce code which is easier to maintain. By following these coding
principles, you can save development and maintenance time.
What are the Programming principles?
• Programming is the process of coding, testing, troubleshooting, debugging and
maintaining a system.
• Programming principles help us to write excellent quality of code and maintain a good
coding practice
Why should a developer follow the principles?
• Actually, writing programs is often a matter of personal taste but there are certain
principles or guidelines that should be followed within your own style in order to make
programs easy to maintain and understand by both, you and others, and also principles
guide the creation of stable, scalable, and robust code.
What are the benefits if developer followed it?
• Readability:
All developers were in a team able to understand the code.
• Extensibility
In the software world, we should not blame the change requests; it’ll come at any time.
So our code is always easy to extend without breaking existing business rules.
• Maintainability
It’s easy to maintain by the development team and the production support team too
because the application is loosely coupled.
• Modularity
Divide a program into reusable pieces: functions, modules, libraries

2
Types of Programming Principles
DRY (Don’t-Repeat-Yourself)
Duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.
"Every piece of knowledge must have a single, unambiguous, authoritative representation within
a system". In other words, a piece of logic should only be represented once in an application.
• Duplication is the root of all software evils.
• Duplication is a waste
KISS (Keep It Simple, Stupid)
• Nowadays programming languages, frameworks, and APIs have powerful means to
create sophisticated solutions for various kinds of problems. Sometimes developers might
feel tempted to write “clever” solutions that use all these complex features.
• The KISS principle states that most systems work best if they are kept simple rather than
making them complex; therefore simplicity should be a key goal in design and
unnecessary complexity should be avoided.
• This principle can be applied to any scenario, including many business activities, such as
planning, designing, and development.
YAGNI (You Aren’t Going to Need It)
• As developers, we'll always think a lot about the future usability of the project and try to
do some extra features coding in a mind that “just in case we need them” or “we will
eventually need them”.
• Just one word… Wrong! I’ll repeat it this way: You didn’t need it, you don’t need it, and
in most of the cases… “You Aren’t Going to Need It”.
• YAGNI states that "don’t implement something until it is necessary".
• There are two main reasons to practice YAGNI,
• You save time because you avoid writing code that you turn out not to need.
• Your code is better because you avoid polluting it with 'guesses' that turn out to be
more or less wrong but stick around anyway.
SOLID
• SOLID principles are the design principles that enable us to manage with most of the
software design problems.
• Robert C. Martin compiled these principles in the 1990s.

3
• These principles provide us ways to move from tightly coupled code and little
encapsulation to the desired results of loosely coupled and encapsulated real needs of a
business properly.
• SOLID principle supports good object-oriented design and programming. Five of these
principles are described as SOLID:
• S: Single responsibility,
• O: Open-closed,
• L: Liskov substitution,
• I: Interface segregation, and
• D: Dependency inversion.
Single Responsibility
• A component of code (e.g. class or function) should perform a single well defined task.
• SRP says "Every software module should have only one reason to change".
• This means that every class, or similar structure, in your code should have only one job to
do. Everything in that class should be related to a single purpose.
Open/Closed Principle
• Software entities (classes, modules, functions, etc.) should be open for extension, but
closed for modification. In other words, don't write classes that people can modify, write
classes that people can extend.
• "Open for extension" means, we need to design our module/class in such a way that the
new functionality can be added only when new requirements are generated.
• "Closed for modification" means we have already developed a class and it has gone
through unit testing.
Liskov Substitution Principle
• The Liskov Substitution Principle (LSP) states that "you should be able to use any
derived class instead of a parent class and have it behave in the same manner without
modification".
• It ensures that a derived class does not affect the behavior of the parent class, in other
words that a derived class must be substitutable for its base class.
• This principle is just an extension of the Open Close Principle and it means that we must
ensure that new derived classes extend the base classes without changing their behavior.

4
Interface Segregation Principle (ISP)
• The Interface Segregation Principle states "that clients should not be forced to implement
interfaces they don't use.
• Instead of one fat interface many small interfaces are preferred based on groups of
methods, each one serving one sub module."
• Means an interface should be more closely related to the code that uses it than code that
implement it.
• So the methods on the interface are defined by which methods the client code needs
rather than which methods the class implements. So clients should not be forced to
depend upon interfaces that they don't use.
Dependency Inversion Principle
• The Dependency Inversion Principle (DIP) states that high-level modules/classes should
not depend on low-level modules/classes.
• Both should depend upon abstractions.
• Secondly, abstractions should not depend upon details.
• Details should depend upon abstractions.
High-level modules/classes implement business rules or logic in a system (application). Low-
level modules/classes deal with more detailed operations; in other words they may deal with
writing information to databases or passing messages to the operating system or services.

5
Structure of C++ Program
It is a common practice to organize a program into three separate files. The class declarations are
placed in a header file and the definitions of member functions go into another file. This
approach enables the programmer to separate the abstract specification of the interface from the
implementation details (member function definition).

Finally, the main program that uses the class is places in a third file which “includes: the
previous two files as well as any other file required.

The Client-Server Model

The class definition including the member functions constitute the server that provides services
to the main program known as client. The client uses the server through the public interface of
the class.

6
First C++ Program- Hello Fugus!
In this part we will write and understand the first program in C++ programming. We are
writing a simple C++ program that prints “Hello Fugus!” message. Let’s see the program first
and then we will discuss each and every part of it in detail.

Example 1:

Output

Example 2: Average of Two Numbers

Output:

7
Explanatory of the above program C++

#include<iostream>
• The #include is directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file.
• The header file iostream should be included at the beginning of all programs that use
input/output statements e.g.
• #include<conio> or #include<conio.h>
• #include<math> or #include<math.h> //for pow()function
• #include<string> or #include<string.h> //for strcpy() etc.
using namespace std;
• Namespace is a new concept introduced by the ANSI C++ standards committee.
• This defines a scope for the identifiers that are used in a program. For using the identifier
defined in the namespace scope we must include the using directive
• Here, std is the namespace where ANSI C++ standard class libraries are defined. All
ANSI C++ programs must include this directive.
• This will bring all the identifiers defined in std to the current global scope. Using and
namespace are the new keyword of C++.
Comments:
• Comments as the names suggests are just a text written by programmer during code
development.
• Comment doesn’t affect your program logic in any way, you can write whatever you
want in comments but it should be related to the code and have some meaning so that
when someone else look into your code, the person should understand what you did in the
code by just reading your comment.
• This improves readability of your code and when you are working on a project with your
team mates, this becomes essential aspect.
There are two types of comments in the above program.
• Single line comment e.g.
/* This function adds two integer numbers
* and returns the result as an integer value
*/
• Multiple line comment e.g.
// Read Numbers or // from keyboard etc.
8
int main()
• As the name suggests, this is the main function of our program and the execution of
program begins with this function, the int here is the return type which indicates to the
compiler that this function will return a integer value.
• Therefore, every main () in C++ should end with a return (0) statement; otherwise a
warning an error might occur.
cout << “Hello Fugus!”;
• The cout object belongs to the iostream file and the purpose of this object is to display
the content between double quotes as it is on the screen.
• This object can also display the value of variables on screen
• A semicolon to terminate end of the statement.

return 0;

• This statement returns value 0 from the main() function which indicates that the
execution of main function is successful.

• A semicolon to terminate end of the statement.

Variables in C++
• A variable is a name which is associated with a value that can be changed. For example
when I write int num=20; here variable name is num which is associated with value 20,
int is a data type that represents that this variable can hold integer values.
Syntax of declaring a variable in C++
• data_type variable1_name = value1, variable2_name = value2; e.g.

• int num1=20, num2=100; or

• num1=20;

num2=100;

Types of variables
• Variables can be categorized based on their data type. For example, in the above example
we have seen integer types variables.Following are the types of variables available in
C++.
• int: These type of variables holds integer value.
• char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.

9
• bool: holds boolean value true or false.
• double: double-precision floating point value.
• float: Single-precision floating point value
Types of variables based on their scope
In our first program we have seen the curly braces in the program like this:

• Any variable declared inside these curly braces have scope limited within these curly
braces, if you declare a variable in main() function and try to use that variable outside
main() function then you will get compilation error.
In C++ there are four kinds of scope as given below:
• Global variables (File scope ).
• Local variables (Local scope).
• Function scope
• Class scope
Global variable (file scope)
• A variable declared outside of any function (including main as well) is called global
variable.
• Global variables have their scope throughout the program, they can be accessed
anywhere in the program, in the main, in the user defined function, anywhere
• If the declaration of an identifier appears outside all functions, it is available to all the
functions in the program and its scope becomes file scope.
• Example 1:

Example 2:

• Here we have a global variable myVar, that is declared outside of main.


10
• We have accessed the variable twice in the main() function without any issues.

Local variable
• Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements (if, if-else etc) and have their scope limited
inside those braces.
• A block in C++ is enclosed by a pair of curly braces i.e., ‘{‘ and ‘}’.
• The variables declared within the body of the block are called local variables and can be
used only within the block.
• Example 1:

11
Example 2:

Can global and local variable have same name in C++?


Let’s see an example having same name global and local variable.

Data Types in C++


• Data types define the type of data a variable can hold, for example an integer variable can
hold integer data, a character type variable can hold character data etc.
• Data types in C++ are categorized in three groups:
Built-in,
User-defined and
Derived.

12
Flow Chart of Data types in C++

Built in data types


• char: For characters. Size 1 byte e.g.
• char ch = 'A';
• int: For integers. Size 2 bytes e.g.
• int num = 100;
• float: For single precision floating point. Size 4 bytes e.g.
• float num = 123.78987;
• double: For double precision floating point. Size 8 bytes e.g.
• double num = 10098.98899;bool:
• For booleans, true or false e.g.
• bool b = true;
• wchar_t: Wide Character. This should be avoided because its size is implementation
defined and not reliable.
Operators in C++
• Operator represents an action. For example + is an operator that represents addition.
• An operator works on two or more operands and produces an output. For example 3+4+5
here + operator work on three operands and produce 12 as output.
Types of Operators in C++

13
Basic Arithmetic Operators
• Basic arithmetic operators are: +, -, *, /, %
• + is for addition.
• – is for subtraction.
• * is for multiplication.
• / is for division.
• % is for modulo.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0
Example

Assignment Operators
• Assignments operators in C++ are: =, +=, -=, *=, /=, %= e.g.
• num2 = num1 would assign value of variable num1 to the variable.
• num2+=num1 is equal to num2 = num2+num1
• num2-=num1 is equal to num2 = num2-num1
• num2*=num1 is equal to num2 = num2*num1
• num2/=num1 is equal to num2 = num2/num1
• num2%=num1 is equal to num2 = num2%num1
Example

14
Auto-increment and Auto-decrement Operators
• ++ and —
num++ is equivalent to num=num+1;
• num–- is equivalent to num=num-1;

Logical Operators
• Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
• Logical operators in C++ are: &&, ||, !
• Let’s say we have two boolean variables b1 and b2.
• b1&&b2 will return true if both b1 and b2 are true else it would return false.
• b1||b2 will return false if both b1 and b2 are false else it would return true.
• !b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.
Example

Relational operators
• We have six relational operators in C++: ==, !=, >, <, >=, <=
• == returns true if both the left side and right side are equal
• != returns true if left side is not equal to the right side of operator.
• > returns true if left side is greater than right.
• < returns true if left side is less than right side.
• >= returns true if left side is greater than or equal to right side.
• <= returns true if left side is less than or equal to right side.
15
Example

16
Statements
Statement perform a number of tasks, such as computing, storing the results of computations,
altering the flow of control, reading and writing from or onto devices (or files), and providing the
information for the compiler.

A computer program is a set instruction for a computer. These instructions, also known as
statements, are executed sequentially that is one after the other as they appear in a program.

The various statement fall in two broad classes:

1. Executable
2. Non-executable.

Executable statements: are those statements that result in a machine code i.e., causes an action to
be performed.

The various categories of executable statements (control statement) are listed.

1. Branching (decision making): This Statement executing one group of instructions


depending on the outcome of a decision.

Examples:
a) if statement
b) nested if statement
c) if-else statement
d) nested if-else statement
e) if else if statement
f) Switch statement
a) if statement in C++

The syntax of if Statement is


Using code of if Statement
if (expression)
{
Statement
}

Using flow chart of if Statement

true
Exp

Statement
false

17
The expression may represent a relation expression, a logical expression, a numeric variable or a
numeric constant. The specified expression may be a simple expression or compound expression.

The expression in C++ language evaluates to a zero or non-zero value. If expression evaluates to
a non-zero value, then the statement in the statement block are executed; otherwise they are
bypassed.

Example of if statement:

Output

b) Nested if Statements in C++

If statement can be nested, i.e., an if statement can be contained within another if statement. The
inner if statement will be executed if the expression of the outer of statement evaluates to non-
zero value.

The syntax of nested if Statement is

Using code of nested if Statement

if (expression_1){
Statement(s);

if (expression_2){
Statement(s);
}
}
18
Statement1 would execute if the expression_1 is true. Statement2 would only execute if both the
conditions (expression_1 and expression_2) are true.

Example of Nested if statement

Output

More examples:

Output

19
c) if –else Statement in C++

Sometimes you have a condition and you want to execute a block of code if condition is true and
execute another piece of code if the same condition is false. This can be achieved in C++ using
if-else statement.

The syntax of if –else Statement is

Using code of if - else Statement

if (expression)
{
Statement(s)_1
}
else
{
Statement(s)_2
}

Using flow chart of if - else Statement

Exp
false true

Statement Statement

If expression evaluates is true, the statement_1 is executed and the statement_2 is bypassed.
However, if the expression evaluates is false, the statement_1 is bypassed and the statement_2 is
executed.

Example of if –else statement

20
Output

d) Nested if –else Statement in C++

Output

21
e) if –else if statement in C++

if-else-if statement is used when we need to check multiple conditions. In this control structure
we have only one “if” and one “else”, however we can have multiple “else if” blocks. This is
how it looks:

The syntax of if- else if Statement is

Using code of if – else if Statement

if (expression_1){
// if expression is true execute this
Statement(s);
}
else if (expression_2) {
// execute this if expression_1 is not met and expression_2 is met
Statement(s);
}
else if (expression_3){
// execute this if exp_1 and exp_2 are not met and exp_3 is met
Statement(s);
}
.
.
else {
// if none of the expression is true
// then those statements gets executed
Statement(s);
}
Note: The most important point to note here is that in if-else-if, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is
met then the statements inside “else” gets executed.

Example of if-else-if

22
Output

f) Switch Case statement in C++


The switch statement provides an alternative to else if construct. The switch statement has more
flexibility and a clearer format then else if construct.

The syntax of switch Statement is

Using code of switch Statement

If expression takes any value from val-2, val-2, val-3,…..val-n, the control is transferred to that
appropriate case. In each case, the statement are executed and then the break statement transfers
the control out of switch statement. If no break statement is used following a case, except last the
one in the absence of default keyword, the control will fall through to the next case. If the value
23
of the expression does no match any of the case values, control goes to the default keyword,
which is usually at the end of the switch statement. The use of the default keyword can be of a
great convenience. If there is no default keyword, the whole switch statement simple terminates
when there is no match.

Using flow chart of switch Statement

= val-1 default
Exp
= val-2 = val-3 = val-n

Statement Statement Statemen Statement Statemen


t t

Example of switch Statement

Output

2. Repetition (looping): This statements executing a group of instructions repetitively either


for a given number of times or until the required conditions are met

24
Examples:

a) for statement
b) while statement
c) do – while statement

a) for statement in C++


The syntax of for Statement is
Using code of for Statement

for (initialization; Test ; increment/decrement)


{
Statement(s)
}

Using flow chart of for Statement

Init

false
Test

true
Statement

Increment/discre
ment

Where init is an expression to initialize the counter, the test is an expression to see when to stop
iterating, and increment/decrement is an expression to increment/decrement the counter for each
pass of the loop. The init and increment/decrement parts can have more than one statement
separated by a comma.

The increment/decrement for the counter can be positive as well as negative and illustration
show below:
a) for (i = 1; i<= n; i++){
// Statement
}
25
Set i=1

false
I<=n

true
Statement

I++

b) for(for (i = 1; i<= n; i--){


// Statement
}

Set i=n

false
I>=n
true
Statement

I--

Example of a Simple For loop in C++


Here in the loop initialization part I have set the value of variable i to 1, condition is i<=6 and on
each loop iteration the value of i increments by 1.

26
Output

Example: display elements of array using for loop

Output

27
Infinite for loop in C++
A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by
mistake. When you set the condition in for loop in such a way that it never return false, it
becomes infinite loop.

Example of infinite for loop

Output

This is an infinite loop as we are incrementing the value of i so it would always satisfy the
condition i>=1, the condition would never return false.

c) While loop in C++

In while loop, condition is evaluated first and if it returns true then the statements inside while
loop execute, this happens repeatedly until the condition returns false. When condition returns
false, the control comes out of loop and jumps to the next statement in the program after while
loop.

The syntax of while Statement is


Using code of while Statement

while (condition)
{
Statement(s);
}

Using code of while Statement

28
While Loop example in C++

Test Runs

Example: Displaying the elements of array using while loop

Infinite While loop


A while loop that never stops is said to be the infinite while loop, when we give the condition in
such a way so that it never returns false, then the loops becomes infinite and repeats itself
indefinitely.

29
An example of infinite while loop:
This loop would never end as I’m decrementing the value of i which is 1 so the condition i<=6
would never return false.

Output

d) do-while loop in C++

do-while loop is similar to while loop, however there is a difference between them: In while
loop, condition is evaluated first and then the statements inside loop body gets executed, on the
other hand in do-while loop, statements inside do-while gets executed first and then the condition
is evaluated.

The syntax of do-while Statement is

Using code of do- while Statement

do
{
Statement(s);
}while(condition);

First, the statements inside loop execute and then the condition gets evaluated, if the condition
returns true then the control jumps to the “do” for further repeated execution of it, this happens
repeatedly until the condition returns false. Once condition returns false control jumps to the next
statement in the program after do-while.

30
Using code of do while Statement

Example of do-while Statement

Example: Displaying array elements using do-while loop


Here we have an integer array which has four elements. We are displaying the elements of it
using do-while loop.

31
3. Jumping: This statement transferring control from one point to another point in the same
program unit.

Example:
a) break statement
b) continue statement
c) goto statement
a) Break statement in C++
The break statement is used in following two scenarios:

a) Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used along
with if statement, whenever used inside loop(see the example below) so that it occurs only for a
particular condition.

b) It is used in switch case control structure after the case blocks. Generally all cases in switch
case are followed by a break statement to avoid the subsequent cases (see the example below)
execution. Whenever it is encountered in switch-case block, the control comes out of the switch-
case body.

The syntax of break Statement is


Using code of break Statement

break;

Using code of break Statement

Example: break statement in for loop


In the examples below, we have a for loop running from 10 to 200 but since we have a break
statement that gets encountered when the loop counter variable value reaches 12, the loop gets
terminated and the control jumps to the next statement in program after the loop body.
32
Test Runs

Example: break statement in while loop

Output

33
Example: break statement in switch loop

Output

In this example, we have break statement after each Case block, this is because if we don’t have
it then the subsequent case block would also execute. The output of the same program without
break would be:

b) Continue statement in C++


Continue statement is used inside loops. Whenever a continue statement is encountered inside a
loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration

The syntax of continue Statement is


Using code of continue Statement

continue;

Using code of do continue Statement

34
Example: continue statement inside for loop
As you can see that the output is missing the value 3, however the for loop iterate though the
num value 0 to 6. This is because we have set a condition inside loop in such a way, that the
continue statement is encountered when the num value is equal to 3. So for this iteration the loop
skipped the cout statement and started the next iteration of loop.

Test Runs

Example: Use of continue in While loop

35
Output

Example of continue in do-While loop

Output

36
goto statement in C++
The goto statement is used for transferring the control of a program to a given label. The syntax
of goto statement looks like this:

goto label_name;
Program structure:

label1:
...
...
goto label2;
...
..
label2:
...
In a program we have any number of goto and label statements, the goto statement is followed by
a label name, whenever goto statement is encountered, the control of the program jumps to the
label specified in the goto statement.

goto statements are almost never used in any development as they are complex and makes your
program much less readable and more error prone. In place of goto, you can
use continue and break statement.

Example of goto statement in C++

Output

Functions in C++
A function is block of code which is used to perform a particular task, for example let’s say you
are writing a large program with C++ and in that program you want to do a particular task
several number of times, like displaying value from 1 to 10, in order to do that you have to write
few lines of code and you need to repeat these lines every time you display values. Another way

37
of doing this is that you write these lines inside a function and call that function every time you
want to display values.

The syntax of function is


Using code

Return_type function_name (parameter_list)


{
Statements;
}
A simple function example

Output

38
Function declaration in C++
The syntax of function declaration is

Using code

Return_type function_name (parameter_list);

The function declaration consists only of a function header; contains no code. Function header
consists of three parts, those are the return type, the function name, and the formal argument list.
A semicolon follows the function header.

Example:
1. int sum(int num1, int num2); or
2. int sum(int, int);

You are telling the compiler that the return type of the function is int, name of the function is
sum and it has two argument all of type int.

Function definition in C++


The syntax of function definition is
Using code

Return_type function_name (parameter_list)


{
Statements;
}
The function header consists of three parts; those are the return type, the function name, and the
formal argument list. A semicolon is not used at the end of function header. With the new
implementation, the return type is mandatory.
The function body contains the local declarations and the statements that define the task to be
accomplished by the function. The body starts with local declaration that specify the variables
need by function. After the local declaration, the function statements, followed by the return
statement.
Example:
{
/* Function is defined after the main method
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
Function calling in C++
The syntax of calling function is
Using code
function_name (parameter);{
Statements;
}

39
We can call the function like this:

Example:
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Types of functions

1) Build-it functions
Built-in functions are also known as library functions. We need not to declare and define these
functions as they are already written in the C++ libraries such as iostream, cmath etc. We can
directly call them when we need.

Example

Here we are using built-in function pow(x,y) which is x to the power y. This function is declared
in cmath header file so we have included the file in our program using #include directive.

Output

40
2) User-defined functions

We have already seen user-defined functions, the example we have given at the beginning of this
class is an example of user-defined function. The functions that we declare and write in our
programs are user-defined functions. Let have more example of user-defined functions .

Output

41
Output

Default Arguments in C++ Functions


The default arguments are used when you provide no arguments or only few arguments while
calling a function. The default arguments are used during compilation of program. For example,
lets say you have a user-defined function sum declared like this: int sum(int a=10, int b=20), now
while calling this function you do not provide any arguments, simply called sum(); then in this
case the result would be 30, compiler used the default values 10 and 20 declared in function
signature. If you pass only one argument like this: sum(80) then the result would be 100, using
the passed argument 80 as first value and 20 taken from the default argument.

Example: Default arguments in C++

42
Output

Rules of default arguments


As you have seen in the above example that I have assigned the default values for only two
arguments b and c during function declaration, it is up to you to assign default values to all
arguments or only selected arguments but remember the following rule while assigning default
values to only some of the arguments: If you assign default value to an argument, the subsequent
arguments must have default values assigned to them, else you will get compilation error.

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. In the following
diagram. I have shown that how the factorial function is calling itself until the function reaches
to the base condition.

Direct recursion vs indirect recursion

Direct recursion: When function calls itself, it is called direct recursion.

43
C++ recursion example: Factorial

Output

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.

Indirect Recursion Example in C++

Output:

44
Arrays in C++

An array is a collection of similar items stored in contiguous memory locations. In programming,


sometimes a simple variable is not enough to hold all the data. For example, suppose we want to
store the marks of 500 students, having 500 different variables for this task is not feasible, we
can define an array with size 500 that can hold the marks of all students.

Declaring an array in C++


There are couple of ways to declare an array.
Method 1:

int arr[5];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

Method 2:

int arr[] = {10, 20, 30, 40, 50};

Method 3:

int arr[5] = {10, 20, 30, 40, 50};

Accessing Array Elements


Array index starts with 0, which means the first array element is at index 0, second is at index 1
and so on. We can use this information to display the array elements. See the code below:

45
Output

Noted although this code worked fine, displaying all the elements of array like this is not
recommended, when you want to access a particular array element then this is fine but if you
want to display all the elements then you should use a loop.

Passing Array to Function in C++

You can pass array as an argument to a function just like you pass variables as arguments. In
order to pass array to the function you just need to mention the array name during function
call like this:

function_name(array_name);

46
Example

we are passing two arrays a & b to the function sum(). This function adds the
corresponding elements of both the arrays and display them.

Output

Strings

Strings are words that are made up of characters, hence they are known as sequence of
characters. In C++ we have two ways to create and use strings: 1) By creating char arrays and
treat them as string 2) By creating string object.

1) By creating char arrays and treat them as string

Output:
47
Example 2: Getting user input as string

This can be considered as inefficient method of reading user input, why? Because when we read
the user input string using cin then only the first word of the string is stored in char array and
rest get ignored. The cin function considers the space in the string as delimiter and ignore the
part after it.

Example 3: Correct way of capturing user input string using cin.get

Output

Drawback of this method

1) Size of the char array is fixed, which means the size of the string created through it is fixed in
size, more memory cannot be allocated to it during runtime. For example, lets say you have
created an array of character with the size 10 and user enters the string of size 15 then the last
five characters would be truncated from the string. On the other hand if you create a larger array
to accommodate user input then the memory is wasted if the user input is small and array is
much larger then what is needed.

2) In this method, you can only use the in-built functions created for array which don’t help
much in string manipulation.

48
String object in C++
Now we have seen how to handle strings in C++ using char arrays. Lets see another and better
way of handling strings in C++ – string objects.

Output

The advantage of using this method is that you need not to declare the size of the string, the size
is determined at run time, so this is better memory management method. The memory is
allocated dynamically at runtime so no memory is wasted.

Debugging: Debugging is a process of fixing the bugs found in testing phase and
Programmer or developer is responsible for debugging and it can’t be automated

Testing: Testing is a process of finding bugs or errors in a software product that is done
manually by tester or can be automated

Difference between Testing and Debugging

Testing Debugging

The purpose of testing is to find bugs and The purpose of debugging is to correct
errors. those bugs found during testing.

Debugging is done by programmer or


Testing is done by tester. developer.

49
It can be automated. It can’t be automated.

It must be done only by insider i.e.


It can be done by outsider like client. programmer.

Most of the testing can be done without Debugging can’t be done without proper
design knowledge. design knowledge.

50
Oops Concept in C++
The main purpose of C++ programming was to add object orientation to the C programming
language, which is in itself one of the most powerful programming languages. If any
programming language follow below oops concept then that language called object oriented
programming language.
• Object
• Class
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

Object
Object is the physical as well as logical entity whereas class is the only logical entity.

Class
Class: Class is a blue print which is containing only list of variables and method and no memory is
allocated for them. A class is a group of objects that has common properties.

Encapsulation
Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in C++ language by class concept. The main advantage of using of encapsulation
is to secure the data from other methods, when we make a data private then these data only use within the
class, but these data not accessible outside the class.

Abstraction
Abstraction is the concept of exposing only the required essential characteristics and behavior with respect
to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.

Inheritance
The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.

Polymorphism
The process of representing one Form in multiple forms is known as Polymorphism. Here one form
represent original form or original method always resides in base class and multiple forms represents
overridden method which resides in derived classes.

51
Access Specifiers in C++
Access specifiers in C++ define how the members of the class can be accessed. C++ has 3
new keywords introduced, namely.
• public
• private
• protected

The keywords public, private, and protected are called access specifiers. A class can have
multiple public, protected, or private labeled sections.
Note: By default, all members and function of a class is private i.e if no access specifier is
specified.

Syntax of Declaring Access Specifiers in C++


Syntax

Public Access Specifier in C++


Public class members are accessible outside the class and it is available for everyone.

52
Syntax

Private Access Specifier in C++


Private class members are accessible with the class and it is not accessible outside the class. If
someone try to access outside the it gives compile time error. By default class variables and
member functions are private

Syntax

Private and Public Access Specifier Example in C++

Output

53
Protected Access Specifier in C++
It is similar to private access specifier. It makes class member inaccessible outside the class.
But they can be accessed by any subclass of that class.
Syntax

54
Output

Class and Object in C++


A class in C++ contains, following properties;
• Data Member
• Method
• Constructor
• Block
• Class and Interface
Object: Object is a instance of class.
An Object in C++ has three characteristics:
• State
• Behavior
• Identity
Syntax

Example:

State: Represents data (value) of an object.


Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
Class is also can be used to achieve user defined data types.

55
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height,
age as well as behaviors:- barking, eating, and sleeping.
Animal class

Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different states
and behaviors. For Example car has state - color, name, model, speed, Mileage. As well as
behaviors - distance travel.
Difference between Class and Object in C++

Class Object

Class is a container with collection of


1 object is a instance of class
variables and methods.

Sufficient memory space will be allocated


No memory is allocated at the time of
2 for all the variables of class at the time of
declaration
declaration.

One class definition should exist only For one class multiple objects can be
3
once in the program. created.

56
Syntax to declare a Class
Syntax

Simple Example of Object and Class


In this example, we will create an Employee class that has one data member and function
member. After creating the object of the Employee class and printing the objects value.

Output

Inheritance in C++
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
• In the inheritance the class which is give data members and methods is known as base or
super or parent class.
• The class which is taking the data members and methods is known as sub or derived or
child class.

57
Syntax

Real Life Example of Inheritance in C++

The real life example of inheritance is child and parents, all the properties of father are
inherited by his son.

Diagram

In the above diagram data members and methods are represented in broken line are inherited
from faculty class and they are visible in student class logically.
Advantage of Inheritance
If we develop any application using this concept than that application has following
advantages,
• Application development time is less.
• Application takes less memory.
• Application execution time is less.
• Application performance is enhancing (improved).
• Redundancy (repetition) of the code is reduced or minimized so that we get consistence
results and less storage cost.

58
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class it has five types
they are:
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
• Multiple inheritance
• Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.

Multilevel inheritances
In multilevel inheritances there exists single base class, single derived class and multilevel
intermediate base classes.
Single base class + single derived class + multilevel intermediate base classes
Intermediate base classes
An intermediate base class is one in one context with access derived class and in another
context same class access base class.

59
Multiple inheritance
In multiple inheritances there exist multiple classes and single derived class.

Hierarchical inheritance
Derivation of two or more classes from a single base class, Class A is only base class and classes
B and C are derived classes.

Hybrid inheritance
Combination of any inheritance type

60
Inheriting the feature from base class to derived class
In order to inherit the feature of base class into derived class we use the following
Syntax

Explanation

• classname-1 and classname-2 represents name of the base and derived classes respectively.
• : is operator which is used for inheriting the features of base class into derived class it
improves the functionality of derived class.

Example of Inheritance

Output

Abstraction in C++
Abstraction is the concept of exposing only the required essential characteristics and behavior
with respect to a context.
61
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Real life example of Abstraction in C++
Abstraction shows only important things to the user and hides the internal details for example
when we ride a vehicle, we only know about how to ride vehicle but cannot know about how it
work and also we do not know internal functionality of vehicle.

Example of Abstraction

Output

Note: Data abstraction can be used to provide security for the data from the unauthorized
methods.

62
Note: Note: In C++ language data abstraction can be achieved by using class.
Encapsulation in C++
Encapsulation is a process of wrapping of data and methods in a single unit. It is achieved in
C++ language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In C++
language encapsulation can be achieve using class keyword, state represents declaration of
variables on attributes and behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
outside the class.
Real Life Example of Encapsulation in C++
The common example of encapsulation is Capsule. In capsule all medicine are encapsulated in
side capsule.

Benefits of encapsulation
• Provides abstraction between an object and its clients.
• Protects an object from unwanted access by clients.
Example: A bank application forbids a client to change an Account's balance
Example used Abstraction example is served.
Polymorphism in C++
The process of representing one Form in multiple forms is known as Polymorphism. Here one
form represent original form or original method always resides in base class and multiple forms
represents overridden method which resides in derived classes.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and morphs means forms. So polymorphism means many forms.

63
Real life example of Polymorphism in C++
Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
or daughter, Here one person have different-different behaviors.

Type of polymorphism
• Compile time polymorphism
• Run time polymorphism
Compile time polymorphism
In C++ programming you can achieve compile time polymorphism in two ways, which is given
below;
• Method overloading
• Method overriding
Method Overloading in C++
Whenever same method name is exiting multiple times in the same class with different number
of parameter or different order of parameters or different types of parameters is known
as method overloading. In below example method "sum()" is present in addition class with
same name but with different signature or arguments.

64
Example of method overloading:

Output:

Method Overriding in C++


Define any method in both base class and derived class with same name, same parameters or
signature, this concept is known as method overriding. In below example same method
"show()" is present in both base and derived class with same name and signature.
Example of method overriding:

65
File Handling in C++
File Handling concept in C++ language is used for store a data permanently in computer and
using file easily to transfer a data from one computer to another. Using file handling we can
store our data in Secondary memory (Hard disk).

Why use File Handling in C++


• For permanent storage.
• The transfer of input - data or output - data from one computer to another can be easily
done by using files.
For read and write from a file you need another standard C++ library called fstream, which
defines three new data types:

Datatype Description

Ofstream This is used to create a file and write data on files

Ifstream This is used to read data from files

Fstream This is used to both read and write data from/to files

How to achieve File Handling


For achieving file handling in C++ we need follow following steps
• Naming a file
66
• Opening a file
• Reading data from file
• Writing data into file
• Closing a file
Functions use in File Handling

Function Operation

open() To create a file

close() To close an existing file

get() Read a single character from a file

put() write a single character in file.

read() Read data from file

write() Write data into file.

Defining and Opening a File


The function open() can be used to open multiple files that use the same stream object.
Syntax

Example:

Closing a File
A file must be close after completion of all operation related to file. For closing file we
need close() function.
Syntax

67
put() and get() function
The function put() write a single character to the associated stream. Similarly, the function get()
reads a single character from the associated stream.
read() and write() function
These functions take two arguments. The first is the address of the variable V, and the second is
the length of that variable in bytes. The address of variable must be cast to type char * (i.e
pointer to character type).
Example:

File Opening mode

Mode Meaning Purpose

ios :: out Write Open the file for write only.

ios :: in Read Open the file for read only.

Open the file for appending data to


ios :: app Appending
end-of-file.

take us to the end of the file when


ios :: ate Appending
it is opened.

Both ios :: app and ios :: ate take us to the end of the file when it is opened. The difference
between the two parameters is that the ios :: app allows us to add data to the end of file only,
while ios :: ate mode permits us to add data or to modify the existing data anywhere in the file.
The mode can combine two or more parameters using the bitwise OR operator (symbol |)
Example:

File pointer
Each file has two associated pointers known as the file pointers. One of them is called the input
pointer (or get pointer) and the other is called the output pointer (or put pointer). The input
68
pointer is used for reading the contents of a given file location and the output pointer is used for
writing to a given file location.
Function for manipulation of file pointer
When we want to move file pointer to desired position then use these function for manage the
file pointers.

Function Operation

seekg() moves get pointer (input) to a specified location.

seekp() moves put pointer (output) to a specified location.

tellg() gives the current position of the get pointer.

tellp() gives the current position of the put pointer.

fout . seekg(0, ios :: beg) go to start

fout . seekg(0, ios :: cur) stay at current position

fout . seekg(0, ios :: end) go to the end of file

fout . seekg(m, ios :: beg) move to m+1 byte in the file

fout . seekg(m, ios :: cur) go forward by m bytes from the current position

fout . seekg(-m, ios :: cur) go backward by m bytes from the current position

fout . seekg(-m, ios :: end) go backward by m bytes from the end

69
Read and Write data from/to File

Output:
70
Enter your choice (1-Read, 2-Write, 3-exit): 1
Enter roll_no: 1
Enter name: musa
Enter father name: sani
Enter your choice (1-Read, 2-Write, 3-exit): 2
Enter roll_no.: 1
roll no.: 1
stu name.: musa
father name: sani
Exception Handling in C++
The process of converting system error messages into user friendly error message is known
as Exception handling. This is one of the powerful features of C++ to handle run time error
and maintain normal flow of C++ application.
Exception
An exception is an event, which occurs during the execution of a program, which disrupts the
normal flow of the program's Instructions.
Handling the Exception
Handling the exception is nothing but converting system error message into user friendly error
message. Use Three keywords for Handling the Exception in C++ Language, they are;
1. try
2. catch
3. throw
Syntax for handling the exception

Try Block
It is one of the block in which we write the block of statements which causes executions at
run time in other words try block always contains problematic statements.
Catch block

71
It is one of the block in which we write the block of statements which will generates user
friendly error messages in other words catch block will suppose system error messages.
Example without Exception Handling

Output: Abnormally terminate program


Example of Exception Handling

Output: Denominator not be zero

Internal Searching and Sorting


Searching is the process of finding element in a given list. In this process we check item is
available in given list or not.
Type of searching
1. Internal search
2. External search
Internal Search: In this search, Searching is performed on main or primary memory.
External Search: In this search, Searching is performed in secondary memory.

72
Complexity Analysis
The Complexity analysis is used to determine, the algorithm will take amount of resources (such
as time and space) necessary to execute it.
There are two types of complexities: 1) Time Complexity and 2) Space Complexity.
Searching Techniques
There are basically three types of searching techniques:
• Linear or sequential search
• Binary search
• Interpolation Search
Linear/ Sequential Search
Linear/Sequential searching is a searching technique to find an item from a list until the
particular item not found or list not reached at end. We start the searching from 0th index to N-1
index in a sequential manner, if particular item found, returns the position of that item otherwise
return failure status or -1.

LINEAR_SEARCH (LIST, N, ITEM, LOC, POS)


In this algorithm, LIST is a linear array with N elements, and ITEM is a given item to be
searched. This algorithm finds the location LOC of ITEM into POS in LIST, or sets POS: = 0, if
search is unsuccessful.
1. Set POS: = 0;
2. Set LOC: = 1;
3. Repeat STEPS a and b while LOC <= N
a. If ( LIST[LOC] = ITEM) then
i. SET POS: = LOC; [get position of item]
ii. Return;
b. Otherwise
i. SET LOC: = LOC + 1; [increment counter]
4. [END OF LOOP]
73
5. Return
Complexity of Linear search
The complexity of search algorithm is based on number of comparisons C, between ITEM and
LIST [LOC]. We seek C (n) for the worst and average case, where n is the size of the list.
Worst Case: The worst case occurs when ITEM is present at the last location of the list, or it is
not there at al. In either situation, we have
C (n) = n
Now, C (n) = n is the worst case complexity of linear or sequential search algorithm.
Average case: In this case, we assume that ITEM is there in the list, and it can be present at any
position in the list. Accordingly, the number of comparisons can be any of the numbers 1, 2, 3, 4
…n. and each number occurs with probability p = 1/n. Then,
C (n) = n/2
Implementation of Linear/ Sequential Search using C++

74
Output:

Binary Search
It is special type of search work on sorted list only. During each stage of our procedure, our
search for ITEM is reduced to a restricted segment of elements in LIST array. The segment
starts from index LOW and spans to HIGH.
LIST [LOW], LIST [LOW+1], LIST [LOW+2], LIST [LOW+ 3]….. LIST[HIGH]
The ITEM to be searched is compared with the middle element LIST[MID] of segment,
where MIDobtained as:
MID = ( LOW + HIGH )/2
We assume that the LIST is sorted in ascending order. There may be three results of this
comparison:
1. If ITEM = LIST[MID], the search is successful. The location of the ITEM is LOC :=
MID.
2. If ITEM < LIST[MID], the ITEM can appear only in the first half of the list. So, the
segment is restricted by modifying HIGH = MID – 1.
3. If ITEM > LIST[MID], the ITEM can appear only in the second half of the list. So, the
segment is restricted by modifying LOW = MID + 1.
75
Initially, LOW is the start index of array, and HIGH is the last index of array.
The comparison goes on. With each comparison, low and high approaches near to each other, the
loop will continue till LOW < HIGH.

Let the item to be searched is: 15


Step1: Initially
1. List[low] = list[0] = 12
2. List[high] = list[9] = 99
3. Mid= (low + high)/2 = (0+9)/2 = 4
4. List[mid]= list[4] = 35
Step2: Since item (15) < list [mid] (35); high = mid -1 = 3
1. List[low] = list[0] = 12
2. List[high] = list[3] = 28
3. Mid =(low + high)/2 = (0+3)/2 = 1
4. List [mid] = list [1] = 15.
Step3: Since item (15) = list [mid] (15);
It is success, the location 1 is returned.
BINARY SEARCH (LIST, N, ITEM, LOC, LOW, MID, HIGH)
Here LIST is a sorted array with size N, ITEM is the given information.
The variable LOW, HIGH and MID denote, respectively,
the beginning, end and the middle of segment of LIST.
The algorithm is used to find the location LOC of ITEM in LIST array.
If ITEM not there LOC is NULL.
1. Set LOW: = 1; LOW: = N;
2. Repeat step a to d while LOW <= HIGH and ITEM != LIST(MID)
a. Set MID := (LOW + HIGH)/2
b. If ITEM = LIST (MID), then
i. Set LOC: = MID
ii.Return
c. If ITEM < LIST (MID) then
i. Set HIGH: = MID - 1;

76
d. Otherwise
i. Set LOW: = MID + 1;
3. Set LOC: = NULL
4. Return

Complexity of Binary search


The complexity measured by the number f(n) of comparisons to locate ITEM in LIST where
LIST contains n elements. Each comparison reduces the segment size in half. Hence, we require
at most f(n) comparisons to locate ITEM, where:
2c >= n
Approximately, the time complexity is equal to log2n. It is much less than the time complexity of
linear search.

Implementation of Binary Search using C++

77
Output:

Example 2:

Output:

78
Difference between Linear Search and Binary Search
Linear Search Binary Search
Sorted list is not required. Sorted list is required.

It can be used in linked list implementation. It cannot be used in liked list implementation.

It is only suitable for static lists, because any change


It is suitable for a list changing very frequently.
requires resorting of the list.
The average number of comparison is relatively
The average number of comparison is very high.
slow.
Interpolation Search
This technique is used if the items to be searched are uniformly distributed between the first and
the last location. This technique is a simple modification in the binary search when MID is
calculated.
Mid = low + (high – low) * ((item – LIST[low]) / (LIST[high] – LIST[low]));
Advantages
1. If the items are uniformly distributed, the average case time complexity is log2(log2(n)).
2. It is considered improvement in binary search.
Disadvantages
1. The calculation of mid is complicated. It increases the execution time.
2. If the items are not uniformly distributed, interpolation search will have very poor
behavior.
Sorting
Generally sorting is done on an array of integer or string but there may be a situation where
sorting is based on the number but actual data may be some other value.
Example 1:
Suppose we have to sort names of student according to roll number. So a structure can be created
which can be used to store roll number and names.
Declaration of structure:

C++ Code to sort structure:

79
Output:

Example 2:

Output:

80
81

You might also like