0% found this document useful (0 votes)
4 views

Chapter 1 - Introduction To Basic Computer Programming

Uploaded by

joelcherenet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 1 - Introduction To Basic Computer Programming

Uploaded by

joelcherenet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

Software

Download the Code::Blocks development environment:


http://www.codeblocks.org/downloads/26

Windows: get the codeblocks-16.01mingw-


nosetup.zip file and unzip it to a convenient folder.

Compiled by Dagne Walle 1


Introduction

Software
Instructions to command computer to perform
actions and make decisions
Hardware
Structured programming
Object-oriented programming

2 Compiled by Dagne Walle


What is a Computer?
Computer
Device capable of performing computations and making
logical decisions
Computer programs
Sets of instructions that control computer’s processing
of data
Hardware
Various devices comprising computer
– Keyboard, screen, mouse, disks, memory, CD-ROM,
processing units, …
Software
3 Programs that run on computer Compiled by Dagne Walle
Computer Organization
Six logical units of computer
1. Input unit
– “Receiving” section
– Obtains information from input devices
Keyboard, mouse, microphone, scanner, networks, …
2. Output unit
– “Shipping” section
– Takes information processed by computer
– Places information on output devices
Screen, printer, networks, …
Information used to control other devices

4 Compiled by Dagne Walle


Computer Organization
Six logical units of computer
3. Memory unit
– Rapid access, relatively low capacity “warehouse”
section
– Retains information from input unit
Immediately available for processing
– Retains processed information
Until placed on output devices
– Memory, primary memory
4. Arithmetic and logic unit (ALU)
– “Manufacturing” section
– Performs arithmetic calculations and logic decisions
5 Compiled by Dagne Walle
Computer Organization
Six logical units of computer
5. Central processing unit (CPU)
– “Administrative” section
– Supervises and coordinates other sections of
computer
6. Secondary storage unit
– Long-term, high-capacity “warehouse” section
– Storage
Inactive programs or data
– Secondary storage devices
Disks
– Longer to access than primary memory
6 – Less expensive per unit than primary memory
Compiled by Dagne Walle
Very brief history of C++

C++

For details more check out A History of C++: 1979−1991 Compiled by Dagne Walle 7
Characteristics of C++
C++ is…
Compiled. A separate program, the compiler, is used to
turn C++ source code into a form directly executed by the
CPU.
Strongly typed and unsafe: Conversions between variable
types must be made by the programmer (strong typing) but
can be avoided when needed (unsafe)
C compatible: call C libraries directly and C code is nearly
100% valid C++ code.
Capable of very high performance: The programmer has
a very large amount of control over the program execution
Object oriented: With support for many programming
styles (procedural, functional, etc.)
No automatic memory management: The programmer is in 8
Compiled by Dagne Walle
control of memory usage
C++ is Object-oriented programming
“Class Car”
OOP defines classes to represent
these things.
Classes can contain data and methods public interface
(internal functions).
Classes control access to internal data
and methods. A public interface is
used by external code when using the
class.
This is a highly effective way of
modeling real world problems inside
of a computer program.

private data and methods

Compiled by Dagne Walle 9


When to choose C++
Choose C++ when:
Program performance matters
Dealing with large amounts of data, multiple CPUs,
complex algorithms, etc.
Programmer productivity is less important
It is faster to produce working code in Python, R,
Matlab or other scripting languages!
The programming language itself can help organize
your code
Access to libraries: Ex. Nvidia’s CUDA Thrust
library for GPUs
Compiled by Dagne Walle 10
What is a Variable?

A variable is a memory address where


data can be stored and changed.

Declaring a variable means specifying


both its name and its data type.

Compiled by Dagne Walle 11


Variables
• A variable is a logically named, typed, structured
piece of storage
• Name allows us to refer to the stored structure
• Type allows us to know structure
• Variables can be assigned new values
• Program can manipulate them!!

Compiled by Dagne Walle 12


Variables

• Definition: allocates space for storage


• Declaration: specifies name and type
– So variable can be referenced here
– … and defined elsewhere
• Type var_name, var_name, …;
• All vars have type given at start
• Good practice: one per line of code!

Compiled by Dagne Walle 13


Initialization

• Good idea: ALWAYS INITIALIZE!!!!


• Initialization – object gets value at time of
definition (when created)
– May be any expression that can be evaluated at time
of creation
– Name becomes visible immediately
– Hence can be used in subsequent initializations in
same line!
Compiled by Dagne Walle 14
Variable Initialization
int i = 0, j = 2*i; /* j initial uses value
of i immediately */

int k = sizeof(double); /* value is


a function that can
be evaluated when k
is defined */
int a = 0, b = 0; /* all type int a and b
initialized to 0 */

Compiled by Dagne Walle 15


What Does a
Variable Declaration Do?

A declaration tells the compiler to allocate


enough memory to hold a value of this
data type, and to associate the identifier
with this location.
int ageOfDog;→
char letter; →
float taxRate;→

Compiled by Dagne Walle 16


Variable Declaration
All variables must declared before use.
At the top of the program
Just before use.
Commas are used to separate identifiers of the
same type.
int count, age;

Variables can be initialized to a starting value


when they are declared
int count = 0;
int age, count = 0;
Compiled by Dagne Walle 17
Assignment Operator Syntax

Variable = Expression
First, expression on right is evaluated.
Then the resulting value is stored in the
memory location of Variable on left.

NOTE: An automatic type force occurs after


evaluation but before the value is stored if
the types differ for Expression and Variable
Compiled by Dagne Walle 18
Assignment Operator
An operator to give (assign) a value to a
variable.
Denote as ‘=‘
Only variable can be on the left side.
An expression is on the right side.
Variables keep their assigned values until
changed by another assignment statement
or by reading in a new value.
Compiled by Dagne Walle 19
Assignment Operator
Mechanism

Example: 5
int count = 5;
int starting; 0

starting = count + 5;
Expression evaluation:
Get value of count: 5
Add 5 to it. 10
Assign to starting
Compiled by Dagne Walle 20
What is an Identifier?

An identifier is the name to denote labels,


types, variables, constants or functions, in
a C++ program.
C++ is a case-sensitive language.
Work is not work

Identifiers should be descriptive


Using meaningful identifiers is a good
programming practice
Compiled by Dagne Walle 21
Identifiers

• Identifier = name – for variable, function,


constant, class, type, etc.
• Cannot be a keyword in C++
• Identifiers may be composed of letters, digits,
and underscore char
– Must begin with _ or letter
• Identifiers are case-sensitive
– Main is not main is not MAIN! Compiled by Dagne Walle 22
Identifier
Identifiers must be unique
Identifiers cannot be reserved words (keywords)
double main return
Identifier must start with a letter or underscore, and
be followed by zero or more letters (A-Z, a-z), digits
(0-9), or underscores
VALID
age_of_dog _taxRateY2K
PrintHeading ageOfHorse
NOT VALID
age# 2000TaxRate Age-Of-Dog
main

Compiled by Dagne Walle 23


What is a Type?
• A type is a qualifier that is used by the
compiler
− Machine languages do not have types
• The type of a variable or constant tells the
compiler:
– How much space the object occupies
– What operations on the object mean

Compiled by Dagne Walle 24


Built-in (aka primitive or intrinsic) Types
“primitive” or “intrinsic” means these types are not
objects
Here are the most commonly used types.
Note: The exact bit ranges here are platform and
compiler dependent!
Typical usage with PCs, Macs, Linux, etc. use
these values
Variations from this table are found in
specialized applications like embedded system
processors.

Compiled by Dagne Walle 25


C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

address
float double long double

pointer reference
Compiled by Dagne Walle 26
C++ Primitive Data Types

Primitive types

integral floating

char short int long bool float double long double

unsigned

Compiled by Dagne Walle 27


some
Arithmetic Types in C++

Type Meaning Minimum Size


bool Boolean NA
char character 8 bits
wchar_t wide character 16 bits
short short integer 16 bits
int integer 16 bits
long long integer 32 bits
long long very long integer 64 bits
float floating point 6 (7) sig. digits
double double 10 (16) sig. digits
28
long double Extended 10 sig. digits
Which Type to Use?
• General Usage
– int – most integer arithmetic
– double – for floating point computation
− char – only for chars
− bool – only for Booleans
• Unsigned
– Used to save space – who cares?
– Do not mix signed and unsigned!
– Can cause headaches easily - avoid
Compiled by Dagne Walle 29
Samples of C++ Data Values
int sample values
4578 -4578 0

bool values
true (1) false(0)

float sample values


95.274 95.0 .265

char sample values


‘B’ ‘d’ ‘4’ ‘?’ ‘*’

Compiled by Dagne Walle 30


bool Data Type
Type bool is a built-in type consisting of just 2
values, the constants true and false
We can declare variables of type bool
bool hasFever; // true if has high temperature
bool isSenior; // true if age is at least 55
The value 0 represents false
ANY non-zero value represents true

Compiled by Dagne Walle 31


Boolean Expression
Expression that yields bool result
6 Relational Operators:
< <= > >= == !=
3 Logical Operators:
! && ||

Compiled by Dagne Walle 32


Boolean Expression (examples)
taxRate is over 25% and income is less than $20000

temperature is less than or equal to 75 or humidity is


less than 70%

age is between 21 and 60

age is 21 or 22

Compiled by Dagne Walle 33


Boolean Expression (examples)
(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age >= 21) && (age <= 60)

(age == 21) || (age == 22)

Compiled by Dagne Walle 34


Relational Operators
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7
y=x<3 0
y=x>3 1 Compiled by Dagne Walle 35
Logical Operators
int age ;
bool isSenior, hasFever ;
float temperature ;
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ; // isSenior is false
hasFever = (temperature > 98.6) ; // hasFever is
true
EXPRESSION VALUE
isSenior && hasFever false
isSenior || hasFever true
!isSenior true
36
!hasFever false Compiled by Dagne Walle
Arithmetic operators:
Arithmetic: + - * / % ++ --
Logical: && (AND) ||(OR) !(NOT)
Comparison: == > < >= <= !=
Beyond arithmetic operation , the “+” is used to
concatenate strings.
What happens when a syntax error is made? The
compiler will complain and refuse to compile the
file.

Compiled by Dagne Walle 37


Special Characters

• Some characters are not printable


• Some characters have special meaning
to the language
• For these, we need escape sequences
– All start with backslash \
– Some predefined: \n newline
– Any by \x where x is a number
Compiled by Dagne Walle 38
Special Characters

newline \n horizontal tab \t alert (bell) \a


vertical tab \v backspace \b double quote \”
backslash \\ question mark \? single quote \'
carriage return \r form feed \f

Can use as single character:


cout << '\n'; cout << “\tHello!\n”;
Generalized escape sequence:
\12 = \014 = x0c = newline in decimal, octal, hex
Note: only the first 3 octal digits are accepted
Note: hex uses all the following digits (!) 39
Compiled by Dagne Walle
Special Characters
Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

40 Compiled by Dagne Walle


C++ Keywords
noexcept static_assert union
nullptr static_cast unsigned
operator struct using
private switch virtual
protected template void
public this volatile
register thread_local wchar_t
reinterpret-cast throw while
return true
short try
signed typedef
sizeof typeid
static typename Compiled by Dagne Walle 41
Simplified IO

C language use printf for output and scanf for input


For standard output, use cout
For standard input, use cin
File IO is also simpler, and will be discussed later
Note: one can still use the IO syntax of C in C++

Compiled by Dagne Walle 42


Simplified IO
Include iostream.h instead of stdio.h
Input/output
cin- object providing a connection to the keyboard
– Standard input stream
– Normally keyboard
Cout-object providing a connection to the monitor
– Standard output stream
– Normally computer screen
cerr -object providing a connection to error streem
– Standard error stream
– Display error messages

43 Compiled by Dagne Walle


Chaining Calls
Multiple uses of the insertion and extraction operator
can be chained together:
cout << E1 << E2 << E3 << … ;
cin >> V1 >> V2 >> V3 >> …;
Equivalent to performing the set of insertion or
extraction operators one at a time
Example
cout << “Total sales are $” << sales << ‘\n’;
cin >> Sales1 >> Sales2 >> Sales3;

Compiled by Dagne Walle 44


Cout
The reserved word, endl, ensures that
the next cout command prints its stuff
on a new line.
New lines can also be added using “\n”.

Compiled by Dagne Walle 45


Cout
For printing output, use this syntax:
cout << a string or an expression;
This prints out the string or the value of the
extpression.
For output chaining, use this syntax
cout << S1 <<S2<<S3<<endl;
Each Si is a string or an expression. The effect is to
print out the value of S1 followed by the value of
S2, followed by the value of S3.

Compiled by Dagne Walle 46


The Insertion Operator (<<)
To send output to the screen we use the insertion
operator on the object cout
Format: cout << Expression;
The compiler figures out the type of the object and
prints it out appropriately
cout << 5; // Outputs 5
cout << 4.1; // Outputs 4.1
cout << “Abebe”; // Outputs String
cout << ‘\n’; // Outputs a newline

Compiled by Dagne Walle 47


Cout (Examples)

Statements Output
int x=3; double y =4.5;
cout <<“the value of x=“<<x; the value of x=3; y=4.5
cout<<“; y=“<<y<<endl;
x+y=7.5
cout <<“x+y”<<x+y;
int x=3; double y =4.5; x=3
cout <<“x = “<<x<<“\n”; y=4.5
cout<<“y=“<<y;
x+y=7.5
cout <<“\nx+y”<<x+y;
Compiled by Dagne Walle 48
Extraction Operator (>>)
Variable cin is predefined to denote an input
stream from the standard input device (the
keyboard)
The extraction operator >> called “get from”
takes 2 operands. The left operand is a stream
expression, such as cin--the right operand is a
variable of simple type.
Operator >> attempts to extract the next item
from the input stream and store its value in the
right operand variable.
Compiled by Dagne Walle 49
The Extraction Operator (>>)
To get input from the keyboard we use the
extraction operator and the object cin
Format: cin >> Variable;
No need for & in front of variable
The compiler figures out the type of the variable and
reads in the appropriate type
int X;
float Y;
cin >> X; // Reads in an integer
cin >> Y; // Reads in a float

Compiled by Dagne Walle 50


Input Statements
SYNTAX

cin >> Variable >> Variable . . . ;

cin statements can be linked together using >> operator.


These examples yield the same output:

cin >> x;
cin >> y;

cin >> x >> y;


Compiled by Dagne Walle 51
Cin
For reading input values into variables:
cin >> variableName1 >> variableName2 >> variableName3;

This reads the input from the standard input


(say the screen for now), puts the first read
value in variableName1, the second read
value in variableName2, and the third read
value in variableName3.

Compiled by Dagne Walle 52


Cin (Examples)
Suppose you want to read an int value and a
double value into variables n and x.

int n; double x;
cout<<“enter an int n, and a double X: “;
cin>>n>>x; // use of cin
cout<<“You entered int n=“<<n;
cout<<“, and double x=“<<x<<endl;

Compiled by Dagne Walle 53


How Extraction Operator works?
Input is not entered until user presses
<ENTER> key.
Allows backspacing to correct.
Skips whitespaces (space, tabs, etc.)
Multiple inputs are stored in the order
entered:
cin>>num1>>num2;
User inputs: 3 4
Assigns num1 = 3 and num2 = 4

Compiled by Dagne Walle 54


Cin>>
cin >> integer1; integer1 45
Assume user entered 45
integer1 45
cin >> integer2;
integer2 72
Assume user entered 72

integer1 45
integer2 72
sum = integer1 + integer2;
sum 117

55 Compiled by Dagne Walle


Type Casting
C++ is strongly typed. It will auto-convert a variable of
one type to another in a limited fashion: if it will not change
the value.
short x = 1 ;
int y = x ; // OK
short z = y ; // NO!

Conversions that don’t change value: increasing precision


(float → double) or integer → floating point of at least the
same precision. double x = 1.0 ;
int y = (int) x ;
float z = (float) (x / y) ;

C++ allows for C-style type casting with the syntax: (new
type) expression

Compiled by Dagne Walle 56


Type Casting
static_cast<new type>( expression )
This is exactly equivalent to the C style cast.
This identifies a cast at compile time.
This will allow casts that reduce precision (ex. double →
float) double d = 1234.56 ;
float f = static_cast<float>(d) ;
// same as
float g = (float) d ;

~99% of all your casts in C++ will be of this type.


dynamic_cast<new type>( expression)
Special version where type casting is performed at runtime,
only works on reference or pointer type variables.
Usually handled automatically by the compiler where
needed, rarely done by the programmer. 57
Compiled by Dagne Walle
Simple Flow of Control
Three processes a computer can do:
Sequential
expressions, insertion(<<) and extraction(>>)
operations
Selection (Branching)
if statement, switch statement
Repetition/Iteration (Loop)
while loop, do-while loop, for loop

Compiled by Dagne Walle 58


Simple if Statement flow chart
Is a selection of whether or not to execute a
statement or a block of statement.

TRUE
expression

statement(s) FALSE

Compiled by Dagne Walle 59


if Statement Flow Chart
Flowchart of pseudocode statement
A decision can be made on
any expression.
zero - false
true nonzero - true
grade >= 60 print “Passed”
Example:
3 - 4 is true

false

60 Compiled by Dagne Walle


Simple if Statement Syntax
if (Boolean Expression)
Statement

if (Bool-Expr)
{
Statement_1

Statement_n
}

Compiled by Dagne Walle 61


These are NOT equivalent. Why?
if (number == 0 ) if (number == 0 )
cout << “Hmmmm ”;
{ cout << “You entered invalid number.\n”;
cout << “Hmmmm ”;
cout << “You entered invalid When number has value 0,
number.\n”; the output will be:
Hmmmm You entered invalid number.
}

When number has value NOT


When number has value 0, the 0, the output will be:
output will be: You entered invalid number.

Hmmmm You entered invalid


number.

When number has value NOT


0, there is NO output.
Compiled by Dagne Walle 62
These are equivalent. Why?
if (number == 0 ) if (!number )
{ {
. .
. .
} }

Read as: Read as:


If number is NOT true
If number is 0 If number is false

Each expression is only true when number has value 0.

Compiled by Dagne Walle 63


If-else Statement Flow Chart
provides selection between executing
one of 2 clauses (the if clause or the
else clause)
TRUE FALSE
expression

if clause else clause

Compiled by Dagne Walle 64


Use of blocks
Denoted by { .. }
Recommended in controlled structures (if and loop)
Also called compound statement.

if (Bool-Expression )
{
“if clause”
}
else
{
“else clause”
}

Compiled by Dagne Walle 65


if/else Satatment
Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";

66 Compiled by Dagne Walle


Ternary conditional operator (?:)
Ternary conditional operator (?:)
Three arguments (condition, value if true,
value if false)
Code could be written:
cout << ( grade >= 60 ? “Passed” : “Failed” );

Condition Value if true Value if false

false true
grade >= 60

print “Failed” print “Passed”

67 Compiled by Dagne Walle


What is the switch Statement
Similar to the if statement
Can list any number of branches
Used in place of nested if statements
Used only with integer expressions
(true/false or int or char)
Avoids confusion of deeply nested if
statements

Compiled by Dagne Walle 68


switch Multiple-Selection
Structure
true
case a case a action(s) break

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break
false

default action(s)

69 Compiled by Dagne Walle


The switch Statement
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statement;
} expression must return an integer value, i.e. be an integer
70
Compiled by Dagne Walle
Switch Statement with integer expression
switch (choice)
{
case 1:
cout << “The greatest ” << endl;
break;
case 2:
cout << “Exciting team ”<< endl;
break;
case 3:
cout << “Boring ” << endl;
break;
case 4:
cout << “Bye Bye” << endl;
}
Compiled by Dagne Walle 71
The switch Statement
What is the purpose of the break statement?
• The break Statement prevents “fall
through”
• It makes the computer jump out of the
current block
• Recall the switch statement to execute all
statements below the point of entering the
statement.
• This can be a problem, if we don’t use
break keyword.

Compiled by Dagne Walle 72


Switch Statement illustrate fall through again

switch (choice){
case 1:
cout << “The greatest ” << endl;
case 2:
cout << “Exciting team ”<< endl;
case 3:
cout << “Boring ” << endl;
case 4:
cout << “Bye Bye << endl;
}
Compiled by Dagne Walle 73
The switch Statement

What will be the output when the user enters 1?


The greatest
Exciting team
Boring
Bye Bye

Compiled by Dagne Walle 74


The switch Statement

What will be the output when the user enters 2?


Exciting team
Boring
Bye Bye

Compiled by Dagne Walle 75


The switch Statement

What will be the output when the user enters 3?


Boring
Bye Bye

Compiled by Dagne Walle 76


The switch Statement

What will be the output when the user enters 4?


Bye Bye

Compiled by Dagne Walle 77


Classic use of switch Statements:
for Menu processing
* * * * Menu * * * *

1. Man United
2. Chelsea
3. Arsenal
4. Quit

Choose either 1, 2, 3 or 4:
Compiled by Dagne Walle 78
Example program to Demo
#include <iostream> //see displaymenu3.cpp
Using namespace std;
int main() {
int choice;
cout << "*********** MENU **************\n";
cout <<endl;
cout << " 1. Man United" << endl;
cout << " 2. Chelsea" << endl;
cout << " 3. Arsenal" << endl;
cout << endl;
cout << "Please choose 1, 2 or 3 : ";
cin >> choice;
switch (choice) {
case 1: cout << “The greatest team“ << endl;
break;
case 2: cout << “Exciting team“ << endl;
break;
case 3: cout << “Boring team“ << endl;
break;
case 4: cout << “Bye Bye << endl;
break;
}
return 0;
Compiled by Dagne Walle 79
}
The switch Default Statement captures errors
or perform default action
e.g. if user enter any other number
switch (choice){
case 1: cout << “The greatest ” << endl;
break;
case 2: cout << “Exciting team ”<< endl;
break;
case 3: cout << “Boring ” << endl;
break;
case 4: cout << “Bye Bye “ << endl;
break;
default: “Incorrect choice” << endl;
}

Compiled by Dagne Walle 80


Nested Switch Statements
For example:
switch( CarType )
{
case Toyota:
switch( EngineCapacity)
{
case 1500:cout << “This is underpowered “;
break;
case 1800: cout << “This is just right”;
break;
case 2000: cout<<“This is expensive to buy”;
}; //closes second switch
case Hummer: cout<<“This is very expensive to buy”;
break;
default: cout << “Unknown model”; Compiled by Dagne Walle 81
} //closes first switch
Problems with switch
Strange rules, once a condition is tested true
execution proceeds until break or end of switch.
Control “falls through” the switch
Get in the habit of always putting breaks in and
putting a default condition in.
Less satisfactory to use where floats or Boolean
expressions are tested.
Putting in semi colon ‘;’after case rather than
colon ‘:’

Compiled by Dagne Walle 82


Recall Purpose of
Loops/Repetition
To apply the same steps again and again to a
block of statements.
Recall a block of statement is one or more
statement, block usually defined by braces { …
} with syntactically correct statements inside.

Compiled by Dagne Walle 83


Most Common Uses of Loops
You should master all these!
For counting
For accumulating, i.e. summing
For searching
For sorting
For displaying tables
For data entry – from files and users
For menu processing
For list processing

Compiled by Dagne Walle 84


Types of loops

while
for
do..while

Compiled by Dagne Walle 85


C/C++ Loop Structures
Pre-test (the test is made before entering the
loop)
while loops
– general purpose
– Event controlled (variable condition)
for loops
– When you know how many times (fixed condition)
– When you process arrays (more in later lectures)
Post-test (the test is done at the end of the loop)
do … while loops
– When you do not know how many times, but you know you
need at least one pass.
– Data entry from users

Compiled by Dagne Walle 86


While Loop

SYNTAX
while ( Expression )
{
… // loop body
}
No semicolon after the boolean expression
Loop body can be a single statement, a null
statement, or a block.

Compiled by Dagne Walle 87


While Loop Mechanism
When the • When the
expression is
tested and expression
found to be
FALSE
Expression
is tested
false, the loop and found
is exited and
control passes
TRUE to be true,
to the
body
the loop
statement body is
statement
which follows
the loop executed.
body. Then, the
expression
is tested
again.
Compiled by Dagne Walle 88
While Loop Example
int count ;
count = 0; // initialize LCV
while (count < 5) // test expression
{
cout << count << “ ”; // repeated action
count = count + 1; // update LCV
}
cout << “Done” << endl ;
LCV: Loop Controlled Variable

Compiled by Dagne Walle 89


Loop Tracing
int count ; count Expression Output
count = 0; 0 true 0

while (count < 5) 1 true 01


2 true 012
{
3 true 0123
cout << count << “ ”;
4 true 01234
count = count + 1; 5 false 0 1 2 3 4 Done
}
cout << “Done” << endl
;

Compiled by Dagne Walle 90


Increment and Decrement
Operators
Denoted as ++ or --
Mean increase or decrease by 1
Pre increment/decrement: ++a, --a
Increase/decrease by 1 before use.
Post increment/decrement: a++, a--
Increase/decrease by 1 after use.
Pre and Post increment/decrement yield
different results when combining with another
operation.
Compiled by Dagne Walle 91
Pre and Post
Increment and Decrement
int count ; count Expression Output
count = 0; 0 true 0
while (count < 5) 1 true 01
{ 2 true 012
cout << count++ << “ “ ; 3 true 0123
} 4 true 01234
cout << “Done” << endl ; 5 false 0 1 2 3 4 Done
int count ; count Expression Output
count = 0; 0 true 1
while (count < 5) 1 true 12
{ 2 true 123
cout << ++count << “ “ ; 3 true 1234
} 4 true 12345
cout << “Done” << endl ; 5 false
92
1 2 3 4 5 Done
Compiled by Dagne Walle
Do-While Loop

SYNTAX
do
{
… // loop body
} while ( Expression ); //note semi colon
Insured that the loop is executed at least once
The LCV is initialized/updated before the end of the loop.
Boolean expression is tested at the end of the loop.
There is a semicolon after the boolean expression.

Compiled by Dagne Walle 93


Do-While Loop Mechanism
• The loop body is executed first

When the • When the


expression is expression is
tested and body tested and
found to be statement found to be
false, the loop true, the
is exited and loop body is
control passes TRUE
FALSE executed.
to the
statement
Expression Then, the
which follows expression is
the loop tested again.
body.

Compiled by Dagne Walle 94


do/while Repetition Structure
Similar to while structure
Makes loop continuation test at end, not
beginning
Loop body executes at least once
Format action(s)

do {
statement true
condition
} while ( condition );
false

95 Compiled by Dagne Walle


Do-While Loop Example
int ans;
do
{
cout << “Choose a number from 1 to 4: “;// repeated action
cin >> ans; // LCV is initialized or updated
} while (ans >= 1 && ans <= 4); // test expression
cout << “Done”;

Output Input ans Expression


Choose a number from 1 to 4: 2 2 true
Choose a number from 1 to 4: 3 3 true
Choose a number from 1 to 4: 1 1 true
Choose a number from 1 to 4: 5 5 false
Done Compiled by Dagne Walle 96
Do-While

do
{
cin >> answer ; // accept choice

if ( ( answer != ‘a’ ) && ( answer != ‘A’ ) )


{
cout << “Please Try again: incorrect answer “;
}
else
{
cout<<“congratulation you got the answer”;
}
} while ( ( answer = ‘a’ ) && ( answer = ‘A’ ) ) ;

Compiled by Dagne Walle 97 97


Do-While Loop vs. While Loop

POST-TEST loop PRE-TEST loop


(exit-condition) (entry-condition)
The looping condition The looping condition
is tested after is tested before
executing the loop executing the loop
body. body.
Loop body is always Loop body may not
executed at least be executed at all.
once.
Compiled by Dagne Walle 98
The for Statement
Used as a counting loop
Used when we can work out in advance the
number of iterations, i.e. the number of
times that we want to loop around.
Semicolons separate the items in the for
loop block
There is no semi colon at the end of the for loop
definition at the beginning of the statement

Compiled by Dagne Walle 99


The for Statement Syntax
start condition while condition change expression

Example:
for (count=1; count < 7; count++)
{
cout << count << endl;
}

Compiled by Dagne Walle 100


A Simple Example
Create a table with a for loop
int num;
cout << "NUMBER\tSQUARE\tCUBE\n“;
cout << "------\t------\t----\n";

for (num = 1; num < 11; num++) {


cout << num << “\t“;
cout << num * num << “\t“;
cout << num * num * num<<“\n";
}
NUMBER SQUARE CUBE
---------- ---------- ------
1 1 1
2 4 8
. . .
. . .
10 100 1000
Compiled by Dagne Walle 101
for and if Statements working together.
Simple search for divisors
Given an integer number find all the numbers
that divide exactly into it (including 1 and itself).
Think I can
use % operator
to find divisors

e.g. if number = 12, divisors are 1,2,3,4,6,12

Compiled by Dagne Walle 102


Solution Design
1. Get the number from user
2. By starting with check number=1 and
finish with number (is this efficient?)
1. find the remainder of dividing number with
current check number
2. if remainder is 0 display current check number
as a divisor.
3. otherwise do not display anything

Compiled by Dagne Walle 103


Program fragment for finding divisors of an integer
cout << “Enter an integer :”;
cin >> number;
for (j = 1; j <= number; j++)
{ if (number % j == 0)
{ cout << j << “ is a divisor of “;
cout << number << endl;
}
}//this program determines whether we have a perfect
number

Compiled by Dagne Walle 104


Common errors in constructing
for Statements
for (j = 0, j < n, j = j + 3)

// commas used when semicolons needed

for (j = 0; j < n)

// three parts needed

for (j = 0; j >= 0; j++)

?????what is wrong here ?????

for (j=0, j=10; j++);

Compiled by Dagne Walle 105


Loop design
Seven Loop Design Factors
1. What is the condition that ends the loop?
2. How should the condition be setup or primed?
3. How should the condition be updated?
4. What processes are being repeated?
5. How do you set up the processes?
e.g. initialise event counters or accumulators
6. How is the process updated?
e.g. update accumulators and counters
7. What is the expected state of the program at exit
from loop?

Compiled by Dagne Walle 106


Programming convention
Use of integers called i,j,k
You will see them all the time.
Most commonly used as loop control variables
Conventionally used for counters
We will see later that counters often have a dual
use as array indices.
arrays to be discussed in later lectures
When you see i,j,k declared expect to see a
loop!

Compiled by Dagne Walle 107


Example of Repetition

int n;

for ( int i = 1 ; i <= n ; i++ )


{
cout << i << “ Potato” << endl;
}

Compiled by Dagne Walle 108


num ? Example of Repetition

int n;

for ( int i = 1 ; i <= n ; i++ )

cout << i << “ Potato” << endl;

OUTPUT

109
Compiled by Dagne Walle
num 1 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

110
Compiled by Dagne Walle
num 1 Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

111
Compiled by Dagne Walle
num 1 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato

112
Compiled by Dagne Walle
num 2 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato

113
Compiled by Dagne Walle
num 2 Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato

114
Compiled by Dagne Walle
num 2 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato

115
Compiled by Dagne Walle
num 3 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato

116
Compiled by Dagne Walle
num 3 Example of Repetition

int num;
true

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato

117
Compiled by Dagne Walle
num 3 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato
3Potato 118
Compiled by Dagne Walle
num 4 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato
3Potato 119
Compiled by Dagne Walle
num 4 Example of Repetition

int num;
false

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

OUTPUT

1Potato
2Potato
3Potato 120
Compiled by Dagne Walle
num 4 Example of Repetition

int num;
false

for ( num = 1 ; num <= 3 ; num++ )

cout << num << “Potato” << endl;

When the loop control condition


is evaluated and has value false, the
loop is said to be “satisfied” and
control passes to the statement
following the for statement.
Compiled by Dagne Walle 121
The output was:

1Potato
2Potato
3Potato

Compiled by Dagne Walle 122


Nested Loops
Recall when a control structure is contained
within another control structure, the inner one
is said to be nested.
if ... for...
for ... for ...

You may have repetition within decision and


vice versa.
Compiled by Dagne Walle 123
Nested Loops for within for
Example :
int row, col;
for (row = 0; row < 5; row++)
{
cout << "\n" <<row; //throws a new line
for (col = 1; col <= 3; col++)
{
cout <<"\t" << col;
}
cout << "\t**"; //use of tab
}

Compiled by Dagne Walle 124


CAUTION! What is the output from this loop?
int count;
for (count = 0; count < 10; count++) ;
{
cout << “*” ;
}

Compiled by Dagne Walle 125


Infinite loop example 2: OUTPUT
*
no output from the for loop! Why?
the ; right after the ( ) means that the body statement is a
null statement
in general, the Body of the for loop is whatever statement
immediately follows the ( )
that statement can be a single statement, a block, or a null
statement
actually, the code outputs one * after the loop completes
its counting to 10
Compiled by Dagne Walle 126
Nested Loops – Example 1
Output
0 1 2 3 **
1 1 2 3 **
2 1 2 3 **
3 1 2 3 **
4 1 2 3 **

variable col changes from


variable row changes from
1 to 3 for every time row
0 to 4
changes 127
Compiled by Dagne Walle
Infinite loops example 1

for (j=0; j>=0; j++) {


cout << j << endl;
}

Compiled by Dagne Walle 128


Loop-Controlled Types
Count-controlled: repeat a specified number of times.
Event-driven: some condition within the loop body
changes and this causes the repeating to stop.
Sentinel-controlled: using a specific value to end.
Sentinel: a value that cannot occur as valid data.
Ask-before-Continuing: ask users if they want to
continue.
Flag-Controlled Loops: use a variable whose value is
changed when an event occurs (usually from false
to true).
Compiled by Dagne Walle 129
Count-Controlled Loop

Has a loop control variable (LCV) as a


counter.
LCV must be
Initialized before start of the loop
Tested (boolean expression)
Updated

Compiled by Dagne Walle 130


Event-driven loop
double salary;
cout << "Enter you salary: ";
cin >> salary;
int years = 0;
while (salary < 50000) {
salary = salary * 1.02;
years++;
}
cout << “You need “ << years << “years to get to
50K";
Compiled by Dagne Walle 131
Sentinel-Controlled

do
{
cout<< ”Enter salary, type -1 to exit”; // no one
earns negative salary

cin>>salary;
// process income
} while (salary > 0);

Compiled by Dagne Walle 132


Ask-before-Continuing
char ans = ‘y’; // LCV is initialized
while (ans == ‘Y’ || ans == ‘y’) // test expression
{
doSomething; // repeated action
cout << “Do you want to continue? ”;
cin >> ans; // LCV is updated
};

Compiled by Dagne Walle 133


Break Statement Revisited

break statement can be used with Switch or any of


the 3 looping structures
it causes an immediate exit from the Switch, while,
do-while, or for statement in which it appears
if the break is inside nested structures, control exits
only the innermost structure containing it

Compiled by Dagne Walle 134


Continue Statement
is valid only within loops
terminates the current loop iteration, but not the
entire loop
in a for or while, continue causes the rest of the
body statement to be skipped--in a for statement,
the update is done
in a do-while, the exit condition is tested, and if
true, the next loop iteration is begun

Compiled by Dagne Walle 135


BREAK statement

allows to exit from any loop.


do
{
cin>>x;
if (x % 2 ==0)
break;
} while (x > 0); // exits when an even number is
entered
Compiled by Dagne Walle 136
The break Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
break;
cout << “j is “ << j<< ‘\n’;
}
cout << “We are out of the loop as j=70.\n”;

j is 50
j is 60
We are out of the loop as j=70.
Compiled by Dagne Walle 137
CONTINUE Statement
allows you to skip the rest of the loop body and go back
to the beginning of the loop.
do
{
cin>>x;
if (x % 2 == 0)
continue;
cout<<x<<endl;
} while (x <100);
//prints out all odd numbers entered less than 100

Compiled by Dagne Walle 138


The continue Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
continue; //skips the 70
cout << “j is “ << j<< ‘\n’;
}//see UseContinue1.cpp
cout << “We are out of the loop” << endl;
j is 50
j is 60
j is 80
Compiled by Dagne Walle 139
We are out of the loop.
break and continue
while ( - - - )
while ( - - - )
{
{
statement 1;
statement 1;
if( - - - )
if( - - - )
continue
break
statement 2;
statement 2;
}
}
statement 3;
statement 3;
Compiled by Dagne Walle 140
Constants

Syntax: const type identifier = value;


Ex: const double TAX_RATE = 0.08;
Convention: use upper case for constant ID.

Compiled by Dagne Walle 141


Why use constants?
Clarity: Tells the user the significance of the
number. There may be the number 0.08 elsewhere
in the program, but you know that it doesn’t stand
for TAXRATE.
Maintainability. Allows the program to be
modified easily.
Ex: Program tax compute has const double
TAXRATE=0.0725. If taxes rise to 8%, programmer
only has to change the one line to const double
TAXRATE=0.08
Safety: Cannot be altered during program
execution Compiled by Dagne Walle 142
Program Style
Indenting:
Separate processes with blank lines
Blank lines are also ignored and are used to increase
readability.
indent statements within statements (loop body)
Comments:
// tells the computer to ignore this line.
for internal documentation. This is done for program
clarity and to facilitate program maintenance.

Compiled by Dagne Walle 143


General rules for Comments
Place a comment at the beginning of every
file with the file name, version number, a
brief program description, programmer’s
name.
Place a descriptive comment after each
variable declared.
Use a blank line before and after variable
declarations
Place a descriptive comment and a blank
line before each subtask.
Compiled by Dagne Walle 144
Hello, World! Explained

The main routine – the start of


every C++ program! It returns
an integer value to the
operating system and (in this
case) takes no arguments:
The return statement returns main()
an integer value to the
operating system after
completion. 0 means “no
error”. C++ programs must
return an integer value. Compiled by Dagne Walle 145
Hello, World! Explained

loads a header file containing function


and class definitions
Loads a namespace called std.
Namespaces are used to separate
sections of code for programmer
convenience. To save typing we’ll
always use this line in this tutorial.

▪ cout is the object that writes to the stdout


device, i.e. the console window.
▪ It is part of the C++ standard library.
▪ Without the “using namespace std;” line this
would have been called as std::cout. It is
defined in the iostream header file.
▪ << is the C++ insertion operator. It is used to
pass characters from the right to the object on
the left. endl is the C++ newline character.
Compiled by Dagne Walle 146
The Compilation Process
Program is created in
Editor Disk
Phases of C++ Programs: the editor and stored
on disk.

Preprocessor Disk Preprocessor program


1. Edit processes the code.
Compiler creates
Compiler Disk object code and stores
2. Preprocess it on disk.
Linker links the object
Linker Disk code with the libraries,
3. Compile Primary
creates a.out and
stores it on disk
Memory
Loader
4. Link
Loader puts program
in memory.
5. Load Disk ..
..
..

Primary
6. Execute CPU
Memory

CPU takes each


instruction and
executes it, possibly
storing new data
..
.. values as the program
..
147 executes.
Compiled by Dagne Walle
The Compilation Process

Compiled by Dagne Walle 148


Opening Code Block and creating a 1st
C++ project…
Step 1. Create a project from the File menu or the
Start Here tab:

Compiled by Dagne Walle 149


Step 2. Choose the Console category and then the
Console application and click Go.

Compiled by Dagne Walle 150


Step 3: Click Next on the “Welcome to the new
console application wizard!” screen.
Step 4: Choose C++!
…then click Next.

Compiled by Dagne Walle 151


Step 5. Enter a project title. If you like you can
change the default folder to hold the project. Click
Next.

Compiled by Dagne Walle 152


Step 6: Choose the compiler, choose GNU GCC as the
compiler. Click Next.

Compiled by Dagne Walle 153


Enable C++11 standard

Step 7.l Right-click on your


project name and choose Build
options

▪ Check off the C++11 option. Click Release


on the left and do the same there as well.
▪ Do this anytime we create a project in Code
Block
Compiled by Dagne Walle 154
Step 8: Your project is now created! Click on
Sources in the left column, then double-click
main.cpp.
Click the icon in the toolbar or press F9 to
compile and run the program.

Compiled by Dagne Walle 155


Hello, World!

Console
window:

Build and compile


Compiled by Dagne Walle 156
messages

You might also like