0% found this document useful (0 votes)
10 views41 pages

ENG2139 Lecture 2

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

ENG2139 Lecture 2

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

ENG2139 INTRODUCTION TO ICT

Lecture 2 : Introduction and Basics of C++

Instructor: George ZIBA


Email: [email protected]
0976854627

George ZIBA , DEPT. of EEE, School of Engineering, UNZA


References
Our main reference text books and websites in this course are:
[1] Juan Soulie, 2007, C++ Language Tutorial
[2] Tony Gaddis, 2015, Starting out with C++ from control structures through
objects
[3] https://www.w3schools.com/cpp/

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 2


Course Outline
Introduction and Basics of C++ :Syntax, Output, Comments, Structure of a program,
Variables, Data types, Constants, Basic input/output, Operators, Strings, Booleans,
Math, Conditions, Switch, While Loop, For Loop, Break/Continue, Arrays, Structures,

C++ Functions: References, Pointers, Functions, Function Parameters, Function


Overloading, Recursion

C++ Classes: OOP, Classes/Objects, Class Methods, Constructors, Access Specifiers,


Encapsulation, Inheritance, Polymorphism, Files, Exceptions

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 5


3
Course Requirements
Distribution of Marks
 Assignments 5%
 Labs 15%
 Test 20%
 Final Exam 60%

Required Compilers/ IDE


 CodeBlocks
 Eclipse
 Any

Time Allocation
• Lectures 2 hours/week
• Laboratory/ Tutorials 3 hours/week

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 4


C++ Math
• C++ has many functions that allow you to perform
mathematical tasks on numbers.
• The max(x,y) function can be used to find the
highest value of x and y:
• And the min(x,y) function can be used to find the
lowest value of x and y:
• Other functions, such as sqrt (square root), round
(rounds a number) and log (natural logarithm),
can be found in the <cmath> header file:
5
C++ 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
• You can use these conditions to perform
different actions for different decisions.
• C++ has the following conditional statements:

6
• 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

7
The if Statement
if (condition) {
// block of code to be executed if the condition is true
}
• Note that if is in lowercase letters. Uppercase
letters (If or IF) will generate an error
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
8
C++ Else
• if (condition) {
• // block of code to be executed if the condition is true
• } else {
• // block of code to be executed if the condition is false
• }
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

9
The else if Statement
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
• if (condition1) {
• // block of code to be executed if condition1 is true
• } else if (condition2) {
• // block of code to be executed if the condition1 is false and condition2
is true
• } else {
• // block of code to be executed if the condition1 is false and condition2
is false
• } 10
C++ Short Hand If Else
• 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. It is often used to replace simple if else
statements:
• variable = (condition) ? expressionTrue : expressionFalse;

int time = 20;


string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

11
C++ Switch
• Use the switch statement to select one of many code
blocks to be executed.

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
12
• 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 chapter

13
The break Keyword
• When C++ reaches a break keyword, it breaks
out of the switch block.
• This will stop the execution of more code and
case testing inside the block.
• When a match is found, and the job is done, it's
time for a break. There is no need for more
testing
• The default keyword specifies some code to run
if there is no case match:
14
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"

15
C++ While Loop
• The while loop loops through a block of code as
long as a specified condition is true:
• while (condition) {
• // code block to be executed
• }
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
16
The 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.
do {
// code block to be executed
}
while (condition);

17
• The example below uses a do/while loop. The
loop will always be executed at least once, even
if the condition is false, because the code block is
executed before the condition is tested:
• Do not forget to increase the variable used in the
condition, otherwise the loop will never end!
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

18
C++ 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:

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

19
• Statement 1 is executed (one time) before the
execution of the code block.
• Statement 2 defines the condition for
executing the code block.
• Statement 3 is executed (every time) after the
code block has been executed.

for (int i = 0; i < 5; i++) {


cout << i << "\n";
}

20
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":

// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}
21
The foreach Loop
• There is also a "for-each loop" (introduced in
C++ version 11 (2011), which is used
exclusively to loop through elements in an
array (or other data sets):
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}

22
C++ Break and Continue
• 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:

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
cout << i << "\n";
}
23
C++ 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:
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
24
C++ 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:
• string cars[4];

25
• We have now declared a variable that holds an
array of four strings. To insert values to it, we
can use an array literal - place the values in a
comma-separated list, inside curly braces:
• string cars[4] = {"Volvo", "BMW", "Ford",
"Mazda"};
• To create an array of three integers, you could
write:
• int myNum[3] = {10, 20, 30};
26
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:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

27
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:
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda",
"Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}

28
C++ 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:
• It is also possible to declare an array without
specifying the elements on declaration, and add
them later:
string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements
string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array
elements
string cars[5];
29
Get the Size of an Array
• To get the size of an array, you can use the
sizeof() operator:
• To find out how many elements an array has,
you have to divide the size of the array by the
size of the data type it contains:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
cout << myNumbers[i] << "\n";
}

30
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:

31
• As with ordinary arrays, you can insert values
with an array literal - a comma-separated list
inside curly braces. In a multi-dimensional
array, each element in an array literal is
another array literal.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

32
Access the Elements of a Multi-Dimensional
Array
• To access an element of a multi-dimensional array,
specify an index number in each of the array's
dimensions.
• This statement accesses the value of the element in the
first row (0) and third column (2) of the letters array.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

cout << letters[0][2]; // Outputs "C"

33
Change Elements in a Multi-Dimensional
Array
• To change the value of an element, refer to
the index number of the element in each of
the dimensions:
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";

cout << letters[0][0]; // Now outputs "Z" instead of "A"


34
Loop Through a Multi-Dimensional Array
• To loop through a multi-dimensional array, you need one loop
for each of the array's dimensions.
• The following example outputs all elements in the letters array:
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}

35
C++ Structures
• Structures (also called structs) are a way to group several
related variables into one place. Each variable in the
structure is known as a member of the structure.

• Unlike an array, a structure can contain many different data


types (int, string, bool, etc.).
• To create a structure, use the struct keyword and declare
each of its members inside curly braces.

• After the declaration, specify the name of the structure


variable (myStructure in the example below):
36
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable

• To access members of a structure, use the dot syntax (.)

// Create a structure variable called myStructure


struct {
int myNum;
string myString;
} myStructure;

// Assign values to members of myStructure


myStructure.myNum = 1;
myStructure.myString = "Hello World!";

// Print members of myStructure


cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n"; 37
One Structure in Multiple Variables
• You can use a comma (,) to use one structure in many variables:
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here

// Put data into the first structure


myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;

// Put data into the second structure


myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;

38
Named Structures
• By giving a name to the structure, you can treat it as a
data type. This means that you can create variables with
this structure anywhere in the program at any time.

• To create a named structure, put the name of the


structure right after the struct keyword:

struct myDataType { // This structure is named "myDataType"


int myNum;
string myString;
};

39
• To declare a variable that uses the structure, use the name of the
structure as the data type of the variable:

struct car {
string brand;
string model;
int year;
};

int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;

// Create another car structure and store it in myCar2;


car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
40
End of Lecture 2

Thank you for your attention!

41

You might also like