CPP Slide2
CPP Slide2
11/6/2017 by desalegn w. 3
What is programming language
• an artificial language that can be used to control the behavior of a
computer
• defined by
• Syntactic - describes the possible combinations of symbols that form a
syntactically correct program
• Semantic - The meaning given to a combination of symbols
• Every programming languages have syntax and semantics
• computers do exactly what they are told to do
• Available programming languages come in a variety of forms and
types
• Programming languages can be divided in to two major categories:
• low-level
• high-level languages
11/6/2017 by desalegn w. 4
Programming Languages
• Machine language
• machine is short for computing machine (i.e., computer)
• computer‟s native language, sequence of zeroes and ones (binary)
• different computers understand different sequences
• hard for humans to understand: 01010001…
• Assembly language
• mnemonics for machine language
• low level: each instruction is minimal
• still hard for humans to understand:
ADD d0,d2
• High-level languages
• FORTRAN, Pascal, BASIC, C, C++, Java, etc.
• high level: each instruction composed of many low-level instructions
• closer to English easier to read and understand:
hypotenuse = Math.sqrt(opposite *
opposite + adjacent * adjacent);
11/6/2017 by desalegn w. 5
Interpreting vs. Compiling Programs
• Each type of computer only “understands” its own machine
language (zeroes and ones)
• Thus we must translate from High-level language to machine
language
• a team of experts programs a translator, called a “compiler” which
translates entirety of a High-level language program to an executable file in
computer‟s native machine language.
• Running :
• compilation: Your program executable
• execution: run executable
• machine executes your program by “running” each machine language instruction in the
executable file
11/6/2017 by desalegn w. 6
Interpreting vs. Compiling Programs
• An alternative to compiling your program is to interpret your program
• each line of your program is translated into machine language and immediately
executed
11/6/2017 by desalegn w. 7
Programs vs. Algorithms
• To make a computer do anything, you have to write a program
• To write a computer program, you have to tell the computer, step
by step, exactly what you want it to do.
• The computer then "executes" the program, following each step, to
accomplish the end goal.
• An algorithm is a finite, step-by-step sequence of instructions that
describe how the data is to be processed to produce the desired
outputs
• The algorithm is implemented by a program
11/6/2017 by desalegn w. 8
Control Structures
• programs could be written in terms of 3 structures:
• Sequence – which instruction should be done next?
• Selection – select between options
• Repetition – repeat an action while a given condition stays true
11/6/2017 by desalegn w. 9
Algorithm
• An algorithm can be represented as
• Flowchart
• Pseudocode
Pseudocode
• is an artificial and informal language that helps programmers develop
algorithms
• allows the designer to focus on the logic of the algorithm without
being distracted by details of language syntax
• text-based" detail (algorithmic) design tool
• Pseudocode is not a rigorous notation, since it is read by other people,
not by the computer
11/6/2017 by desalegn w. 10
• Examples:
• Write a program that prints “passed” when the student garde is greater than 60 and
“failed” otherwise.
• If student's grade is greater than or equal to 60
• Print "passed"
• else
• Print "failed“
• Pseudo-code the task of computing the final price of an item after figuring in sales
tax. Note the three types of instructions: input (get), process/calculate (=) and output
(display)
1. get price of item
2. get sales tax rate
3. sales tax = price of time times sales tax rate
4. final prince = price of item plus sales tax
5. display final price
6. stop
• Variables: price of item, sales tax rate, sales tax, final price
11/6/2017 by desalegn w. 11
Flow Chart
• A graphic representation of an algorithm, often used in
the design phase of programming to work out the logical
flow of a program
11/6/2017 by desalegn w. 12
Sequence
11/6/2017 by desalegn w. 13
Selection
True
• Single Selection (if) Won Raise
lottery? Hand
• If you‟ve won the lottery:
raise your hand False
• Double Selection (if-else)
• If you‟re happy:
smile
else:
cry False True
cry Happy? Smile
11/6/2017 by desalegn w. 14
Selection (continued)
• Multiple Selection (switch)
If the light is ... Light True
Red? Stop
red -> stop
False
green -> go True
Light
Green? Go
yellow -> slow down False
True
Light Slow
Yellow? Down
False
11/6/2017 by desalegn w. 15
Repetition
• While
True while it’s still clumpy
Mixture
Stir Stir the mixture
Clumpy?
False
11/6/2017 by desalegn w. 16
Repetition (continued)
• For
Teaching a baby to count
Counter = 1
from 1 to 10:
counter = 1
Add 1
to counter if counter <= 10:
increment counter
CounterTrue
Print print counter number
≤ 10?
counter
False
11/6/2017 by desalegn w. 17
Variables
• Location in memory where value can be stored
• All variables have two important attributes
• A type - Once defined, the type of a C++ variable cannot be
changed
• A value - can be changed by assigning a new value
• E.g. int a = 5;
• Type integer
• Value 5
11/6/2017 by desalegn w. 18
Variable Declaration
• defining (creating) a variable
• Two parts
• Variable name - unique name of the memory location
• Data type (or type) - defines what kind of values the variable
can hold
• Syntax
• <type> <Var-idf>;
• E.g.
• double varTime;
• int myAge;
• Can declare several variables of same type in one
declaration
• Comma-separated list
• int integer1, integer2, sum;
• Variables must be declared before used
11/6/2017 by desalegn w. 19
Variable assignment
• Variable names
• Valid identifier
• Series of characters (letters, digits, underscores)
• Cannot begin with digit
• Case sensitive
• Assignment operator =
• Assigns value on left to variable on right
• Binary operator (two operands)
• Example:
• sum = variable1 + variable2;
• Add the values of variable1 and variable2
• Store result in sum
11/6/2017 by desalegn w. 20
Variables and Memory Concept
• Variable names
• Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
• When new value placed into variable, overwrites old value
• Writing to memory is destructive
• Reading variables from memory nondestructive
• Example
• int number1= 45;
• int number2= 72;
• int sum = 0;
• sum = number1 + number2;
• Value of sum is overwritten
• Values of number1 and number2 remain intact
11/6/2017 by desalegn w. 21
Memory locations after calculating and
storing the sum of number1 and number2.
11/6/2017 by desalegn w. 22
Data Types
• When you define a variable in C++, you must tell the compiler
what kind of variable it is
• Tell the data type
• Pointers
11/6/2017 by desalegn w. 23
Simple Data Types
• Three categories of simple data
• Integral: integers (numbers without a decimal)
11/6/2017 by desalegn w. 24
Type Size Values
unsigned short int 2 bytes 0 to 65,535
11/6/2017 by desalegn w. 27
Simple Data Types
• Type char
• used to represent character data
• a single character which includes a space
• 1 byte, enough to hold 256 values
• must be enclosed in single quotes eg. „d‟
• Escape sequences treated as single char
• „\n‟ newline
• „\‟‟ apostrophe
• „\”‟ double quote
• „\t‟ tab
• (0-255) or as a member of the ASCII set
• E.g. the lowercase letter "a" is assigned the value 97
11/6/2017 by desalegn w. 28
Simple Data Types
• Strings
• used to represent textual information
• string constants must be enclosed in double quotation marks eg.
“Hello world!”
• empty string “”
• new line char or string “\n”
• “the word \”hello\”” (puts quotes around “hello” )
• String variables use:
#include “apstring.cpp”
• use quotes for user supplied libraries
11/6/2017 by desalegn w. 29
Operator
• symbols that take one or more arguments (operands) and
operates on them to produce a result
• A unary operator requires one operand.
• A binary operator requires two operands.
• A tertiary operator requires three operands.
• 5 Operators
• Arithmetic operators
• Assignment operator
• Increment/Decrement operators
• Relational operators
• Logical operators
11/6/2017 by desalegn w. 30
Arithmetic Operators
• Common
• Addition +
• Subtraction -
• Multiplication *
• Division /
• Mod %
• Note
• No exponentiation operator
• Single division operator
• Operators are overloaded to work with more than one type of object
11/6/2017 by desalegn w. 31
Integer Division
• Integer division produces an integer result
• Truncates the result
• Examples
• 3 / 2 evaluates to 1
• 4 / 6 evaluates to 0
• 10 / 3 evaluates to 3
11/6/2017 by desalegn w. 32
Mod
• Produces the remainder of the division
• Examples
• 5 % 2 evaluates to 1
• 12 % 4 evaluates to 0
• 4 % 5 evaluates to 4
11/6/2017 by desalegn w. 33
Arithmetic Operators and Precedence
• Consider m*x + b which of the following is it equivalent
to
• (m * x) + b
• m * (x + b)
• Operator precedence tells how to evaluate expressions
• Examples
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
11/6/2017 by desalegn w. 35
Increment & Decrement Operators
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
• Pre-increment: ++variable
• Post-increment: variable++
• Pre-decrement: --variable
• Post-decrement: variable--
11/6/2017 by desalegn w. 36
Increment & Decrement Operators
(continued)
• ++count; or count++; increments the value of count by 1
• --count; or count--; decrements the value of count by 1
• If x = 5; and y = ++x;
• After the second statement both x and y are 6
• If x = 5; and y = x++;
• After the second statement y is 5 and x is 6
11/6/2017 by desalegn w. 37
Assignment Operator
• Assignment operator =
• Assigns value on left to variable on right
• Binary operator (two operands)
• Example:
• int a= 5;
• float b= 9.66;
• char ch=„d‟;
• int m, n, p;
• m = n = p = 100;
11/6/2017 by desalegn w. 38
Relational Operators
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or 5 <= 5 // gives 1
Equal
> Greater Than 5 > 5.5 // gives 0
>=
Greater Than 6.3 >= 5 // gives 1
or Equal
Relational operators
11/6/2017 by desalegn w. 39
Logical Operators
• Like the relational operators, logical operators
evaluate to 1 or 0.
Logical operators
11/6/2017 by desalegn w. 40
Basic Input/Output
cin standard input stream
cout standard output stream
11/6/2017 by desalegn w. 41
First Program in C++
1. #include <iostream.h>
2. int main()
3. {
4. cout << "Hello World!\n";
5. return 0;
6. }
11/6/2017 by desalegn w. 42
First Program in C++: Printing a Line
of Text (Cont.)
• Preprocessor directives
• Processed by preprocessor before compiling
• Begin with #
• Example
• #include <iostream>
• Tells preprocessor to include the input/output stream header
file <iostream>
• White space
• Blank lines, space characters and tabs
• Used to make programs easier to read
• Ignored by the compiler
11/6/2017 by desalegn w. 43
First Program in C++: Printing a Line of Text
(Cont.)
• Function main
• A part of every C++ program
• Exactly one function in a program must be main
• what will be executed when you run your program
• “main” is function where execution starts
• Can “return” a value
• Example
• int main()
• This main function returns an integer (whole number)
• Body is delimited by braces ({})
• Statements
• Instruct the program to perform an action
• All statements end with a semicolon (;)
11/6/2017 by desalegn w. 44
First Program in C++: Printing a Line of Text
(Cont.)
• Stream insertion operator <<
• Value to right (right operand) inserted into left operand
• Example
• cout << "Hello World!\n";
• Inserts the string " "Hello World!” " into the standard output
• Displays to the screen
• Escape characters
• A character preceded by "\"
• Indicates “special” character output
• Example
• "\n"
11/6/2017
• Cursor moves to beginning of next line on the screen
by desalegn w. 45
First Program in C++: Printing a Line of Text
(Cont.)
• return statement
• One of several means to exit a function
• When used at the end of main
• The value 0 indicates the program terminated successfully
• Example
• return 0;
11/6/2017 by desalegn w. 46
Basic Elements
• Five kind of tokens in C++
• Comments
• Keywords (reserved words)
• Identifiers
• Literals
• Operators
11/6/2017 by desalegn w. 47
Comments
• Remark about programs
• Explain programs to other programmers
• Improve program readability
• Ignored by compiler
• Two types
• Single-line comment
• Begin with //
• Example
• // This is a text-printing program.
• Multi-line comment
• Start with /*
• End with */
• Typical uses
• Identify program and who wrote it
• Record when program was written
11/6/2017• Add descriptions of modifications by desalegn w. 48
Keywords (reserved words)
• Words with special meaning to the compiler
• Have a predefined meaning that can‟t be changed
• All reserved words are in lower-case letters
• Must not be used for any other purposes
• Example
• and , auto, bool, break, char, const, default, delete ,do,
double, else, for, friend, new
11/6/2017 by desalegn w. 49
Identifiers
• Programmer given names
• Identify classes, variables, functions, etc.
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
• Not be a reserved word
• C++ is case sensitive
• Some predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may be redefined, but it is
not a good idea
11/6/2017 by desalegn w. 50
Legal and Illegal Identifiers
• The following are legal identifiers in C++:
• first
• conversion
• payRate
11/6/2017 by desalegn w. 51
if-else Statement Syntax
• Formal syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
• Note each alternative is only
ONE statement!
• To have multiple statements execute in
either branch use compound statement
11/6/2017 by desalegn w. 52
Compound Statement in Action
• Note indenting in this example:
if (myScore > yourScore)
{
cout << "I win!\n";
wager = wager + 100;
}
else
{
cout << "I wish these were golf scores.\n";
wager = 0;
}
11/6/2017 by desalegn w. 53
The Optional else
• else clause is optional
• If, in the false branch (else), you want "nothing" to happen, leave it out
• Example:
if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;
• Note: nothing to do for false condition, so there is no else clause!
• Execution continues with cout statement
11/6/2017 by desalegn w. 54
Nested Statements
• if-else statements contain smaller statements
• Compound or simple statements (we‟ve seen)
• Can also contain any statement at all, including another if-else stmt!
• Example:
if (speed > 55)
if (speed > 80)
cout << "You‟re really speeding!";
else
cout << "You‟re speeding.";
• Note proper indenting!
11/6/2017 by desalegn w. 55
Multiway if-else: Display
• Not new, just different indenting
• Avoids "excessive" indenting
• Syntax:
11/6/2017 by desalegn w. 56
Multiway if-else Example: Display
11/6/2017 by desalegn w. 57
The switch Statement
• A new statement for controlling
multiple branches
• Uses controlling expression which returns bool data type (true or
false)
• Syntax:
• next slide
11/6/2017 by desalegn w. 58
switch Statement Syntax
11/6/2017 by desalegn w. 59
The switch Statement in Action
11/6/2017 by desalegn w. 60
The switch: multiple case labels
• Execution "falls thru" until break
• switch provides a "point of entry"
• Example:
case "A":
case "a":
cout << "Excellent: you got an "A"!\n";
break;
case "B":
case "b":
cout << "Good: you got a "B"!\n";
break;
• Note multiple labels provide same "entry"
11/6/2017 by desalegn w. 61
switch Menu Example
• Switch statement "perfect" for menus:
switch (response)
{
case "1":
// Execute menu option 1
break;
case "2":
// Execute menu option 2
break;
case 3":
// Execute menu option 3
break;
default:
cout << "Please enter valid response.";
}
11/6/2017 by desalegn w. 62
Conditional Operator
• Also called "ternary operator"
• Allows embedded conditional in expression
• Essentially "shorthand if-else" operator
• Example:
if (n1 > n2)
max = n1;
else
max = n2;
• Can be written:
max = (n1 > n2) ? N1 : n2;
• "?" and ":" form this "ternary" operator
11/6/2017 by desalegn w. 63
Loops
• 3 Types of loops in C++
• while
• Most flexible
• No "restrictions"
• do -while
• Least flexible
• Always executes loop body at least once
• for
• Natural "counting" loop
11/6/2017 by desalegn w. 64
while Loops Syntax
11/6/2017 by desalegn w. 65
while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
• Loop body executes how many times?
11/6/2017 by desalegn w. 66
do-while Loop Syntax
11/6/2017 by desalegn w. 67
do-while Loop Example
• count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
• Loop body executes how many times?
• do-while loops always execute body at least once!
11/6/2017 by desalegn w. 68
while vs. do-while
• Very similar, but…
• One important difference
• Issue is "WHEN" boolean expression is checked
• while: checks BEFORE body is executed
• do-while: checked AFTER body is executed
• After this difference, they‟re
essentially identical!
• while is more common, due to it‟s
ultimate "flexibility"
11/6/2017 by desalegn w. 69
for Loop Syntax
for (Init_Action; Bool_Exp; Update_Action)
Body_Statement
• Example
• for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
• How many times does loop body execute?
11/6/2017 by desalegn w. 70
The break and continue Statements
• Flow of Control
• Recall how loops provide "graceful" and clear flow of control in
and out
• In RARE instances, can alter natural flow
• break;
• Forces loop to exit immediately.
• continue;
• Skips rest of loop body
• These statements violate natural flow
• Only used when absolutely necessary!
11/6/2017 by desalegn w. 71
Nested Loops
• Recall: ANY valid C++ statements can be inside body of loop
• This includes additional loop statements!
• Called "nested loops"
• Requires careful indenting:
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;
• Notice no { } since each body is one statement
• Good style dictates we use { } anyway
11/6/2017 by desalegn w. 72