Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Programming For Engineers 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Programming for Engineers

Introduction to C (Revision) Control Structures


Source:
Deitel & Deitel. C How To Program.
Seventh Edition. Pearson Education, Inc. 2013.

Copyright Notice
Do not remove this notice.

COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969

WARNING
This material has been produced and communicated to you by or on
behalf of the University of South Australia pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the
Act. Any further reproduction or communication of this material by you
may be the subject of copyright protection under the Act.
Do not remove this notice.

Required Reading
C How to Program, Deitel & Deitel
Chapter 3:
Structured Program Development in C
3.1 - 3.7, 3.11, 3.12
Chapter 4:
C Program Control
4.1 4.8, 4.10 4.12

Random Number Generation


Random Number Generation
To generate random numbers (pseudo-random) use
the C Standard Library function called rand().
To access the rand() function from the standard
library include the following preprocessor directive at
the top of your program:
#include <stdlib.h>

stdlib - contains functions to convert numbers to


text and text to numbers, memory allocation, random
numbers, and other utility functions.

Random Number Generation


Random Number Generation
i = rand();
Generates an integer value between 0 and
RAND_MAX (=32767)
To generate an integer between 1 and n:
1 + ( rand() % n )
rand() % n returns a number between 0 and n 1
add 1 to make the number between 1 and n.
To generate an integer between 1 and 10 use:
1 + (rand() % 10)

C Functions
Random Number Generation
/* Fig. 5.7: Deitel & Deitel (Modified)
Deitel & Deitel. C How To Program. Fifth Edition.
Pearson Education, Inc. 2007.
*/
#include <stdlib.h>
int main()
{
Output:
int i;
66556
for (i = 1; i <= 20; i++)
51153
{
66242
printf("%d ", 1 + (rand() % 6) );
if (i % 5 == 0)
62341
printf("\n");
} /* end for */
return 0;
} /* end main */
/* (C) Copyright 1992-2007 by Deitel & Associates, Inc.
and Pearson Education, Inc. All Rights Reserved. */

Random Number Generation


Random Number Generation
Computers are not capable of generating truly random numbers. If you run your
program several times you will notice that the list of numbers generated (and the
actions your program takes based on these values) is the same each time.
Numbers are not really random generated from a seed.
To change the sequence, you can change the seed. For example:
unsigned int seed = 12345;
srand(seed);

This seed value gives the random number generator a new starting point.
This will generate a different sequence of numbers, however, will still generate
the same sequence every time the program is run.
For a different sequence of numbers each run, use the time function which
returns the time of the day in seconds.
You only need to do this once at the start of your program.
#include <time.h>

srand(time( NULL ));

Random Number Generation


Blackjack is a popular card game where the goal is to beat the dealer by
having the higher hand which does not exceed 21. The card game
translates well into a dice game. Instead of a deck of 52 cards, we will use
two 11 sided dice in order to have the higher total, or hand which does not
exceed 21. We implement parts of the game in this lecture.

Write a program that:


Simulates the rolling of two 11-sided dice (the face value on the die
are 1 11). Use the rand() function.
randomNo = 1 + (rand() % 11);
That is, generate two random numbers between 1-11 and store
them in variables called playerDie1 and playerDie2.
Calculate the die total and store in variable called playerTotal.

Display them to the screen in the following format:


Player's hand is: 1 + 4 = 5

Random Number Generation


Answer
#include <stdlib.h>
#include <stdio.h>

int main() {
int playerDie1;
int playerDie2;
int playerTotal;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;

/* Display player hand to the screen */


printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);
return 0;
}

Control Structures
Control Structures
Programs can be written using three control structures
(Bohn and Jacopini):
Sequence
Statements are executed one after the other in order.

Selection (making decisions)


C has 3 types of selection structures:

if
if/else
switch
Repetition (doing the same thing over and over)
C has 3 types of repetition structures:

while
do/while
for

statement1;
statement2;
statement3;

Equality and Relational Operators


Selection and repetition structures require comparisons to work (based on a
logical condition).
Equality & Relational operators make those comparisons.
Logical operators allow us to combine the comparisons.
Equality & Relational Operators
Used to make decisions
Used in expressions where a true/false result is required.

is equal to

==
!=
<
<=
>
>=
Example of use:
if (x == 0)
:

is not equal to
is less than
is less than or equal to
is greater than
is greater than or equal to
while (x <= 0)

Logical Operators
Logical Operators (&& || !) combine comparisons
Used when either one, or both, of two (or more) conditions must
be satisfied.
if (it is 1.00 and I am hungry)
have lunch

x >= 0 && x <= 5


x <= 2 || x >= 4
!(a == b && c == d)

and
or
not

Logical Operators
! (not) negates the value of the operand. That is, converts true to
false, and false to true.
&& (and) requires both a and b to be true for the whole expression
to be true. Otherwise, the value of the expression is false.
|| (or) requires one of a or b to be true for the whole expression to
be true. The expression is false only when neither a nor b is true.
Truth Table. Logical Operators.

a
0
0
1
1

b
0
1
0
1

a && b
0
0
0
1

a || b
0
1
1
1

!a
1
1
0
0

The result of a logical expression is always true or false.


True = any non-zero value. False = 0. The following code adds 1 to
age if age is not equal to 0.
if (age)
age++;

Logical Operators
Can also store the result of an expression.
For example:
int
int
int
int

x = 5;
y = 1;
z = 5;
res;

res
res
res
res

=
=
=
=

x
x
y
y

< y;
== z;
< x && z < y;
< x || y == z;

Logical Operators
Short Circuit Evaluation
When evaluating:
result = cond1 && cond2;
If cond1 is false result must be false so cond2 is not
evaluated.
Similarly, with:
result = cond1 || cond2;

If cond1 is true result must be true so cond2 is not


evaluated.

Conditional Operator
Conditional Operator
Ternary operator. Has the general form:
condition ? value1 : value2
If the condition is true the expression returns value1, else
returns value2.
z = x > y ? x : y;
This is equivalent to the statement:
if (x > y)
z = x;
else
z = y;

Selection Structures
Making decisions
So far, we have seen programs that all start at the top and
execute each statement in order until the end is reached.
Execute different sections of code depending on the values of
data as the program runs.
Greater flexibility and therefore more powerful.
Lets look at ways a program can control the path of execution

Selection Structures
The if Selection Structure
A simple if statement has the following form:

Condition

True
False

Next statement

if (boolean expression)
true block

Statements

Selection Structures
If the expression (boolean expression) is true, the statement(s) in
the true block are executed.
If the expression is false, the program jumps immediately to the
statement following the true block.
If the expression is true execute the statement in the true block.
if (age >= 18)
printf("You can vote");

Selection Structures
Compound Statements
Statement can be a single statement or a compound statement.
Compound statements must be enclosed within { and }.
{

Statement

if (speed >= 65)


{
fine = 10 * (speed - 60);
printf("Fine %d", fine);

}
else
printf("No fine.");
IMPORTANT!
Indent the statements that are controlled by the condition.

Selection Structures
The if/else Selection Structure
Allows us to execute one set of statements if the
expression is true and a different set if the expression is
false. An if/else statement has the following form:

False

Condition

True
Statements

Statements

Next statement
if (boolean expression)
true block
else
else block

Selection Structures
The if/else Selection Structure

For Example:
if (mark >= 50)
printf("Passed");
else
printf("Failed");

Selection Structures
Combining comparisons
AND operator evaluates true only if both conditions are true - true
only if temperature is greater than zero and less than 40.
if (temperature > 0 && temperature < 40)
printf("Normal temperature");
else
printf("Extreme temperature");
OR operator evaluates false only if both conditions are false - true if
either of the conditions are true, that is, if it is raining or highUV.
raining = 1;
highUV = 1;
if (raining || highUV)
printf("Take an umbrella!");

Selection Structures
Nested if Statements
Used to achieve multiple tests.
Find the smallest of 3 integers.
int num1, num2, num3, min;
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
min = num2;
else
min = num3;
printf("Minimum: %d", min);

Selection Structures
Nesting if statements may be difficult to read.
Use linearly nested if statements to test against many
values.
if (mark >= 85)
printf ("HD");
else if (mark >= 75)
printf ("D");
else if (mark >= 65)
printf ("C");
else if (mark >= 55)
printf ("P1");
else if (mark >= 50)
printf ("P2");
else if (mark >= 40)
printf ("F1");
else
printf ("F2");

Selection Structures
Lets revisit our Blackjack program

Include code that checks the players hand for 21


(Blackjack) on the first roll.
If the player has Blackjack, display Blackjack! Player
Wins! to the screen.
Otherwise, if the player does not have Blackjack, display Play
out player's hand to the screen.

Selection Structures
Answer
#include <stdlib.h>
#include <stdio.h>

int main() {
int playerDie1;
int playerDie2;
int playerTotal;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;

/* Display player hand to the screen */


printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);
if (playerTotal == 21) {
printf("Blackjack! Player wins!");
}
else {
printf("Play out player's hand...");
}
return 0;
}

Selection Structures
The switch Selection Structure

x=?

=1

=2

=3

=4

st1;

st2;

st3;

st4;

break;

break;

break;

break;

Selection Structures
The switch Selection Structure
The syntax for switch is:
switch(expression){
case label 1 : body 1
case label 2 : body 2
:
case label n : body n
default : default body
}

Selection Structures
The switch Selection Structure
char idChar;
int aCount= 0, bCcount = 0, cCount = 0;
switch (idChar)
{
case 'A':
aCount = aCount + 1;
break;
case 'B':
bCount = bCount + 1;
break;
case 'C':
cCount = cCount + 1;
break;
default:
/* Optional */
printf("Error");
}
Omitting break would cause the next action to be executed.

Control Structures
Loops are used when you need to repeat a set
of instructions multiple times.
C supports three different types of loops:
for loop
while loop
do/while loop

for loop
Good choice when you know how many times you
need to repeat the loop.

while loop
Good choice when you need to keep repeating the
instructions until a criteria is met.

Control Structures: while loop


The while repetition structure.

A while loop has the following form:


while (boolean expression) {
statements
}
As long as the boolen expression is true, the while block is
executed.
If the boolean expression is or becomes false, the loop
terminates.
Reuse common code by returning to a point in the program and
executing a block of code as many times as we need.
The program will loop back until the condition on the while line is
false. Each pass is called an iteration.

Control Structures: while loop


An example:
int a = 0;

while (a < 10) {


printf("%d\n", a);
a = a + 1;
}

Control Structures: while loop


Statements in the loop body are executed as long as the
boolean expression is true.
A while statement is usually preceded by initialisation.
A statement within the loop must eventually change the
condition.
int a = 0;

while (a < 10) {


printf("%d\n", a);
a = a + 1;
}

Control Structures: while loop


What is the output produced by the following code?
int a = 0;
/* initialise loop control
while (a < 3) {
/* test loop control */
printf("going loopy %d\n", a);
a = a + 1;
/* update loop control */
}
printf("yee ha!");

*/

Control Structures: while loop


What is the output produced by the following code?
int a = 3;

while (a >= 0) {
printf("In while loop %d\n", a);
a -= 1; a = a 1;
}
printf("The end!");

Control Structures: while loop


An example while loop:
To compute the sum of the first 100 integers:
1 + 2 + 3 + + 100
int sum = 0;
int number = 1;
while (number <= 100) {
sum = sum + number;
number = number + 1;
}
printf ("Sum: %d\n", sum);

It is possible to nest while loops.

Processing Input

A while loop is commonly used to process input.


Use a while loop to repeat a set of commands until
a condition is met.
When reading input, your loops should take the
following form (algorithm).
prompt user for data
read data

/* initialise loop control */

WHILE (value read in is OK)


perform the processing

/* test loop control */

prompt user for data


read data

/* update loop control */

Processing Input

An example (read and sum numbers until the user enters a negative
number):
#include <stdio.h>
int main()
{
int no;
int total = 0;
/* initialise loop control */
printf("Please enter a number (-1 to quit): ");
scanf("%d", &no);
/* test loop control */
while (no >= 0) {
printf("Number is: %d\n", no);
total = total + no;
/* update loop control */
printf("Please enter a number (-1 to quit): ");
scanf("%d", &no);
}
printf("\nSum of all numbers entered is: %d\n\n", total);
return 0;
}

Processing Input

An example (read and display menu commands until the user enters
'q' to quit):
#include <stdio.h>
int main()
{
char choice;

/* initialise loop control */


printf("Please enter [a, b, c or q to quit]: ");
scanf("%c", &choice);
/* test loop control */
while (choice != 'q') {
printf("Choice entered was: %c\n", choice);
/* update loop control */
printf("Please enter [a, b, c or q to quit]: ");
scanf(" %c", &choice);
}
printf("\nThanks - we\'re done here!\n\n");
return 0;
}

Processing Input
Lets revisit our Blackjack program now lets include code to play
out the players hand

Prompt for and read whether the player would like to hit (h) or stand
(s). Implement a loop which continues to simulate one die being
rolled until the user enters stand (s).
Display the value of die 1, die 2 and the total roll value as seen
below:
Player's hand is: 6 + 7 = 13
Play out player's hand...
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 13 + 5 = 18
Please enter h or s (h = Hit, s = Stand): s
Thanks for playing!

Processing Input
Lets revisit our Blackjack program
It does not make sense to continue rolling when the player busts
(exceeds 21).
Modify the loop developed in the previous stage so that it also stops
looping if the player busts (exceeds 21).
Player's hand is: 9 + 5 = 14
Play out player's hand...
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 14 + 1 = 15
Please enter h or s (h = Hit, s = Stand): h
Player's hand is: 15 + 10 = 25
Player busts!
Thanks for playing!

Processing Input
Answer
#include <stdlib.h>
#include <stdio.h>
int main() {
int playerDie1;
int playerDie2;
int playerTotal;
char play;
/* Roll player's hand */
playerDie1 = 1 + (rand()%11);
playerDie2 = 1 + (rand()%11);
/* Work out current hand total */
playerTotal = playerDie1 + playerDie2;

/* Display player hand to the screen */


printf("\n\nPlayer's hand is: %d + %d = %d", playerDie1, playerDie2, playerTotal);
:
:
:

Processing Input
:
if (playerTotal == 21) {
printf("Blackjack! Player wins!");
}
else {
printf("Play out player's hand...");
printf("\nPlease enter h or s (h = Hit, s = Stand): ");
scanf(" %c", &play);
while (playerTotal < 21 && play == 'h') {
/* Roll again (one die only) */
playerDie1 = 1 + (rand()%11);
/* Display the player's hand to the screen */
printf("Player's hand is: %d + %d = %d\n", playerTotal, playerDie1, (playerTotal+playerDie1));
playerTotal = playerTotal + playerDie1;
/* Prompt again only if player has not busted (i.e. hand total has not exceeded 21). */
if (playerTotal < 21) {
printf("\nPlease enter h or s (h = Hit, s = Stand): ");
scanf(" %c", &play);
}
}
}
printf("\nThanks for playing!\n");
return 0;
}

Processing Input
A note on reading characters (please keep this in mind when
undertaking practical and assignment work):
The scanf function behaves differently when the %c format specifier is
used from when the %d conversion specifier is used. When the %d
conversion specifier is used, white space characters (blanks, tabs or
newlines, etc) are skipped until an integer is found. However, when the
%c conversion specifier is used, white space is not skipped, the next
character, white space or not, is read.
You may find that this causes your loops to 'skip' the prompt and not
provide you with an opportunity to enter a character at the prompt.
To fix this, leave a space before the %c as seen in the following scanf
statement.

scanf(" %c", &response);

Processing Input
A note on reading characters continued
#include <stdio.h>

int main() {
char playAgain = 'y';
while (playAgain == 'y') {
printf("\n\nDo stuff...

: )\n\n");

/* space before %c skips white-space characters


such as newline */
printf("Play again [y|n]? ");
scanf(" %c", &playAgain);
}

return 0;
}

Processing Input

Another common use for a while loop is error checking of user input.
A program that generates a random number between 1-10, asks the user to guess the
number.
int main() {
int randomNo;
int guess;

/* Random number 1 - 10 */
/* User's guess
*/

/* Generate a random number 1 - 10 */


randomNo = 1 + (rand() % 10);
printf("\nRandom number is: %d\n", randomNo);
/* Prompt for and read user's guess */
printf("\nPlease enter your guess: ");
scanf("%d", &guess);
/* check to confirm that guess is in correct range test loop control */
while (guess < 1 || guess > 10) {
printf("Input must be between 1 - 10 inclusive.\n");
/* update loop control */
printf("\nPlease enter your guess: ");
scanf("%d", &guess);
}
/* Determine whether user guessed correctly */
if (guess == randomNo)
printf("\nWell done - you guessed it!\n");
else
printf("\nToo bad - better luck next time!\n");
return 0;

Processing Input

Another common use for a while loop is error checking of user input.
A program that reads and displays menu commands until the user enters 'q' to quit.
printf("Please enter [a, b, c or q to quit]: ");
scanf("%c", &choice);
/* check to confirm that user enters either 'a', 'b', 'c' or 'q' */
while (choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q') {
printf("\nInput must be a, b, c or q to quit!\nPlease try again...\n\n");
printf("Please enter [a, b, c or q to quit]: ");
scanf(" %c", &choice);
}
while (choice != 'q') {
printf("Choice entered was: %c\n", choice);

printf("Please enter [a, b, c or q to quit]: ");


scanf(" %c", &choice);
/* check to confirm that user enters either 'a', 'b', 'c' or 'q' */
while (choice != 'a' && choice != 'b' && choice != 'c' && choice != 'q') {
printf("\nInput must be a, b, c or q to quit!\nPlease try again...\n\n");

printf("Please enter [a, b, c or q to quit]: ");


scanf(" %c", &choice);
}
}
printf("\nThanks - we\'re done here!\n\n");
return 0;
}

Control Structures: do/while loop


The do/while repetition structure
The condition is tested after the loop so the statements are
executed at least once (whereas a while loop can be a 'zero
trip').
int product = 1;
int number = 2;
do {
product *= number;
number += 2;
} while (product <= 1000000);

Control Structures: for loop


Use a for loop when a variable runs from a starting to an ending
value with a constant increment or decrement.
The loop executes a known or fixed number of times.
The header of a for loop usually contains:
An initialisation statement of the loop control.
Executed before the condition is evaluated (or the body
executed).
A boolean expression.
Evaluated before the loop body is executed.
A increment or decrement statement.
Updates the loop control, executed after the loop body.
The variable should be int, not float not double.

Control Structures: for loop


The for repetition structure.
Use a for loop when number of iterations is known in advance.
A for loop has the following form:
for (initialise; boolean expression; increment)
{
statements
}

As long as the boolen expression is true, the for block is


executed.
If the boolean expression is or becomes false, the loop
terminates.

Control Structures: for loop


An example:
int a;

for (a = 0; a < 10; a++) {


printf("%d\n", a);
}

Control Structures: for loop


What is the output produced by the following code?
int a;

for (a = 0; a < 3; a++) {


printf("going loopy %d\n", a);
}
printf("yee ha!");

Control Structures: for loop


What is the output produced by the following code?
int a;

for (a = 3; a >= 0; a--) {


printf("In for loop %d\n", a);
}
printf("The end!");

Control Structures: for loop


In most cases, the for statement can be represented with
an equivalent while statement:
An example for loop:
To compute the sum of the first 100 integers:
1 + 2 + 3 + + 100

int sum = 0;
int number;
for (number = 1; number <= 100; number++) {
sum += number;
}
printf ("Sum: %d\n", sum);
It is possible to nest for loops.

Control Structures: for loop


Design:
Use for loops if you know exactly how many times a loop needs to
execute.
int main() {
int i;
int years;
printf("How many years? ");
scanf("%d", &years);
for (i = 0; i < years; i++) {
printf("In the years loop!\n");
}
return 0;
}

Use while loops if you dont know how many times a loop needs to
execute.
int main() {
char playAgain = 'y';
while (playAgain == 'y') {
printf("In the play again loop!\n");
printf("Play Again? ");
scanf(" %c", &playAgain);
}
return 0;
}

Control Structures: for loop


Write a program that asks the user to enter a number
between 1 and 10. Use a for loop to display a line
containing that number of adjacent asterisks.
For example, if your program reads the number seven, it
should print *******

Control Structures

End
Introduction to C (revision)
Control Structures

Looking forward to C++...

Deitel & Deitel. C How to Program. Fifth Edition. Pearson Education, Inc. 2007.

Chapter 18: C++ as a Better C; Introducing Object Technology


18.1 18.11
Chapter 19: Introduction to Classes and Objects
19.1 19.11
Chapter 20: Classes: A Deeper Look, Part 1
20.1 20.8
Chapter 21: Classes: A Deeper Look, Part 2
21.6

Introduction to C++
Developed by Bjarne Stroustrup at Bell Laboratories.
The name C++ includes Cs increment operator(++) to
indicate that C++ is an enhanced version of C.
Provides object-oriented programming capabilities.
C++ standard document Programming languages
C++ - ISO/IEC 14882-2011

Can use a C++ compiler to compile C programs.

C++ Program: Adding Two Integers


// Addition Program: Deitel & Deitel; C How to Program
// Deitel & Deitel. C How To Program. Fifth Edition. Pearson Education, Inc. 2007.

#include <iostream>
using namespace std;

int main()
{
int number1;
cout << "Enter first integer\n";
cin >> number1;
// declaration
int number2;
int sum;

cout << "Enter second integer\n";


cin >> number2;
sum = number1 + number2;
cout << "Sum is " << sum << endl;
// indicate that program ended successfully
return 0;
}
/* (C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved. */

Comments
C++ allows 2 types of comment delimiters:
The C delimiters (/* and */).
The C++ double slash (//) which provides a comment
from the double slash to the end of the current line.

The C++ Preprocessor


The preprocessor directive:
#include <iostream>
Include contents of input/output stream header file.
Allows the use of cout and cin

The Main Function


As in C, programs must have exactly one main
function.

int main ()
In C, return-value-type is not necessary.
In C++, return-value-type is necessary for all
functions.
If not specified, the compiler will generate an
error.

Identifiers
C++ identifiers are the same as in C.

Defining Variables
C++ definitions are the same as in C.
However,
In C, variable definitions must be before executable
statements.
In C++, variable definitions placed almost anywhere inside
a block.

Keywords
C++ keywords
Keywords common to the C and C++ programming languages
auto
continue

break
default

case
do

char
double

const
else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

C++ keywords
C++-only keywords
and
bool

and_eq
catch

asm
class

bitand
compl

bitor
const_cast

delete

dynamic_cast

explicit

export

false

friend

inline

mutable

namespace

new

not

not_eq

operator

or

or_eq

private

protected

public

reinterpret_cast static_cast

template

this

throw

true

try

typeid

typename

using

virtual

wchar_t

xor

xor_eq

(C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved.

Basic Data Types


The basic data types common to C & C++ are:

char
int
float
double

- an 8-bit character
- an integer
- single precision floating point
- double precision floating point

C++ only basic data types:


wchar_t
bool

- a wide (16 bit) character


- boolean
- evaluates to the constants true or
false.

Operators
C++ operators are the same as in C.
C does not have a boolean data type.
FALSE
TRUE

is represented by zero
is represented by any non-zero integer.

Relational, logical and conditional operators evaluate to TRUE


(non-zero integer) or FALSE (zero).

C++ has a bool data type which evaluates to the


constants true or false (keywords).
Can be initialised using integers, a non-zero value will convert to
true and a zero integer will convert to false.
Relational, logical and conditional operators evaluate to true or
false.

Operators continued
Scope Resolution Operator (::)
Unique to C++.
Provides access to variables that otherwise would be
masked within the current scope. For example:
int num = 100;
class AccumulateNum
{
int num;
public:
void setNum(int);
void printNum();
};
void AccumulateNum::printNum()
{
cout << local value of num is << num;
cout << external value of num is << ::num;
}

Control Structures
C++ control structures are the same as in C.
C++ allows declarations mixed with statements.
Define a control variable in the for loop. E.g:
for (int i = 0; i < 100; i++)
{ // i exists in this block
}
// i is unknown

Control variable can be used only in the body of the


for structure.
Control variable value is unknown outside the for
body.

You might also like