Chapter One: Problem Solving Using Computers
Chapter One: Problem Solving Using Computers
Simegnew A.
Computer Fundamentals
What is a Computer?
Why Computer?
Speed
Accuracy
Storage Capability
Versatility
Diligence
Automatic
Cont..
What is computer system?
Hardware
Input Devices
Central Processing Unit (CPU)
Output Devices
Storage devices
Primary storage device
Secondary storage device
Software
Application Software
System software
Cont..
Bus
Cont.. .
.
.
.
. .
2000 01001010 Encoding for character ‘J’
2001 01100001 Encoding for character ‘a’
2002 01110110 Encoding for character ‘v’
2003 01100001 Encoding for character ‘a’
2004 00000011 Encoding for number 3
If the system can be engineered using current technology and within budget.
If the system can be integrated with other systems that are used.
Requirement Analysis (Requirement Gathering)
Try to understand the business in general: (activities done, how it is done, etc)
Define the specific information requirements: who needs what information, where, when,
and how
Present a detail description of the functions the new system must perform
In this phase we identify:
Inputs to the problem and their form (Filing status: Single, Married, divorced)
Outputs expected from the solution and their form
Constraints (What are the limits on the data? Income cannot be a negative number)
Assumptions (Problem deals in $US, Only for 2005)
Formulas (For determining the area, it is length x width)
Design
Also known as algorithm design
In this phase we focus on ‚HOW‛ question.
There are different ways of describing of algorithm
Pseudo codes
Structured chart
Flow chart
Implementation
Algorithms cannot be executed (performed) directly by the computer
The process of writing the program
Conversion of algorithm into desired programming language.
Testing
Also called program verification or debugging.
Removing error in the program.
Error in the program is called bug and the process of correcting known error is called
Debugging.
Three types of error: - syntax error, run time error and logical error.
Unit testing (Program testing): Test each unit of program in the system separately
System testing: Test the functions of the system as a whole (performance, capacity for
file storage, recovery and restart capabilities)
Acceptance testing: System is evaluated by users and management
Maintenance
This stage is ongoing throughout the life of the system
Involves correcting faults which are not detected during testing
Fix bugs found by the customer
Make modifications
Add new features
Software Crisis
Let us now focus on the Causes of software crisis:
Due to the Projects running over-budget
Due to the Projects running over-time
Software was very inefficient and was of low quality
Software often did not meet requirements
Code was difficult to maintain and Projects were a mess and
unmanageable
Cont…
There are some solutions for preventing software crisis:
Experience working as a team member on a software development project
Knowledge of basic statics and experimental design
Less time and fewer people needed for productive innovation
Algorithm development
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 mechanically, 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
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 hard notation, since it is read by other people, not by the computer
Pseudocode
Pseudo code can be broken down into five components.
Variables
Assignment
Input/output
Selection
Repetition
Computation/Assignment
set the value of "variable" to :"arithmetic expression" or
"variable" equals "expression" or
"variable" = "expression"
• Input/Output
– get "variable", "variable", ...
display "variable", "variable", ...
• Conditional
– if "condition"
(subordinate) statement 1
etc ...
else
(subordinate) statement 2
etc ...
• Iterative
– while "condition"
(subordinate) statement 1
etc ...
Example
Write a program that obtains two integer numbers from the user. It will print out the
sum of those numbers.
Pseudo code:
Prompt the user to enter the first integer
Prompt the user to enter a second integer
Compute the sum of the two user inputs
Display an output prompt that explains the answer as the sum
Display the result
Example
Write pseudo code that reads two numbers and multiplies them together and print out
their product.
Read num1 , num2
Set multi to num1*num2
Write multi
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
Flowchart symbols
Process Symbol
Arithmetic computations or data movement
Decision Symbol
Yes/No decision to be made by the program
Flowline
Instructions transferring to next step
Start/End Symbol
Represent the start and the end of the program
Input/Output Symbol
Show input or output data
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:
frown False True
Frown Happy? Smile
Selection (continued)
True
Light Slow
Yellow? Down
False
Example
Write the algorithmic description and draw a flow chart to find the following sum.
Algorithmic description
Start
1. Initialize sum to 0 and counter to 1
Sum = 0
1.1 If the counter is less than or equal to 50 Counter = 1
Exit
2. Write sum
Example
A certain company plan to give a 10% bonus to each of its employees at the end of
every year. If an employee has been working 10/more years at the company, she/he is
to get an additional birr 100. Draw a flowchart of an algorithm to calculate and print
the bonus for a given employee.
Chapter Two
Fundamentals of C++ Programming Language
Your readiness to learn:
Your readiness to learn:
Your readiness to learn:
Your readiness to learn:
Programming paradigm…
Unstructured Programming
Procedural programming .
Structured Programming
disadvantages
Complex
if the same statement sequence is needed at different locations
within the program, the sequence must be copied
Procedural programming
based upon the concept of procedure call
A procedure call is used to invoke the procedure
Procedures (routines, subroutines, methods,
functions) simply contain a series of computational
steps to be carried out to solve a problem
We have a single program, which is divided into small
pieces called procedures
Advantage
to re-use the same code at different places in the
program without copying it
easier way to keep track of program flow
Example
FORTRAN, ADA
Structured Programming
is a subset of procedural programming (also known as
modular programming)
procedures of a common functionality are grouped together
into separate modules
Each module can have its own data
allows each module to manage an internal state which is modified
by calls to procedures of this module
top-down design model
map out the overall program structure into separate subsections
Advantage
Reuse
easier to understand and modify
Object Oriented Programming - OOP
• Is a method of implementation in which programs are organized as
cooperative collections of objects
• Data and operations are grouped together
• Each object is capable of receiving messages, processing data, and sending
messages to other objects
• Modeling of the domain as objects so that the implementation naturally
reflects the problem at hand.
History Note
• First programmable computer
• Designed by Charles Babbage
• Began work in 1822
• Not completed in Babbage’s life time
• First programmer
• Ada Augusta, Countess of Lovelace
• Colleague of Babbage
Programming and Problem Solving
Algorithm
A sequence of precise instructions which
leads to a solution
Program
An algorithm expressed in a language the computer
can understand
Program Design
Programming is a creative process
No complete set of rules for creating a program
Syntax errors
Violation of the grammar rules of the language
Discovered by the compiler
Error messages may not always show correct location of
errors
Run-time errors
Error conditions detected by the computer at run-time
Logic errors
Errors in the program’s algorithm
Most difficult to diagnose
Computer does not recognize such an error
Linking
C++ programs are typically created by
linking together one or more OBJ files
one or more libraries
A library is a collection of linkable files
A Linker combines
The object code for the programs we write
and
The object code for the pre-compiled routines
into
The machine language program the CPU can run
Summary
• The steps to create an executable file are
• Create a source code file, with a .CPP extension.
• Compile the source code into a file with the .OBJ extension.
• Link your OBJ file with any needed libraries to produce an executable
program
Program is created in
• Phases of C++ Programs: Editor
the editor and stored
Disk on disk.
1. Edit Preprocesso Disk
Preprocessor program
processes the code.
r
2. Preprocess Compiler Disk
Compiler creates
object code and stores
it on disk.
3. Compile Linker Disk Linker links the object
code with the libraries
4. Link Primary Memory
Loader
5. Load Loader puts program
in memory.
Disk ..
6. Execute
..
..
Primary Memory
CPUtakes each
CPU instruction and
executes it, possibly
storing new data
..
..
values as the program
..
executes.
Showing Sample program
#include <iostream>
executing
Keyboard program Screen
cin cout
cin >> x;
cin >> y;
1. #include <iostream.h>
2. int main()
3. {
4. cout << "Hello World!\n";
5. return 0;
6. }
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>
Common Programming Error
Escape characters
A character preceded by "\"
Indicates “special” character output
Example
"\n"
Cursor moves to beginning of next line on the screen
Common Programming Error
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;
Basic Elements
Five kind of tokens in C++
Comments
Keywords (reserved words)
Identifiers
Literals
Operators
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
Add descriptions of modifications
Example
1 /* Fig. 2.1: fig02_01.cpp
2 Text-printing program. */
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11
Welcome to C++!
Every program should begin with a comment that
describes the purpose of the program, author, date
and time.
Chapter Three
Constants, Variables, data Types and Operators
C++ tokens
Identifiers: Names given to different entries such as variables, structures, and functions
Keywords: Reserved words which have fixed meaning and its meaning cannot be changed
Constants: Are like a variable, except that their value never changes during execution once
defined
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, they are reserved for special purpose
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
Rules for naming C++ identifiers
Identifiers must begin with a letter or underscore( _ ).
No special characters are allowed in identifier naming, only letters,
digits or underscores can be used.
A keyword can’t be an identifier.
White space is not allowed within identifier
It should only be up to 31 characters long
Legal and Illegal Identifiers
Outline
3
4
#include <iostream.h> // allows program to perform input and output
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
CONSTANTS
Constants are treated just like regular variables except that their
values cannot be modified after their definition
There are two simple ways in C++ to define constants
Using #define preprocessor.
Using const keyword
The #define Preprocessor
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
Area.cpp
#include <iostream.h>
int main() {
float Length;
float Width;
// Extract length and width
cout << enter width and length: ";
cin >> Length >> Width;
// Compute and insert the area
float Area = Length * Width;
cout << "Area = " << Area << " = Length "
<< Length << " * Width " << Width <<
endl;
return 0;}
• Write a program that accepts a character from the user and echo it to
the screen.
Operator
A symbol that tells the compiler to perform specific mathematical or
logical manipulations
5 Operators
Arithmetic operators
Assignment operator
Increment/Decrement operators
Relational operators
Logical operators
Arithmetic Operators
Common
Addition +
Subtraction -
Multiplication *
Division /
Mod %
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
Mod
Produces the remainder of the division
Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4
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)
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--
Increment & Decrement Operators (continued)
Assignment operator =
Assigns value on left to variable on right
Example:
int a= 5;
float b= 9.66;
char ch=‘d’;
int m, n, p;
m = n = p = 100;
Assignment Operator
Compound assignment Operator
+=, -=, *=, /=, %=
Compound assignment Operator
Relational Operators
Operator
Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
Relational operators
Logical Operators
• Like the relational operators, logical operators
evaluate to 1 or 0.
Logical operators
Type conversion
• A value in any of the built-in types can be converted
• Called type cast
• Syntax
• (<data – type> )value; or <data – type> (value);
• E.g
• (int) 3.14 // converts 3.14 to an int to give 3
• (long) 3.14 // converts 3.14 to a long to give 3L
• (double) 2 // converts 2 to a double to give 2.0
• (char) 122 // converts 122 to a char whose code is 122
• (unsigned short) 3.14 // gives 3 as an unsigned short
Some times the compiler does the type casting – implicit
type cast
E.g
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d;
Chapter Four
Control Flow Statements
(Selection and Repetition Statements
Introduction
C++ provides different forms of statements for different purposes
Declaration statements
Assignment-like statements
etc
The order in which statements are executed is called flow control
Branching statements:
Specify alternate paths of execution, depending on the outcome of a logical
condition
Loop statements:
specify computations, which need to be repeated until a certain logical
condition is satisfied.
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
Compound/Block Statement
Only "get" one statement per branch
Must use compound statement { } for multiples
Also called a "block" statement
Each block should have block statement
Even if just one statement
Enhances readability
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;
}
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
Example2, when dividing two values, we may want to check that the
denominator is nonzero
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!
Multi way if-else: Display Statements
Multi way if-else Example:
Display
Write Program to find number is Even or Odd using if-else statement
Write a program that accepts a character from the user and:
If the char is number print “the character is a number”
If the char is capital letter print “the character is capital letter”
If the char is small letter print “the character is small letter”
Else “the character is special character”;
to the screen.
The switch Statement
A new statement for controlling multiple branches
Uses controlling expression which returns bool data type (true or
false)
Syntax:
next slide
The switch Statement
The switch Statement in Action
The switch Statement in Action
switch(1) {
case 1 : cout << '1';
case 2 : cout << '2';
}
switch(1) {
case 1 : cout << '1';
break;
case 2 : cout << '2';
break;
}
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"
Equivalent to if statement
switch (expr) {
case c1:
statements // do these if expr == c1
break;
case c2:
statements // do these if expr == c2
break;
case c2: // multiple values can share same statements
case c3:
case c4:
statements // do these if expr == any of c2, c3, or c4 break;
default:
statements // do these if expr != any above}
Equivalent to if statement
if (expr==c1) {
statements
} else if (expr==c2) {
statements
} else if (expr==c2 || expr==c3 || expr==c4) {
Statements
} else {
Statements
}
Loops
A loop is a way of repeating a series of instructions several
times
Two Parts to Repetition
a Body
what needs to be repeated
must be marked off in some fashion like {}
a Control expression
some way to make the repetition stop when desired
Infinite loops not wanted!
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
while Loops Syntax
The while statement (also called the while loop) provides a way of
repeating a statement while a condition holds.
while Loops
First expression (called the loop condition) is evaluated
If the outcome is nonzero then statement (called the loop body) is
executed and the whole process is repeated
Otherwise, the loop is terminated
while Loops Example
Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
while Loops Example2
void main()
{
int sum =0,i=1,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
while (i <= n)
sum += i++;
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
}
do-while Loop Syntax
The do statement (also called do loop) is similar to the while statement,
except that its body is executed first and then the loop condition is
examined.
do-while Loop
First statement is executed and then expression is evaluated.
If the outcome of the latter is nonzero then the whole process is
repeated.
Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop.
It is useful for situations where we need the loop body to be executed at least
once, regardless of the loop condition.
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!
do-while Loop Example2
void main ()
{
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
}
for Loop Syntax
This is the simplest and straight-forward looping construct that has the
following general look:
for(expression1;expression2;expression3)
First expression1 is evaluated. Each time round the loop, expression2 is
int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
Loop Issues
Loop’s condition expression can be ANY boolean expression
Examples:
while (count<3 && done!=0)
{
// Do something
}
for (index=0;index<10 && entry!=-99)
{
// Do something
}
Loop Pitfalls: Misplaced ;
Watch the misplaced ; (semicolon)
Example:
while (response != 0) ;
{
cout << "Enter val: ";
cin >> response;
}
Notice the ";" after the while condition!
Result here: INFINITE LOOP!
Loop Pitfalls: Infinite Loops
Loop condition must evaluate to false at some iteration through loop
If not infinite loop.
Example:
while (1)
{
cout << "Hello ";
}
A perfectly legal C++ loop always infinite!
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
Nested Loops Exercise
Write a program which produces a simple multiplication table of the
following format for integers in the range 1 to 9:
The break and continue Statements
Break
Causes immediate exit from a while, for, do/while or switch
structure
Program execution continues with the first statement after the
structure
Common uses of the break statement:
Escape early from a loop
Skip the remainder of a switch structure
The break and continue Statements
Continue
Skips the remaining statements in the body of a while, for or
do/while structure and proceeds with the next iteration of the
loop
In while and do/while, the loop-continuation test is evaluated
immediately after the continue statement is executed
In the for structure, the increment expression is executed, then
the loop-continuation test is evaluated
The break and continue Statements
Causes an immediate jump to the loop test
int next = 0;
while (true){
cin >> next;
if (next < 0)
break;
if (next % 2!=0) //odd number, don’t print
continue;
cout << next << endl;
}
cout << “negative num so here we are!” << endl;
Chapter Five
Introduction to Arrays and Functions
Arrays
• Array
• Consecutive group of memory locations
• All of which have the same type
• Index
• Position number used to refer to a specific
location/element
• Also called subscript
• Place in square brackets
• Must be positive integer or integer expression
• First element has index zero, last element has index n-1
Properties of an array
• Homogeneous
• Contiguous
• Have random access to any element
• Ordered (numbered from 0 to n-1)
• Number of elements does not change - MUST be a constant when
declared
Declaring Arrays
• When declaring arrays, specify
• Name
• Type of array
• Number of elements
arrayType arrayName[ numberOfElements ];
• Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
• Format similar to regular variables
• Example:
int b[ 100 ], x[ 27 ];
178
Examples Using Arrays
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
• If too many a syntax error is produced
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
179
Array of 12 elements
Arrays (Cont.)
• Examine array c in the figure
• c is the array name
• c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
Declaration of an Array
• The index is also called the subscript
182
Using a named constant
•To avoid such errors, we refer to specific array elements explicitly by their
array name and subscript number (e.g., c[ 6 ] or c[ 7 ]).
Solution to problem
int counter = 0, n[5], total = 0; average = total / 5;
float average; ct= 0;
while (counter < 5) while (ct < 5)
{ {
cout << "enter a number ";
if (n[ct] > average)
cin >> n[counter];
total = total + n[counter]; cout << n[ct];
counter = counter + 1; ct = ct + 1;
} }
Initializing Array
• Initializing an array in a declaration with an initializer list
• Initializer list
• Items enclosed in braces ({})
• Items in list separated by commas
• Example
• int n[] = { 10, 20, 30, 40, 50 };
• Because array size is omitted in the declaration, the
compiler determines the size of the array based on the
size of the initializer list
• Creates a five-element array
• Index values are 0, 1, 2, 3, 4
• Initialized to values 10, 20, 30, 40, 50, respectively
Initializing Array
• If fewer initializers than elements in the array
• Remaining elements are initialized to zero
• Example
• int n[ 10 ] = { 0 };
• Explicitly initializes first element to zero
• Implicitly initializes remaining nine elements to zero
• If more initializers than elements in the array
• Compilation error
Initialization of arrays
• int a[] = {1, 2, 9, 10}; // has 4 elements
• int a[5] = {2, 5, 4, 1, -2, 5}; // error!
• int a[5] = {2, 3}; // rest are zero
• int a[5] = {0}; // all are zero
• can use it with char, float, even bool
Assigning Values to
Individual Array Elements
float temps[5];
int m = 4; // Allocates memory
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
7000 7004 7008 7012 7016
? ? ? ? ?
temps[0] temps[1] temps[2] temps[3] temps[4] 190
Now what values are printed?
float temps[5]; // Allocates memory
int m;
.....
for (m = 4; m >= 0; m--)
{
cout << temps[m] << endl;
}
What is temps[m] + 1 ?
7000 7004 7008 7012 7016
temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
Find next largest element and swap
max = 0;
for (i = 1; i < n-1; i++) // note n-1, not n
{
if (a[max] < a[i])
max = i;
}
temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
put a loop around the general code to repeat
for n-1 passes
for (pass = n-1; pass >= 0; pass --)
{ max = 0;
for (i = 1; i <= pass; i++)
if (a[max] < a[i])
max = i;
temp = a[max];
a[max] = a[pass];
a[pass] = temp;
}
Multidimensional Array
• Multidimensional arrays with two dimensions
• Called two dimensional or 2-D arrays
• Represent tables of values with rows and columns
• Elements referenced with two subscripts ([x][y])
• In general, an array with m rows and n columns is called an m-
by-n array
• E.g.
• int a[5][4]; // row then column
• twenty elements, numbered from [0][0] to [4][3]
• Multidimensional arrays can have more than two dimensions
Two-Dimensional Array
• A two-dimensional array is a collection of components, all
of the same type, structured in two dimensions, (referred
to as rows and columns)
• Individual components are accessed by a pair of indexes
representing the component’s position in each dimension
DataType ArrayName[ConstIntExpr][ConstIntExpr]...;
201
Processing a 2-d array by rows
finding the total for the first row
for (i = 0; i < 5; i++)
total = total + a[0][i];
finding the total for the second row
for (i = 0; i < 5; i++)
total = total + a[1][i];
Processing a 2-d array by rows
total for ALL elements by adding first row, then second row, etc.
total for ALL elements by adding first column, second column, etc.
user-defined
built-in
E.g pow(), sqrt(), cin, etc
Declaration of Functions
Functions must be declared before use
The declaration tells the compiler
The name,
Return type,
Parameters of the function
Three ways
Write your prototype into a file, and then use the #include directive to include it
in your program.
Write the prototype into the file in which your function is used.
Define the function before it is called by any other function.
Function Prototypes
The declaration of a function is called its prototype
Is a statement - it ends with a semicolon
It consists of the function's
return type,
name,
parameter list
Syntax
return_type function_name (type [parameterName1], type
[ParameterName2] ... );
E.g. long Area(int, int);
Or
long Area(int length, int width);
Function Prototypes
• All functions have a return type – default is int
• If the function doesn’t have a return type void will be used
• void is a reserved word
• The function prototype usually placed at the beginning of the
program
• The definition of the prototype must be given
• Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using
#include
Defining a Function
• The definition tells the compiler how the function works.
• Consists of :
• the function header :
• like the function prototype except that the parameters must be named
• there is no terminating semicolon
• its body
• the task of the function
• Syntax
return_type function_name(parameter declarations)
{
declarations;
statements;
}
Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is typically used to exit
the function early
• C++ does not allow nested functions
• The definition of one function cannot be included in the body of another
function
• A function definition must agree in return type and parameter list
with its prototype
Defining a Function
• If the function returns a value, it’s definition should end with a
return statement
• The body of the function is always enclosed in braces, even
when it consists of only one statement
• return keyword
• Returns data, and control goes to function’s caller
• If no data to return, use return;
• Function ends when reaches right brace
• Control goes to caller
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values.
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
} // end main
1 4 9 16 25 36 49 64 81 100
Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<endl;