Algorithms and Computing
Department of Computer Engineering (DCE)College of E&ME
NUST
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– Programs that run on computer, Instructions to command
computer to perform actions and make decisions
Computer Organization
Six logical units of computer1. Input unit
• “Receiving” section
• Obtains information from input devices
– Keyboard, mouse, microphone, scanner,… etc
2. Output unit • “Shipping” section
• Takes information processed by computer
• Places information on output devices
– Screen, printer,… etc
– Information used to control other devices
Computer Organization
Six logical units of computer3. 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
Computer Organization
Six logical units of computer5. 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
• Less expensive per unit than primary memory
Machine Languages, Assembly Languages, and High-level
Languages Three types of computer languages
1. Machine language• Only language computer directly understands• “Natural language” of computer• Defined by hardware design
– Machine-dependent• Generally consist of strings of numbers
– Ultimately 0s and 1s• Instruct computers to perform elementary operations
– One at a time• Cumbersome for humans• Example:
+1300042774+1400593419+1200274027
Machine Languages, Assembly Languages, and High-level
Languages Three types of computer languages
2. Assembly language• English-like abbreviations representing elementary computer
operations
• Clearer to humans
• Incomprehensible to computers
– Translator programs (assemblers)
• Convert to machine language
• Example:
LOAD PURCHASE PRICEADD SALES TAXSTORE RETAIL PRICE
Machine Languages, Assembly Languages, and High-level
Languages Three types of computer languages
3. High-level languages • Similar to everyday English, use common mathematical
notations
• Single statements accomplish substantial tasks
– Assembly language requires many instructions to accomplish simple tasks
• Translator programs (compilers)
– Convert to machine language
• Example:
RETAIL PRICE = PURCHASE PRICE + SALES TAX
History of C and C++
History of C– Evolved from two other programming languages
• BCPL and B
– Dennis Ritchie (Bell Laboratories)• Added data typing, other features
– Development language of UNIX
– Hardware independent• Portable programs
– 1989: ANSI standard
– 1990: ANSI and ISO standard published
History of C and C++
History of C++ – Extension of C
– Early 1980s: Bjarne Stroustrup (Bell Laboratories)
– “Spruces up” C
– Provides capabilities for object-oriented programming• Objects: reusable software components
– Model items in real world
• Object-oriented programs
– Easy to understand, correct and modify
– Hybrid language• C-like style
• Object-oriented style
• Both
C++ Standard Library
Standardized version of C++– United States
• American National Standards Institute (ANSI)
– Worldwide• International Organization for Standardization (ISO)
C++ programs– Built from pieces called classes and functions
C++ standard library– Rich collections of existing classes and functions
“Building block approach” to creating programs– “Software reuse”
Other High-level Languages
FORTRAN – FORmula TRANslator
– 1954-1957: IBM
– Complex mathematical computations• Scientific and engineering applications
COBOL– COmmon Business Oriented Language
– 1959: computer manufacturers, government and industrial computer users
– Precise and efficient manipulation of large amounts of data• Commercial applications
Other High-level Languages
Pascal – Prof. Niklaus Wirth
– Academic use
Basics of a Typical C++ Environment
C++ systems– Program-development environment
– Language
– C++ Standard Library
Basics of a Typical C++ Environment
Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
Loader
PrimaryMemory
Program is created inthe editor and storedon disk.
Preprocessor programprocesses the code.
Loader puts programin memory.
CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.
CompilerCompiler createsobject code and storesit on disk.
Linker links the objectcode with the libraries,Creates an executablefile and stores it on disk
Editor
Preprocessor
Linker
CPU
PrimaryMemory
.
.
.
.
.
.
.
.
.
.
.
.
Disk
Disk
Disk
Disk
Disk
A Simple Program:Printing a Line of Text
Input/output
– cin• Standard input stream
• Normally keyboard
– cout• Standard output stream
• Normally computer screen
A Simple Program:Printing a Line of Text
Comments– Document programs
– Improve program readability
– Ignored by compiler
– Single-line comment• Begin with //
Preprocessor directives– Processed by preprocessor before compiling
– Begin with #
A Simple Program:Printing a Line of Text
Standard output stream object– std::cout– “Connected” to screen
– << • Stream insertion operator
• Value to right (right operand) inserted into output stream
Escape characters– \– Indicates “special” character output
12 // A first program in C++.3 #include <iostream.h>4 5 // function main begins program execution6 int main()7 {8 cout << "Welcome to C++!\n";9 10 return 0; // indicate that program ended successfully11 12 } // end function main
Welcome to C++!
Single-line comments.
Preprocessor directive to include input/output stream header file <iostream>.
Function main appears exactly once in every C++ program..
Function main returns an integer value.Left brace { begins function body.
Corresponding right brace } ends function body.
Statements end with a semicolon ;.
Name cout belongs to namespace std.
Stream insertion operator.
Keyword return is one of several means to exit function; value 0 indicates program terminated successfully.
12 // Printing a line with multiple statements.3 #include <iostream.h>4 5 // function main begins program execution6 int main()7 {8 cout << "Welcome "; 9 cout << "to C++!\n";10 11 return 0; // indicate that program ended successfully12 13 } // end function main
Welcome to C++!
Multiple stream insertion statements produce one line of output.
12 // Printing multiple lines with a single statement3 #include <iostream.h>4 5 // function main begins program execution6 int main()7 {8 cout << "Welcome\nto\n\nC++!\n";9 10 return 0; // indicate that program ended successfully11 12 } // end function main
Welcome
to
C++!
Using newline characters to print on multiple lines.
Another Simple Program:Adding Two Integers
Variables – Location in memory where value can be stored
– Common data types• int - integer numbers• char - characters• double - floating point numbers
– Declare variables with name and data type before useint integer1;
int integer2;
int sum;
– Can declare several variables of same type in one declaration• Comma-separated list
int integer1, integer2, sum;
Another Simple Program:Adding Two Integers
Variables– Variable names
• Valid identifier
– Series of characters (letters, digits, underscores)
– Cannot begin with digit
– Case sensitive
Another Simple Program:Adding Two Integers
Input stream object– >> (stream extraction operator)
• Used with std::cin• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
= (assignment operator)– Assigns value to variable
– Binary operator (two operands)
– Example:sum = variable1 + variable2;
12 // Addition program.3 #include <iostream.h>4 5 // function main begins program execution6 int main()7 {8 int integer1; // first number to be input by user 9 int integer2; // second number to be input by user 10 int sum; // variable in which sum will be stored11 12 cout << "Enter first integer\n"; // prompt13 cin >> integer1; // read an integer14 15 cout << "Enter second integer\n"; // prompt16 cin >> integer2; // read an integer17 18 sum = integer1 + integer2; // assign result to sum19 20 cout << "Sum is " << sum << endl; // print sum21 22 return 0; // indicate that program ended successfully23 24 } // end function main
Declare integer variables.
Use stream extraction operator with standard input stream to obtain user input.
Stream manipulator std::endl outputs a newline, then “flushes output buffer.”
Concatenating, chaining or cascading stream insertion operations.
Enter first integer
45
Enter second integer
72
Sum is 117
Memory Concepts
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 previous value
– Reading variables from memory nondestructive
Memory Concepts
std::cin >> integer1;– Assume user entered 45
std::cin >> integer2;– Assume user entered 72
sum = integer1 + integer2;
integer1 45
integer1 45
integer2 72
integer1 45
integer2 72
sum 117
Arithmetic
Arithmetic calculations– *
• Multiplication
– / • Division
• Integer division truncates remainder– 7 / 5 evaluates to 1
– %• Modulus operator returns remainder
– 7 % 5 evaluates to 2
Arithmetic
Rules of operator precedence– Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
– Multiplication, division, modulus applied next• Operators applied from left to right
– Addition, subtraction applied last• Operators applied from left to rightOperator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Modulus
Evaluated second. If there are several, they re evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Decision Making: Equality and Relational Operators
if structure– Make decision based on truth or falsity of condition
• If condition met, body executed
• Else, body not executed
Equality and relational operators
Decision Making: Equality and Relational Operators
Standard algebraic equality operator or relational operator
C++ equality or relational operator
Example of C++ condition
Meaning of C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
Decision Making: Equality and Relational Operators
if ( x == y )
cout << x << " is equal to " << y << endl;
12 // Using if statements, relational3 // operators, and equality operators.4 #include <iostream.h>5 6 78 9 10 // function main begins program execution11 int main()12 {13 int num1; // first number to be read from user14 int num2; // second number to be read from user15 16 cout << "Enter two integers, and I will tell you\n"17 << "the relationships they satisfy: ";18 cin >> num1 >> num2; // read two integers19 20 if ( num1 == num2 ) 21 cout << num1 << " is equal to " << num2 << endl;22 23 if ( num1 != num2 )24 cout << num1 << " is not equal to " << num2 << endl;25
Can write cout and cin without std:: prefix.
Declare variables.
if structure compares values of num1 and num2 to test for equality.
If condition is true (i.e., values are equal), execute this statement.if structure compares values
of num1 and num2 to test for inequality.
If condition is true (i.e., values are not equal), execute this statement.
26 if ( num1 < num2 )27 cout << num1 << " is less than " << num2 << endl;28 29 if ( num1 > num2 )30 cout << num1 << " is greater than " << num2 << endl;31 32 if ( num1 <= num2 )33 cout << num1 << " is less than or equal to "34 << num2 << endl;35 36 if ( num1 >= num2 )37 cout << num1 << " is greater than or equal to "38 << num2 << endl;39 40 return 0; // indicate that program ended successfully41 42 } // end function main
Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Statements may be split over several lines.
Enter two integers, and I will tell you
the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
Algorithms
Before writing a program– Have a thorough understanding of problem
– Carefully plan your approach for solving it
Algorithms
Computing problems– Solved by executing a series of actions in a specific order
Algorithm a procedure determining– Actions to be executed
– Order to be executed
– Example: recipe
Program control– Specifies the order in which statements are executed
Pseudocode
Pseudocode– Artificial, informal language used to develop algorithms
– Similar to everyday English
Not executed on computers – Used to think out program before coding
• Easy to convert into C++ program
– Only executable statements• No need to declare variables
Control Structures
Sequential execution– Statements executed in order
Transfer of control– Next statement executed not next one in sequence
3 control structures– Sequence structure
• Programs executed sequentially by default
– Selection structures• if, if/else, switch
– Repetition structures• while, do/while, for
Control Structures
Flowchart– Graphical representation of an algorithm
– Special-purpose symbols connected by arrows (flowlines)
– Rectangle symbol (action symbol)• Any type of action
– Oval symbol• Beginning or end of a program
if Selection Structure
Selection structure– Choose among alternative courses of action
– Pseudocode example: If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true• Print statement executed, program continues to next statement
– If the condition is false• Print statement ignored, program continues
– Indenting makes programs easier to read• C++ ignores whitespace characters (tabs, spaces, etc.)
if Selection Structure
Translation into C++If student’s grade is greater than or equal to 60
Print “Passed”
if ( grade >= 60 ) cout << "Passed";
Diamond symbol (decision symbol)– Indicates decision is to be made
– Contains an expression that can be true or false• Test condition, follow path
if Selection Structure
Flowchart of pseudocode statement
true
false
grade >= 60
print “Passed”
if/else Selection Structure
if– Performs action if condition true
if/else– Different actions if conditions true or false
Pseudocodeif student’s grade is greater than or equal to 60
print “Passed”else
print “Failed”
C++ codeif ( grade >= 60 ) cout << "Passed";else cout << "Failed";
Selection Structure
Ternary conditional operator (?:)– Three arguments (condition, value if true, value if false)
Code could be written:cout << ( grade >= 60 ? “Passed” : “Failed” );
truefalse
print “Failed” print “Passed”
grade >= 60
Condition Value if true Value if false
if/else Selection Structure
Nested if/else structures– One inside another, test for multiple cases
– Once condition met, other statements skippedif student’s grade is greater than or equal to 90
Print “A”
else if student’s grade is greater than or equal to 80
Print “B”else
if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or equal to 60 Print “D”
else
Print “F”
if/else Selection Structure
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";
if/else Selection Structure
Compound statement– Set of statements within a pair of braces if ( grade >= 60 )
cout << "Passed.\n";else { cout << "Failed.\n"; cout << "You must take this course again.\n";}
– Without braces,cout << "You must take this course again.\n";
always executed
Block– Set of statements within braces
Even or Odd
int num;cout<<"Enter any number"<<endl;cin>>num;
if(num%2==0)cout<<"The number is even"<<endl;
elsecout<<"The number is odd"<<endl;
Dangling Else Problem
if ( x > 5)
if ( y > 5)
cout << “x and y are > 5”;
else
cout << “x is <= 5”;
Dangling Else Problem
if ( x > 5)
if ( y > 5)
cout << “x and y are > 5”;
else
cout << “x is <= 5”;
Dangling Else Problem
if ( x > 5)
{
if ( y > 5)
cout << “x and y are > 5”;
}
else
cout << “x is <= 5”;
else associated with the first if
Guess Number
#include <iostream.h> #include <cstdlib.h> int main() { int magic; int guess; magic = rand(); // get a random number cout << "Enter your guess: "; cin >> guess; if (guess == magic) { cout << "** Right **\n"; cout << magic << " is the magic number.\n"; } else { cout << "...Sorry, you're wrong."; if(guess > magic) cout <<" Your guess is too high.\n"; else cout << " Your guess is too low.\n"; } return 0; }
while Repetition Structure
Repetition structure– Action repeated while some condition remains true
– Psuedocodewhile there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
Exampleint product = 2;
while ( product <= 1000 )
product = 2 * product;
The while Repetition Structure
Flowchart of while loop
product <= 1000 product = 2 * producttrue
false
Formulating Algorithms (Counter-Controlled Repetition)
Counter-controlled repetition– Loop repeated until counter reaches certain value
Definite repetition– Number of repetitions known
Example A class of ten students took a quiz. The grades (integers in
the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.
Formulating Algorithms (Counter-Controlled Repetition)
Pseudocode for example:Set total to zero
Set grade counter to one
While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter
Set the class average to the total divided by tenPrint the class average
Next: C++ code for this example
12 // Class average program with counter-controlled repetition.3 #include <iostream>4 5678 9 // function main begins program execution10 int main()11 {12 int total; // sum of grades input by user13 int gradeCounter; // number of grade to be entered next14 int grade; // grade value15 int average; // average of grades16 17 // initialization phase18 total = 0; // initialize total19 gradeCounter = 1; // initialize loop counter20
21 // processing phase22 while ( gradeCounter <= 10 ) { // loop 10 times23 cout << "Enter grade: "; // prompt for input24 cin >> grade; // read grade from user25 total = total + grade; // add grade to total26 gradeCounter = gradeCounter + 1; // increment counter27 }28 29 // termination phase30 average = total / 10; // integer division31 32 // display result33 cout << "Class average is " << average << endl; 34 35 return 0; // indicate program ended successfully36 37 } // end function main
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.
Formulating Algorithms (Sentinel-Controlled Repetition)
Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run
– Unknown number of students
– How will program know when to end?
Sentinel value– Indicates “end of data entry”
– Loop ends when sentinel input
– Sentinel chosen so it cannot be confused with regular input • -1 in this case
Formulating Algorithms (Sentinel-Controlled Repetition)
Top-down, stepwise refinement– Begin with pseudocode representation of top
Determine the class average for the quiz
– Divide top into smaller tasks, list in orderInitialize variables
Input, sum and count the quiz grades
Calculate and print the class average
Formulating Algorithms (Sentinel-Controlled Repetition)
Many programs have three phases– Initialization
• Initializes the program variables
– Processing• Input data, adjusts program variables
– Termination• Calculate and print the final results
– Helps break up programs for top-down refinement
Formulating Algorithms (Sentinel-Controlled Repetition)
Refine the initialization phaseInitialize variables
becomes:
Initialize total to zero
Initialize counter to zero
ProcessingInput, sum and count the quiz grades
becomes:
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
Formulating Algorithms (Sentinel-Controlled Repetition)
TerminationCalculate and print the class average
becomes:
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print “No grades were entered”
Next: C++ program
12 // Class average program with sentinel-controlled repetition.3 #include <iostream>4 56789 10 #include <iomanip> // parameterized stream manipulators11 12 using std::setprecision; // sets numeric output precision 13 14 // function main begins program execution15 int main()16 {17 int total; // sum of grades18 int gradeCounter; // number of grades entered19 int grade; // grade value20 21 double average; // number with decimal point for average22 23 // initialization phase24 total = 0; // initialize total25 gradeCounter = 0; // initialize loop counter
Data type double used to represent decimal numbers.
26 27 // processing phase28 // get first grade from user29 cout << "Enter grade, -1 to end: "; // prompt for input30 cin >> grade; // read grade from user31 32 // loop until sentinel value read from user33 while ( grade != -1 ) { 34 total = total + grade; // add grade to total35 gradeCounter = gradeCounter + 1; // increment counter36 37 cout << "Enter grade, -1 to end: "; // prompt for input38 cin >> grade; // read next grade39 40 } // end while41 42 // termination phase43 // if user entered at least one grade ...44 if ( gradeCounter != 0 ) {45 46 // calculate average of all grades entered47 average = static_cast< double >( total ) / gradeCounter;48
static_cast<double>() treats total as a double temporarily (casting).
Required because dividing two integers truncates the remainder.
gradeCounter is an int, but it gets promoted to double.
49 // display average with two digits of precision50 cout << "Class average is " << setprecision( 2 )51 << average << endl;52 53 } // end if part of if/else54 55 else // if no grades were entered, output appropriate message56 cout << "No grades were entered" << endl;57 58 return 0; // indicate program ended successfully59 60 } // end function main
Enter grade, -1 to end: 75
Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
setprecision(2)prints two digits past decimal point (rounded to fit precision).
Programs that use this must include <iomanip>
Nested Control Structures
Problem statement A college has a list of test results (1 = pass, 2 = fail) for 10
students. Write a program that analyzes the results. If more than 8 students pass, print “Hardworking Class”.
Notice that– Program processes 10 results
• Fixed number, use counter-controlled loop
– Two counters can be used• One counts number that passed
• Another counts number that fail
– Each test result is 1 or 2• If not 1, assume 2
Nested Control Structures
Top level outlineAnalyze exam results and decide if class was hardworking
First refinementInitialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if class was hardworking
RefineInitialize variables
becomes:
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
Nested Control Structures
RefineInput the ten quiz grades and count passes and failures
becomes:
While student counter is less than or equal to tenInput the next exam result
If the student passed
Add one to passesElse Add one to failures
Add one to student counter
Nested Control Structures
RefinePrint a summary of the exam results and decide if class was
hardworking
becomes:
Print the number of passes
Print the number of failures
If more than eight students passed Print “Hardworking Class”
Program next
12 // Analysis of examination results.3 #include <iostream>4 5678 9 // function main begins program execution10 int main()11 {12 // initialize variables in declarations13 int passes = 0; // number of passes14 int failures = 0; // number of failures15 int studentCounter = 1; // student counter16 int result; // one exam result17 18 // process 10 students using counter-controlled loop19 while ( studentCounter <= 10 ) {20 21 // prompt user for input and obtain value from user22 cout << "Enter result (1 = pass, 2 = fail): ";23 cin >> result;24
25 // if result 1, increment passes; if/else nested in while26 if ( result == 1 ) // if/else nested in while27 passes = passes + 1; 28 29 else // if result not 1, increment failures 30 failures = failures + 1; 31 32 // increment studentCounter so loop eventually terminates33 studentCounter = studentCounter + 1; 34 35 } // end while36 37 // termination phase; display number of passes and failures38 cout << "Passed " << passes << endl; 39 cout << "Failed " << failures << endl;40 41 // if more than eight students passed, print "raise tuition"42 if ( passes > 8 )43 cout << “Hardworking Class" << endl; 44 45 return 0; // successful termination46 47 } // end function main
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Passed 6
Failed 4
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 2
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Enter result (1 = pass, 2 = fail): 1
Passed 9
Failed 1
Hardworking Class