0% found this document useful (0 votes)
4 views10 pages

C Handouts 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

COMPUTER PROGRAMMING PART 4

LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

C++ Operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two
values:
Example

int x = 100 + 50;

• Although the + operator is often used to add together two values,


like in the example above, it can also be used to add together a
variable and a value, or a variable and another variable:
Example

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ divides the operators into the following groups:


• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.

Operator Name Description Example


+ Addition Adds together two values x+y

Subtracts one value from


- Subtraction x-y
another

* Multiplication Multiplies two values x*y

Divides one value by


/ Division x/y
another
Returns the division
% Modulus x % y
remainder
Increases the value of a
++ Increment ++x
variable by 1
Decreases the value of a
-- Decrement --x
variable by 1

Assignment Operators
• Assignment operators are used to assign values to variables.
• In the example below, we use the assignment operator (=) to
assign the value 10 to a variable called x:
Example

int x = 10;

1 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

• The addition assignment operator (+=) adds a value to a variable:


Example

int x = 10;
x += 5;

• A list of all assignment operators:

Operator Example Same As


= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

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
chapter.
• In the following example, we use the greater than operator (>) to
find out if 5 is greater than 3:
Example

int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

• A list of all comparison operators:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators
• As with comparison operators, you can also test for true (1) or
false (0) values with logical operators.
• Logical operators are used to determine the logic between
variables or values:

Operator Name Description Example


Returns true if both
&& Logical and x < 5 && x < 10
statements are true
2 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Returns true if one


|| Logical or of the statements is x < 5 || x < 4
true
Reverse the result,
!(x < 5 && x <
! Logical not returns false if the
10)
result is true

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
• 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 cout << x + y + z;

The if Statement
Use the if statement to specify a block of C++ code to be executed if
a condition is true.

Syntax

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.

In the example below, we test two values to find out if 20 is greater


than 18. If the condition is true, print some text:

Example

if (20 > 18) {


cout << "20 is greater than 18";
}

3 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

We can also test variables:

Example

int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

Example explained
In the example above we use two variables, x and y, to test whether x
is greater than y (using the > operator). As x is 20, and y is 18, and
we know that 20 is greater than 18, we print to the screen that "x is
greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if
the condition is false.

Syntax

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
}

Example

int time = 20;


if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained
In the example above, time (20) is greater than 18, so the condition
is false. Because of this, we move on to the else condition and print
to the screen "Good evening". If the time was less than 18, the
program would print "Good day".

4 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

The else if Statement


Use the else if statement to specify a new condition if the first
condition is false.

Syntax

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
}

Example

int time = 22;


if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is
also false, so we move on to the else condition since condition1 and
condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

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. It is often used to
replace simple if else statements:

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example

int time = 20;


if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

5 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

You can simply write:

Example

int time = 20;


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

C++ Switch Statements


Use the switch statement to select one of many code blocks to be
executed.

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

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
The example below uses the weekday number to calculate the weekday
name:

Example

int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";

6 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
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.

A break can save a lot of execution time because it "ignores" the


execution of all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case
match:

Example

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"

C++ While Loop


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:

Syntax

while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over
again, as long as a variable (i) is less than 5:
7 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Example

int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

*Note: Do not forget to increase the variable used in the condition,


otherwise the loop will never end!

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.

Syntax

do {
// code block to be executed
}
while (condition);

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:

Example

int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

Do not forget to increase the variable used in the condition,


otherwise the loop will never end!

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:

Syntax

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


// code block to be executed
}

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.
8 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

The example below will print the numbers 0 to 4:

Example

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


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

Example explained
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.

Another Example
This example will only print even values between 0 and 10:

Example

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


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

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

Example

// 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)
}
}

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

Syntax

for (type variableName : arrayName) {


// code block to be executed

9 | Page
COMPUTER PROGRAMMING PART 4
LECTURE HANDOUTS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

The following example outputs all elements in an array, using a "for-


each loop":

Example

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


for (int i : myNumbers) {
cout << i << "\n";
}

*Note: Don't worry if you don't understand the example above. You will
learn more about arrays in the C++ Arrays chapter.

10 | P a g e

You might also like