Computer
Programming II
Prof. Soha Safwat
Computer Programming II
CSC1200
Instructor: Prof. Soha Safwat
Assistant professor of Computer
Science
Dean of Faculty of Computer
Science and information System
Grading Policy:
• Attendance & activity 10%
• Assignments + Quizzes 10%
• Lab 10%
• Project 10%
• Midterm 20%
• Final 40%
You should attend more than 50% of lectures to
enter the Midterm and final exams) 3
Classroom rules
• Entry is not allowed after half an hour from
the start of the lecture unless there is an
excuse
• No -entry or exit from the classroom after
starting the lecture without permission
• No -discussions out of the lecture content
• No –side conversations or whispering 4
What is C++?
• C++ is a cross-platform language that can be used to create
high-performance applications.
• C++ was developed by Bjarne Stroustrup, as an extension to
the C language in the early 1980s.
• C++ gives programmers a high level of control over system
resources and memory.
• C++ incorporates object-oriented programming (OOP) features,
making it possible to model real-world entities and behaviors in
software design.
• C++ supports procedural, generic, and object-oriented
programming paradigms, making it versatile for various types
of applications, from system software to game development.
• The language was updated 5 major times in 2011, 2014, 2017,
2020, and 2023 to C++11, C++14, C++17, C++20, and C+
Why Use C++
• Performance: C++ is known for its high performance and
efficiency, allowing for fine-grained control over system resources
and memory management.
• Object-Oriented Programming: It supports OOP concepts such
as inheritance, encapsulation, and polymorphism, enabling better
code organization and reusability.
• Standard Template Library (STL): C++ includes the STL, a
powerful library of algorithms and data structures that streamline
coding and enhance productivity.
• Cross-Platform Development: C++ code can be compiled and
run on various platforms, making it suitable for cross-platform
applications.
• Large Community and Ecosystem: A vast community of
developers, extensive libraries, and frameworks enhance support
and resources for learning and project development.
Difference between C and C++
1.Programming Paradigm:
o C: Primarily a procedural programming language that focuses on function
and procedure-based coding.
o C++: Supports both procedural and object-oriented programming,
enabling better modeling of complex systems.
2.Data Abstraction:
o C: Does not provide features for data abstraction, leading to a less
organized structure for larger programs.
o C++: Introduces classes and objects, allowing for data abstraction and
encapsulation of data and methods.
Difference between C and C++
3. Function Overloading:
o C: Does not support function overloading; each function must have a
unique name.
o C++: Supports function overloading, allowing multiple functions with the
same name but different parameter lists.
4.Memory Management:
o C: Uses functions like malloc and free for dynamic memory allocation.
o C++: Introduces new and delete operators for dynamic memory
management, along with constructors and destructors for better resource
handling.
Difference between C and C++
5. Standard Libraries:
o C: Has a smaller standard library primarily focused on
functions and standard input/output.
o C++: Offers a more extensive standard library, including the
Standard Template Library (STL), which provides ready-to-use
data structures and algorithms.
6.Exception Handling:
o C: Does not have built-in support for exception handling.
o C++: Provides a robust exception handling mechanism with
try, catch, and throw keywords.
C++ Install IDE
• An IDE (Integrated Development Environment) is used to edit
AND compile the code.
• Popular IDE's include Code::Blocks, Eclipse, and Visual Studio.
These are all free, and they can be used to both edit and
debug C++ code.
C++ Syntax
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us
work with input and output objects, such as cout (used in line 5).
Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for
objects and variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to
make the code more readable.
Line 4: Another thing that always appear in a C++ program is int
main(). This is called a function. Any code inside its curly
brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together
with the insertion operator (<<) to output/print text. In our example,
it will output "Hello World!".
Line 6: return 0; ends the main function.
Line 7: Do not forget to add the closing curly bracket } to actually
end the main function.
Notes
Note: C++ is case-sensitive: "cout" and "Cout" has different
meaning.
Note: Every C++ statement ends with a semicolon ;.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However,
multiple lines makes the code more readable.
C++ Statements
• A computer program is a list of "instructions" to be
"executed" by a computer.
• In a programming language, these programming instructions
are called statements.
• The following statement "instructs" the compiler to print the
text "Hello World" to the screen:
C++ Output (Print Text)
• The cout object, together with the << operator, is used to
output values and print text.
• Just remember to surround the text with double quotes (""):
C++ Output Numbers
• You can also use cout() to print numbers.
• However, unlike text, we don't put numbers inside double
quotes:
C++ New Lines
To insert a new line in your output, you can use the \
n character.
Another way to insert a new line, is with the endl manipulator:
Both \n and endl are used to break lines. However, \n is most
used.
But what is \n exactly?
The newline character (\n) is called an escape sequence, and
it forces the cursor to change its position to the beginning of
the next line on the screen. This results in a new line.
C++ Comments
• Comments can be used to explain C++ code, and to
make it more readable. It can also be used to
prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.
• Single-line Comments
• Single-line comments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by
the compiler (will not be executed).
• Multi-line Comments
• Multi-line comments start with /* and ends with */.
• Any text between /* and */ will be ignored by the
compiler:
Variables
• Variables are containers for storing data values.
• In C++, there are different types of variables
(defined with different keywords), for example:
•int - stores integers (whole numbers), without decimals,
such as 123 or -123
•double - stores floating point numbers, with decimals, such
as 19.99 or -19.99
•char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
•string - stores text, such as "Hello World". String values
are surrounded by double quotes
•bool - stores values with two states: true or false
Variables
• Declaring (Creating) Variables
• To create a variable, specify the type and assign it a value:
Multiple Variables
• Declare Many Variables
• To declare more than one variable of the same type, use a comma-
separated list:
Identifiers
• Identifiers
• All C++ variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
• The general rules for naming variables are:
•Names can contain letters, digits and underscores
•Names must begin with a letter or an underscore (_)
•Names are case-sensitive (myVar and myvar are different variables)
•Names cannot contain whitespaces or special characters like !, #, %,
etc.
•Reserved words (like C++ keywords, such as int) cannot be used as
names
Constants
• Constants
• When you do not want others (or yourself) to change existing variable
values, use the const keyword (this will declare the variable as
"constant", which means unchangeable and read-only):
User Input
• User Input
• You have already learned that cout is used to output (print) values. Now
we will use cin to get user input.
• cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
• In the following example, the user can input a number, which is stored in
the variable x. Then we print the value of x:
Data Types
• Data Types
• As explained in the Variables slides, a variable in C++ must be a
specified data type.
Operators
• Operators
• Operators are used to perform operations on variables and values.
• C++ divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic Operators
Assignment Operators
Comparison Operators
• Comparison operators are used to compare two values (or
variables). This is important in programming, because it helps
us to find answers and make decisions.
• The return value of a comparison is either 1 or 0, which
means true (1) or false (0). These values are known
as Boolean values, and you will learn more about them in
the Booleans and If..Else slides.
Logical Operators
Strings
• Strings
• Strings are used for storing text/characters.
• For example, "Hello World" is a string.
• A string variable contains a collection of characters surrounded by
double quotes.
String Concatenation
• String Concatenation
• The + operator can be used between strings to add them together to
make a new string. This is called concatenation:
String Length
• String Length
• To get the length of a string, use the length() function:
User Input Strings
• cin considers a space (whitespace, tabs, etc) as a
terminating character, which means that it can only store a
single word (even if you type many words).
• That's why, when working with strings, we often use
the getline() function to read a line of text. It takes cin as
the first parameter, and the string variable as second.
Math
• Math
• C++ has many functions that allows you to perform mathematical
tasks on numbers.
• Max and min
• The max(x,y)
• The min(x,y)
• Other functions, such as sqrt (square root), round (rounds a number)
and log (natural logarithm)
If ... Else
• Conditions and If Statements
• You already know that C++ supports the usual logical conditions
from mathematics:
•Less than: a < b
•Less than or equal to: a <= b
•Greater than: a > b
•Greater than or equal to: a >= b
•Equal to a == b
•Not Equal to: a != b
• You can use these conditions to perform different actions for
different decisions.
• C++ has the following conditional statements:
•Use if to specify a block of code to be executed, if a specified condition is
true
•Use else to specify a block of code to be executed, if the same condition is
false
•Use else if to specify a new condition to test, if the first condition is false
•Use switch to specify many alternative blocks of code to be executed
The if Statement
• Use the if statement to specify a block of C++ code to be
executed if a condition is true.
• The else Statement
• Use the else statement to specify a block of code to be executed if
the condition is false.
Short Hand If Else
• Short Hand If...Else (Ternary Operator)
• There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands.
• It can be used to replace multiple lines of code with a single line, and
is often used to replace simple if else statements:
• Switch Statements
Switch
• Use the switch statement to select one of
many code blocks to be executed.
• This is how it works:
•The switch expression is evaluated once.
•The value of the expression is compared with
the values of each case.
•If there is a match, the associated block of
code is executed.
•The break and default keywords are
optional, and will be described later in this
slide.
Loops
• C++ Loops
• Loops can execute a block of code as long as a specified condition is
reached.
• Loops are handy because they save time, reduce errors, and they
make code more readable.
• C++ While Loop
• The while loop loops through a block of code as long as a specified
condition is true:
Do/While Loop
• The do/while loop is a variant of the while loop. This loop
will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the
condition is true.
For Loop
For Loop
When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
• Statement 1 sets a variable before the loop starts
(int i = 0).
• Statement 2 defines the condition for the loop to run
(i must be less than 5). If the condition is true, the loop
will start over again, if it is false, the loop will end.
• Statement 3 increases a value (i++) each time the
code block in the loop has been executed.
Nested Loops
• It is also possible to place a loop inside another loop. This is called
a nested loop.
• The "inner loop" will be executed one time for each iteration of
the "outer loop":
Break and Continue
Break
You have already seen the break statement used in an earlier
slide of this tutorial. It was used to "jump out" of a switch
statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 4:
Break and Continue
Continue
The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration
in the loop.
This example skips the value of 4:
Arrays
• Arrays
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• To declare an array, define the variable type, specify the
name of the array followed by square brackets and specify
the number of elements it should store:
Array
Access the Elements of an
Array
You access an array element by referring to the index number
inside square brackets [].
This statement accesses the value of the first
element in cars:
Arrays and Loops
Loop Through an Array
You can loop through the array elements with the for loop.
The following example outputs all elements in the cars array:
Omit Array Size
• In C++, you don't have to specify the size of the array. The
compiler is smart enough to determine the size of the array
based on the number of inserted values:
Fixed Size (Arrays) vs. Dynamic Size (Vectors)
• You will often hear the terms "fixed size" and "dynamic size"
when discussing arrays in C++.
• This is because the size of an array in C++ is fixed, meaning
you cannot add or remove elements after it is created.
Vectors
Vectors
• For operations that require adding and removing array elements, C++
provides vectors, which are resizable arrays.
• The size of a vector is dynamic, meaning it can grow and shrink as
needed.
• Vectors are found in the <vector> library, and they come with many
useful functions to add, remove and modify elements:
• You will learn much more about vectors and other data structures
Array Size
Get the Size of an Array
To get the size of an array, you can use the sizeof() operator:
• Why did the result show 20 instead of 5,
when the array contains 5 elements?
• It is because the sizeof() operator
returns the size of a type in bytes.
• You learned from the Data Types that
an int type is usually 4 bytes, so from the
example above, 4 x 5 (4 bytes x 5
elements) = 20 bytes.
Multi-Dimensional Arrays
• Multi-Dimensional Arrays
• A multi-dimensional array is an array of arrays.
• To declare a multi-dimensional array, define the variable type, specify
the name of the array followed by square brackets which specify how
many elements the main array has, followed by another set of square
brackets which indicates how many elements the sub-arrays have:
Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Create a Function
• C++ provides some pre-defined functions, such as main(), which is used to
execute code. But you can also create your own functions to perform certain
actions.
• To create (often referred to as declare) a function, specify the name of the
function, followed by parentheses ():
Functions
• A C++ function consist of two parts:
• Declaration: the return type, the name of the function, and
parameters (if any)
• Definition: the body of the function (code to be executed)
• Note: If a user-defined function, such as myFunction() is
declared after the main() function, an error will occur:
Functions
• However, it is possible to separate the declaration and the
definition of the function - for code optimization.
• You will often see C++ programs that have function
declaration above main(), and function definition
below main(). This will make the code better organized and
easier to read:
Function Parameters
• Parameters and Arguments
• Information can be passed to functions as a parameter. Parameters act
as variables inside the function.
• Parameters are specified after the function name, inside the
parentheses. You can add as many parameters as you want, just
separate them with a comma:
Default Parameters
Default Parameter Value
• You can also use a default parameter value, by using the equals sign (=).
• If we call the function without an argument, it uses the default value
("Norway"):
Multiple Parameters
The Return Keyword
Return Values
• The void keyword, used in the previous examples, indicates that the function
should not return a value.
• If you want the function to return a value, you can use a data type (such
as int, string, etc.) instead of void, and use the return keyword inside the
function:
Pass Array to a Function
Function Overloading
• Function Overloading
• With function overloading, multiple functions can have the
same name with different parameters:
Variable Scope
• it is important to learn how variables act inside and outside of functions.
• In C++, variables are only accessible inside the region they are created. This is
called scope.
Local Scope Global Scope
• A variable created outside of a
• A variable created inside a function function, is called a global
belongs to the local scope of that variable and belongs to the global
function, and can only be used inside scope.
that function:
• Global variables are available from
within any scope, global and local:
Recursion
• Recursion
• Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
• Recursion may be a bit difficult to understand. The best way to figure out
how it works is to experiment with it.
100 + sum(99)
100 + ( 99 + sum(98) )
100 + ( 99 + ( 98 + sum(97) ) )
...
100 + 99 + 98 + 97 +…+ sum(0)
100 + 99 + 98 + 97 +…+ 0
References
Creating References
• A reference variable is a "reference" to an existing variable, and it is
created with the & operator:
Memory Address
Memory Address
• In the example from the previous slide, the & operator was used to create a
reference variable. But it can also be used to get the memory address of a
variable; which is the location of where the variable is stored on the computer.
• When a variable is created in C++, a memory address is assigned to the
variable. And when we assign a value to the variable, it is stored in this
memory address.
• To access it, use the & operator, and the result will represent where the
variable is stored:
Pointers
Creating Pointers
• You learned from the previous slide, that we can get the memory
address of a variable by using the & operator:
• A pointer however, is a variable that stores the memory
address as its value.
• A pointer variable points to a data type (like int or string) of
the same type, and is created with the * operator. The
address of the variable you're working with is assigned to the
pointer:
Dereference
• Get Memory Address and Value
• In the example from the previous slide, we used the pointer variable to
get the memory address of a variable (used together with
the & reference operator).
• However, you can also use the pointer to get the value of the variable,
by using the * operator (the dereference operator):
Modify Pointers
• Modify the Pointer Value
• You can also change the pointer's value. But note that this will also
change the value of the original variable:
Functions - Pass By Reference
• Pass By Reference
• In the examples from the previous slides, we used normal variables
when we passed parameters to a function.
• You can also pass a reference to the function. This can be useful when
you need to change the value of the arguments: