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

Computer Programming

c++ 3 pdf

Uploaded by

akidasimndwe
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)
36 views41 pages

Computer Programming

c++ 3 pdf

Uploaded by

akidasimndwe
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

COMPUTER PROGRAMMING

LECTURE 3.0
OBJECTIVES
•Introduction to C++ Strings.
•Use of Constants in C++.
•Understanding C++ Operators.
•Basic Input/output in C++.
•Introduction to Control Structures
Introduction to Strings
•Variables that can store non-numerical values that are longer than one single character are
known as strings.
•The C++ language library provides support for strings through the standard string class.
•This is not a fundamental type, but it behaves in a similar way as fundamental types do in its
most basic usage.
•A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header file in our source code: <string>.
•A good example of the declarations of a string can be seen on the next slide.
Introduction to Strings
Constants
•Constants are expressions with a fixed value
•Literals are used to express particular values within the source code of a program.
•We have already used these previously to give concrete values to variables or to express
messages we wanted our programs to print out, for example, when we wrote:
a = 5 ;
the 5 in this piece of code was a literal constant.
•Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean.
Constants
•Examples of literals are shown on the table below

Literal Constant Example


Integer Numerals 1776, 707, 0273, 0x4b, 75u
Floating Point Numbers 3.14159, 6.02e23,3.0
Character and String Literals ‘z’, ’p’, ”Hello World”
Boolean literals true, false
Defined constants (#define)
•You can define your own names for constants that you use very often without having to resort to
memory consuming variables
•This is done through using the #define preprocessor directive.
•Its format is: #define identifier value example : #define PI 3.14159
Defined constants (#define)
•The #define directive is not a C++ statement but a directive for the preprocessor; therefore it
assumes the entire line as the directive and does not require a semicolon (;) at its end.
•If you append a semicolon character (;) at the end, it will also be appended in all occurrences
within the body of the program that the preprocessor replaces.
Declared constants (const)
•With the const prefix you can declare constants with a specific type in the same way as you
would do with a variable:

•Here, pathwidth and tabulator are two typed constants.


•They are treated just like regular variables except that their values cannot be modified after
their definition.
Operators
•Once we know of the existence of variables and constants, we can begin to operate with them.
•For that purpose, C++ integrates operators.
•Assignment (=) : The assignment operator assigns a value to a variable.

◦ The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as
the rvalue (right value).
◦ The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an
operation or any combination of these.
◦ The most important rule when assigning is the right-to-left rule: The assignment operation always takes
place from right to left, and never the other way:
Operators (Assignment)
•Assignment (=) :
• Consider the statement below

• This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue).
• The value that was stored until this moment in a is not considered at all in this operation, and in fact
that value is lost.
• Consider also that we are only assigning the value of b to a at the moment of the assignment operation.
• Therefore a later change of b will not affect the new value of a.
Operators (Arithmetic)
•Can you tell the value of a and b ?
Operators (Arithmetic)
•The assignment operation can be used as the rvalue (or part of an rvalue) for another
assignment operation.
•Consider the example below:

•This is equivalent to:

•That means: first assign 5 to variable b and then assign to a the value 2 plus the result of the
previous assignment of b (i.e. 5), leaving a with a final value of 7.
Operators (Arithmetic)
• The five arithmetical operations supported by the C++ language are:
i. Addition +
ii. Subtraction –
iii. Multiplication *
iv. Division /
v. Modulo %

• Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators.
• The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%).
• Modulo is the operation that gives the remainder of a division of two values.
• For example, if we write: a = 11 % 3; The value of a will be 2.
Operators (Arithmetic)
• The five arithmetical operations supported by the C++ language are:
i. Addition +
ii. Subtraction –
iii. Multiplication *
iv. Division /
v. Modulo %

• Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators.
• The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%).
• Modulo is the operation that gives the remainder of a division of two values.
• For example, if we write: a = 11 % 3; The value of a will be 2.
Operators (Compound
Assignment)
•When we want to modify the value of a variable by performing an operation on the value
currently stored in that variable we can use compound assignment operators:

Expression Is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
Operators (Increase and
decrease ++, --)
•The increase operator (++) and the decrease operator (--) increase or reduce by one the value
stored in a variable.
• They are equivalent to +=1 and to -=1.
•Thus these three statements below are all functionally equivalent.

•A characteristic of this operator is that it can be used both as a prefix and as a suffix.
• That means that it can be written either before the variable identifier (++a) or after it (a++).
Operators (Increase and
decrease ++, --)
•Although in simple expressions like a++ or ++a both have exactly the same meaning, in other
expressions in which the result of the increase or decrease operation is evaluated as a value in
an outer expression they may have an important difference in their meaning:
• In the case that the increase operator is used as a prefix (++a) the value is increased before the
result of the expression is evaluated and therefore the increased value is considered in the outer
expression;
•In case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and
therefore the value stored before the increase operation is evaluated in the outer expression.
•This is best illustrated on the table below:
Operators (Relational and equality
operators)
•In order to evaluate a comparison between two expressions we can use the relational and
equality operators.
•The result of a relational operation is a Boolean value that can only be true or false, according to
its Boolean result.
•We may want to compare two expressions, for example, to know if they are equal or if one is
greater than the other is.
•Here is a list of the relational and equality operators that can be used in C++:
Operators (Logical operators)
•In order to evaluate a comparison between two expressions we can use the relational and
equality operators.
•The result of a relational operation is a Boolean value that can only be true or false, according to
its Boolean result.
•We may want to compare two expressions, for example, to know if they are equal or if one is
greater than the other is.
•Here is a list of the relational and equality operators that can be used in C++:
Operators (Logical operators !, &&,
||)
•The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one
operand, located at its right, and the only thing that it does is to inverse the value of it,
producing false if its operand is true and true if its operand is false.
•Basically, it returns the opposite Boolean value of evaluating its operand.
Example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
Operators (Logical operators !, &&,
||)
•The logical operators && and || are used when evaluating two expressions to obtain a single
relational result.
•&& corresponds to the Boolean logical operation AND, while || corresponds to the Boolean
logical operation OR.
•The table below shows the results of using these operators.
Operators (Logical operators !, &&,
||)
For example:
•( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
•( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
Operators (Precedence of
operators)
•When writing complex expressions with several operands, we may have some doubts about
which operand is evaluated first and which later.
•For example, in this expression:

•Does it mean :

•The correct answer is the first of the two expressions, with a result of 6.
Operators (Precedence of
operators)
•There is an established order with the priority of each operator, and not only the arithmetic
ones (those whose preference come from mathematics) but for all the operators which can
appear in C++.

•if you want to write complicated expressions and you are not completely sure of the precedence
levels, always include parentheses. It will also become a code easier to read.
Basic Input/Output
•C++ uses a convenient abstraction called streams to perform input and output operations in
sequential media such as the screen or the keyboard.
•A stream is an object where a program can either insert or extract characters to/from it.
•We do not really need to care about many specifications about the physical media associated
with the stream - we only need to know it will accept or provide characters sequentially.
•The standard C++ library includes the header file iostream, where the standard input and output
stream objects are declared.
Standard Output (cout)
•By default, the standard output of a program is the screen, and the C++ stream object defined to
access it is cout.
•cout is used in conjunction with the insertion operator, which is written as << (two "less than"
signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen
Standard Input (cin)
• The standard input device is usually the keyboard.
• Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>)
on the cin stream.
• The operator must be followed by the variable that will store the data that is going to be extracted
from the stream.
• For example:

•The first statement declares a variable of type int called age, and the second one waits for
an input from cin (the keyboard) in order to store it in this integer variable.
Standard Input (cin)
• cin can only process the input from the keyboard once the RETURN key has been pressed.
• Therefore, even if you request a single character, the extraction from cin will not process the input until
the user presses RETURN after the character has been introduced.
• You must always consider the type of the variable that you are using as a container with cin extractions.
• If you request an integer you will get an integer, if you request a character you will get a character and if
you request a string of characters you will get a string of characters.
• You can also use cin to request more than one datum input from the user:

• In both cases the user must give two data, one for variable a and another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.
Standard Input (cin)
•We can use cin to get strings with the extraction operator (>>) as we do with fundamental data
type variables.
•However, as it has been said, cin extraction stops reading as soon as if finds any blank space
character, so in this case we will be able to get just one word for each extraction. This behavior
may or may not be what we want;
•For example if we want to get a sentence from the user, this extraction operation would not be
useful.
•In order to get entire lines, we can use the function getline, which is the more recommendable
way to get user input with cin:
Standard Input (cin)
•Consider the example below:
Control Structures
•A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions.
•For that purpose, C++ provides control structures that serve to specify what has to be done by
our program, when and under which circumstances.
•With the introduction of control structures we are going to have to introduce a new concept:
the compound statement or block.
• A block is a group of statements which are separated by semicolons (;) like all C++ statements,
but grouped together in a block enclosed in braces: { }:
{ statement1; statement2; statement3; }
Control Structures
•A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions.
•For that purpose, C++ provides control structures that serve to specify what has to be done by
our program, when and under which circumstances.
•With the introduction of control structures we are going to have to introduce a new concept:
the compound statement or block.
• A block is a group of statements which are separated by semicolons (;) like all C++ statements,
but grouped together in a block enclosed in braces: { }:
{ statement1; statement2; statement3; }
Control Structures
•Most of the control structures that we will see in this section require a generic statement as part
of its syntax.
•A statement can be either a simple statement (a simple instruction ending with a semicolon) or
a compound statement (several instructions grouped in a block), like the one just described.
•In the case that we want the statement to be a simple statement, we do not need to enclose it
in braces ({}).
•But in the case that we want the statement to be a compound statement it must be enclosed
between braces ({}), forming a block.
Control Structures
•Most of the control structures that we will see in this section require a generic statement as part
of its syntax.
•A statement can be either a simple statement (a simple instruction ending with a semicolon) or
a compound statement (several instructions grouped in a block), like the one just described.
•In the case that we want the statement to be a simple statement, we do not need to enclose it
in braces ({}).
•But in the case that we want the statement to be a compound statement it must be enclosed
between braces ({}), forming a block.
Control Structures: if...else
• The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement

• We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else, its form used in conjunction with if is:
if (condition) statement1 else statement2

• The if + else structures can be concatenated with the intention of verifying a range of values.
if (condition1) statement1 else if (condition2) statement2…else
• Remember that in case that we want more than a single statement to be executed, we must group
them in a block by enclosing them in braces { }
Control Structures: Loops (Iteration
Structures)
•Loops have as purpose to repeat a statement a certain number of times or while a condition is
fulfilled.
•While Loop: this repeats a block of statements while a given condition is true.
•Its format is:
while (expression) {
statement
}
•When creating a while-loop, we must always consider that it has to end at some point, therefore
we must provide within the block some method to force the condition to become false at some
point, otherwise the loop will continue looping forever.
Control Structures: Loops (Iteration
Structures)
•Consider the example below using a while loop
Control Structures: Loops (Iteration
Structures)
•Do While Loop: Its functionality is exactly the same as the while loop, except that condition in
the do-while loop is evaluated after the execution of statement instead of before, granting at
least one execution of statement even if condition is never fulfilled.
•Its format is:
do {
statement
}
while (condition);
Control Structures: Loops (Iteration
Structures)
•For Loop: Its functionality is exactly the same as the while loop, except that condition in the do-
while loop is evaluated after the execution of statement instead of before, granting at least one
execution of statement even if condition is never fulfilled.
•Its format is:
for (initialization; condition; increase/decrease)
{
statement;
}
Control Structures: Loops (Iteration
Structures)
•The for loop works in the following way:
1. Initialization is executed. Generally it is an initial value setting for a counter variable. This is executed
only once.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends and statement is
skipped (not executed).
3. Statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to step
2(checking condition)

•You may use the following Jump Statements when inside any loop:
• break- to leave a loop even if the condition for its end is not fulfilled.
• continue- skip the rest of the loop in the current iteration as if the end of the statement block had been
reached.

You might also like