You are on page 1of 9

CPE 104L 1

Programming Logic and Design

Unit 2
C++ Elements

Lesson 3 – Strings
Declaring String
Strings are used for storing text. A string variable contains collection of characters
surrounded by double quotes.

Strings can be initialized with any valid string literal just like numerical type variables can
be initialized to any valid numerical literal. Both initialization formats are valid with
strings:
string mystring = "This is a string example";
string mystr ("This is a string example also ");

Strings can also perform all the other basic operations that fundamental data types can, like
being declared without an initial value and being assigned values during execution
CPE 104L 2
Programming Logic and Design

Character and string literals can also represent special characters that are difficult to
express in the source code, like newline (\n) or tab (\t). Here is a list of the single character
escape codes:

Escape code Description

\n newline
\r carriage return
\t tab
\v vertical tab
\b Backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)

String Concatenation

The + operator can be used between strings to add them together to make a new string.
This is called concatenation:
CPE 104L 3
Programming Logic and Design

In the example above, we added a space after firstName to create a space between John and
Doe on output. However, you could also add a space with quotes (“ “ or ‘ ‘):

Append

A string in C++ is actually an object, which contain functions that can perform certain
operations on strings. For example, you can also concatenate strings with the append()
function:

***NOTE***

C++ uses the + operator for both addition and concatenation. Numbers are added. Strings

are concatenated.
If you add two numbers, the result will be a number.

If you add two strings, the result will be a string concatenation.

If you try to add a number to a string, an error will occur.

ERROR!
CPE 104L 4
Programming Logic and Design

String Length
To get the length of a string, use the length() function:

You might see some C++ programs that use the size() function to get the length of a string.
This is just an alias of length(). It is completely up to you if you want to use the length() or
size():

Access Strings
You can access the characters in a string by referring to its index number inside square
brackets [].

This example prints the first character in myString:

String indexes start with 0 as the first character.

Change String Characters


To change the value of a specific character in a string, refer to the index number, and use
single quotes.
CPE 104L 5
Programming Logic and Design

User Input Strings


It is possible to use the extraction operator >> on cin to display a string entered by a user:

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which
means that it can only display a single word (even if you type many words):

From the example above, you would expect the program to print "John Doe", but it only
prints "John".

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:
CPE 104L 6
Programming Logic and Design

Lesson 4 – Operators and its Hierarchy

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators such as Arithmetic Operators, Relational
Operators, Logical Operators, Bitwise Operators and Assignment Operators.

Arithmetic Operators

Assume variable A = 0 and variable B = 20


Operator Description Example
+ Addition A + B = 30
- Subtraction A - B = -10
* Multiplication A * B = 200
/ Division B/A= 2
% Modulo B%A= 0
++ Increment A++ will result to 11
-- Decrement A-- will result to 9

Relational Operators

Assume variable A = 0 and variable B = 20


Operator Description Example
== Equal to (A == B) evaluates to true
!= Not equal to (A != B) evaluates to true
> Greater than (A > B) evaluates to true
< Less than (A < B) evaluates to true
>= Greater than equal to (A >= B) evaluates to true
<= Less than equal to (A <= B) evaluates to true
CPE 104L 7
Programming Logic and Design

Logical Operators

Operator 1st Condition 2nd Condition Output


AND (&&) True True True
True False False
False True False
False False False
OR (||) True True True
True False True
False True True
False False False
NOT (!) True – False
False – True

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows –
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
CPE 104L 8
Programming Logic and Design

If A = 60; and B = 13; The binary format of A=0011 1100 and B = 0000 1101,
applying the principle above will yield to A&B = 0000 1100, A|B = 0011 1101, A^B = 0011
0001 and ~A = 1100 0011
Operator Description Example
& Binary AND Operator (A & B) will give 12 which is 0000 1100
| Binary OR Operator (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator (A ^ B) will give 49 which is 0011 0001
(~A ) will give -61 which is 1100 0011 in
Binary Ones Complement 2's complement form due to a signed
~ Operator binary number.
<< Binary Left Shift Operator A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator A >> 2 will give 15 which is 0000 1111

Assignment Operators

Operator Description Example


= Simple assignment operator. C = A will assign value of A into C
+= Add AND assignment operator. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
C >>= 2 is same as C = C >> 2
>>= Right shift AND assignment operator.
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
Bitwise exclusive OR and assignment
C ^= 2 is same as C = C ^ 2
^= operator.
Bitwise inclusive OR and assignment
C |= 2 is same as C = C | 2
|= operator.
CPE 104L 9
Programming Logic and Design

Operators Precedence in C++


When writing complex expressions with several operands, we may have some
doubts about which operand is evaluated first and which later. This affects how an
expression is evaluated. Certain operators have higher precedence than others. From
greatest to lowest priority, the priority order is as follows:

Category Operator Grouping


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

You might also like