CPSC 230 Computers and Programming I
description
Transcript of CPSC 230 Computers and Programming I
CPSC 230Computers and Programming I
Fall 2004Dr. Lynn Lambert
This course will teach you: C++ Object-oriented concepts Programming Some stabs at problem solving
How computers work Computers understand machine
language only Each computer has its own
language All computer languages are in
binary (1s and 0s) No computer understands English,
Powerpoint, or C++
A computer program: Add X to Y and store in Z
In machine language: 01040100 (already simplified to decimal)
01050160 04040506 02060180
HUH!?
Assembly
Each machine instruction has matching, more English-like assembler:
Load X (was: 01040100) Load Y (was: 01050160) Add X Y Z (was: 04040506) Store Z (was: 02060180)Better, but … all this for one addition!?
C++
z=x+y;
Much better!
BUT, no machines understand source code. Only machine code.
Designing a Program1. Decide the problem to solve.
2. Design the solution!!!!!! 3. Translate design to C++4. Type the C++ program (source code) using
an editor (emacs): program.cc5. Compile (g++). Translates C++ into
machine language (object, machine, executable code)
6. Link (g++). Creates executable. Can be done with step 5 or separately.
7. Run the program (after 1-6).
At each step:
1. Think
2. Do
3. Debug
4. Test
Write a program to calculate the volume of a sphere Problem well-defined Design solution:
Read radius Calculate volume: V = 4/3r3
Print answer
Extreme Programming Also called Agile Programming,
Agile Methods Goal is to produce easily
modifiable, reliable code that corresponds to user wants
Pairs programming, tests created before program is written
Test for volume program Radius input: 2.0 // nice normal test
Answer should be: 33.5 Radius input: 2 // testing integer input
Answer should be: 33.5 Radius input: 0 // ALWAYS test for 0
Answer should be: 0 Others tests: negative, large, small,
etc.
C++ Program#include <iostream> // allows reading in and out
using namespace std; // standard namespace
int main() { float radius; // radius of a sphere float volume; // volume of sphere; float is decimal.// other types are int, char, bool, double
const float mypi = 3.14159; // const values cannot be changed // M_PI also defined in cmathcout << “This program calculates the
volume “ << “of a sphere given its radius.”
<< endl;// lots of other ways to do this cout. cout << “Enter the radius> “;cin >> radius;
// volume = 4/3 r3
try 1: volume = 4/3 M_PI r …? 3?try 2: volume = 4 / 3 * M_PI * r * r;try 2.b: volume = 4/3 * M_PI * pow(r, 3); // pow is in cmathcout << "The volume of a sphere with
radius ";cout << radius << " is " << volume <<
endl;return EXIT_SUCCESS; // in <cstdlib>}
Now, let’s do it
great. except it doesn't work.
int + int is int float + float is float
int - int is int float - float is float
int * int is int float * float is float
int / int is int float / float is float
Class Work
Write a program that converts a user entered number of inches to the equivalent number of centimeters (1 inch = 2.54 centimeters).
Work with your partner. Write an algorithm first Write the tests next (input value for what
variable, why this test, expected answer)
Gradually convert the algorithm to C++
FunctionsChapter 3
(modified from Deitel & Deitel web page)
Why functions? divide and conquer repeatable. reuse reliable code encapsulated
Program Components in C++
Modules: functions and classes Programs use new and “prepackaged”
modules New: programmer-defined functions, classes Prepackaged: from the standard library
Functions invoked by function call Function name and information
(arguments/parameters) it needs Function definitions
Only written once
Program Components in C++
Boss to worker analogy A boss (the calling function or caller)
asks a worker (the called function) to perform a task and return (i.e., report back) the results when the task is done
Library Functions Functions called by writing
functionName(argument1, argument2, …);
Perform common mathematical calculations Include the header file <cmath> Call the appropriate function
Library Functions Examplevolume = 4.0 / 3.0 * M_PI * pow(r, 3); pow (exponentiation) function returns
baseexponent (pow(2,3) would return 8) Other math functions listed on p. 173
of text All functions in math library return a double
Parameters/Arguments Function arguments can be
Constants sqrt( 4 );
Variables sqrt( x );
Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x );
Header Files Header files contain
Function prototypes Definitions of data types and
constants Header files ending with .h
Programmer-defined header files#include “myheader.h”
Library header files#include <cmath>
Other libraries Perform string operations, include
<string> Perform character manipulations,
include <cctype> file handling, <fstream> standard constants and routines
<cstdlib> Lots of others
To find a function or library Look in your textbook Ask your partner/class mates Ask me Look on google (or other search
engine) Look on google groups
Writing your own functions
To call a function, you need: Function call – invokes function execution done
To write your own function, you need: Function call (e.g., pow, sqrt). We know
this. Function prototype (shown in function libraries,
like <cmath> -- contains interface information) Function definition– contains the C++ that
defines how that function will be executed (e.g., main). Really, we know this.
Function call Calling/invoking a function
Tells C++ to go do function. If never called, never performed
nothing new. No change in how library functions, your functions are called
After finished, passes back result. Calling function can store or use result
x = pow(2, 3); cout << pow(2, 3);
Function Call Syntax
nameoffunction(arg1, arg2, …) square(x); Parentheses an operator used to call
function Pass argument x Function gets its own copy of arguments
Write a function call that prints the result of sqrt of 4. Discuss with 2 others.
Function definition Format for function definition
return-value-type function-name( parameter-list ){ declarations and statements}
Parameter list Comma separated list of arguments
Data type needed for each argument If no arguments, use void or leave blank
Return-value-type Data type of result returned (use void if nothing
returned)
Function definition Example function
int square( int y )
{
return y * y;
}
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
Functions cannot be defined inside other functions
You try Write a function definition, sum3,
that returns the sum of 3 integers.
Function Prototypes Purpose
Tells compiler argument(s) type and return type of function
int square( int ); Function takes an int and returns an int
Syntax Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if definition after function call semicolon (unlike header in function definition)
Function Prototypes Prototype must match function
header Function prototype
int sqr(int); Function Header in Function Definition
int sqr(int y){ …}
Write a function prototype for sum3
// Fig. 3.3: fig03_03.cpp. But modified from code in book// Creating and using a programmer-defined function.#include <iostream>#include <cstdlib> using namespace std; // modified from code in book int square( int ); // function prototype int main() { int number; // Ask user for number square then square that number cout << “This program calculates the square of an integer.”
<< endl; cout << “Enter a number> “; cin >> number; // next line is function call cout << number << “ squared is “ << square(number) << endl; return EXIT_SUCCESS; // indicates successful termination} // end main
Function call.: Parentheses () cause function to be called. When done, it returns the result.
Function prototype: specifies data types of arguments and return values. square expects and int, and returns an int.
function header: return typefunction name, parameter list.
function body: C++ statements in between {}s.
// this continues program begun on previous slide// square function definition returns // square of an integer int square( int y ) // y is a copy of argument to function{ return y * y; // returns square of y as an int } // end function square
OR
int square(int nbr){ int answer; answer = nbr * nbr; return answer;}
void Empty parameter lists
void or leave parameter list empty Indicates function takes no arguments Function print takes no arguments
and returns no value void print(); void print( void );
print function example Prototype
void printinfo(void); Function call
int main (){ ... printinfo(); …}
print function example cont'd function definition
void printinfo(){ cout << "this program calculates";
cout << " the area of a sphere"; cout << endl;}
void can be anywhere or nowhere
Return type OR argument list OR both or neither can be void
void printint(int x) int getint() void printinstructions() int square(int x)
Function overloading Function overloading
Functions with same name and different parameters
Should perform similar tasks i.e., function to square ints and function to
square floatsint square( int x) {return x * x;}
float square(float x) { return x * x; }
Similar to overloaded +, /, etc. operators
Function overloading cont'd Overloaded functions distinguished
by signature Based on position, number, and type of
parameters (order of parameters matters)
Name mangling Encodes function identifier with parameters
Type-safe linkage Ensures proper overloaded function called
// Fig. 3.25: fig03_25.cpp2 // Using overloaded functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 // function square for int values 9 int square( int x ) 10 { 11 cout << "Called square with int argument: " << x << endl;12 return x * x; 13 14 } // end int version of function square 15 16 // function square for double values 17 double square( double y ) 18 { 19 cout << "Called square with double argument: " << y << endl;20 return y * y; 21 } // end double version of function square 23
24 int main()25 {26 int intResult = square( 7 ); // int version called27 double doubleResult;28 doubleResult = square( 7.5 ); // calls double version29 cout << "\nThe square of integer 7 is " << intResult30 << "\nThe square of double 7.5 is " 31 << doubleResult << endl; 32 33 return 0; // indicates successful termination34 35 } // end main
Called square with int argument: 7Called square with double argument: 7.5 The square of integer 7 is 49The square of double 7.5 is 56.25
Class Work With your partner, write a program
that calculates the volume of a sphere, and uses a function calcspherevolume.
Talk to your neighbors Use the book Use your notes
If Statements
Sections 1.25, 2.4-2.6
Control Structures All code thus far executes every
line of code sequentially We want to be able to repeat, to
choose some lines of code Three types of control: sequence,
conditional, repetition/iteration
Types of control structures Sequence – default in C++,
execute each instruction sequentially as it reached
Conditional – choose whether to execute some C++ statement (if, if -else switch)
Iteration – loop. Repeat some set of statements multiple times
Conditional Choose which statement to execute. Form: if (some condition is true), then do some action If (comparison) then (action) Many examples in English:
If raining, wear raincoat. If cold, wear winter coat.
When in Rome, do as the Romans (if in Rome, act like a Roman)
Conditionals in C++ If (comparison) then (action) Need a way to write the
comparison and the action Comparison is boolean expression
(evaluates to be true or false) Action is any (series of) C++
statements
ComparisonsBoolean expressions can have many
different forms: Using bool variables
bool shoulddoif=true; if (shoulddoif) // then do some action
Relational expression (compares values) Logical Expression (manipulates values
with and, or, not) Can be combined
Relational Operators
int x, y; x < y x <= y x > y x >= y x != y x == y // NOT x=y
Evaluating Boolean Expressions
true, false
0 is false Non-zero is true int x=3;
x is true. sometimes useful, but can cause problems
x=3 is NOT comparing x and 3.
Evaluating Boolean Expressions
int x=3; int y = 4; int z=5;
x < yx < y < zx = yy == 4z >= xx != 3(x + 4) < (y - 1)
truetrue, but tricky x is now 4, 4 is nonzero, so this
is true
truetruefalse7 < 3 false
Logical Operators and (&&, single & very different)
both values must be true for the expression to be true
if it is cold and rainy, wear your winter raincoat (if either isn't true, don't)
or (|| - on keyboard, called pipe symbol) either value can be true if it is cold or rainy, wear a coat (if one is true, do)
not (!) changes the truth value of the expression if it is not cold, do not wear a winter coat
Logical Operators
int x=3; int y=10;(x < y) && (y < 20)
(x == 3) || (y == 3)
x < y; 3 < 10; truey < 20; 10 < 20; truetrue && true is truex == 3 true.short circuit
evaluation(y==3 falsetrue || false is true)
More logical operators
int x=3; int y=10;!(y=10)
(x != 3) || (y != 3)
trick questiony=10 is 10 (true); !true is falsefalsex != 3 falsey != 3 truefalse || true is true
Yet more logical operators
int x=3; int y=10;!((x+1 < 4) ||(y <= 10))
!((x+1 < 4) &&(y <= 10))
x+1 = 44 < 4 false.keep
goingy <= 10 truefalse || true true! true is false4 < 4 false. DONE
with &&. Do not look at y <=10.
!false true
if statements if statement form:
if (boolean expression) c++ statement
if (x < y) cout << "x < y" << endl;
if statements cautions MUST have ()s around boolean
expression no syntax error for non-boolean like
expressions only ONE statement in an if
statement no ';' after if condition Make sure you account for values
that are equal
Your turn Write an if statement to assign x to
y if x is greater than y Discuss with 2 others
if-else If you want to do one thing if a condition is
true and something else if not, use if-else. form: if (condition)
C++ statement else C++ statement
if (x < y) cout << x << " is less than the other number"; else cout << y << " is less than the other number";
> one statement in an ifIf you want to have more than one statement
inside an if or an else, use {}s:if (x < y) { cout << x << " is less than the other number";
x = 0; } else { cout << y << " is less than the other number";
y = 0; }
If-else cautions either if clause or else clause or
both may have {}s. After statements inside if and else
clause are executed, control passes back to next sequential statement
no ';' after else Make sure you account for values
that are equal
Watch Out
if (3 < 4) x = 3;else cout << "3 < 4 is false" << endl; x = 0;cout << "the value of x is " << x <<
endl;
Embedded ifs If statements and if-else
statements may be embedded (if within if). simply evaluate them as the C++ code is executed:
if-else example is most common. sets up a table of conditions
Embedded if-else
F<60
D60-69
C70-79
B80-89
A>90
GradeAverage
Embedded if-else for tableif (ave >= 90) grade = 'A';else if ((ave < 90) && (ave >= 80)) // note: need ()s around entire condition grade = 'B'; else if ((ave < 80) && (ave >=70)) grade = 'C';else if ((ave < 70) && (ave >=60)) grade = 'D';else if ((ave < 70) && (ave < 60)) grade = 'F';
Tracing through the embeded if
Fixing the embedded ifif (ave >= 90) grade = 'A';else if (ave >= 80)// We know (ave < 90) or we wouldn't be
here grade = 'B'; else if (ave >=70) // we know ave < 80 grade = 'C';else if (ave >=60) grade = 'D';else // if ((ave < 70) && (ave < 60)) grade = 'F';
Cautions for embedded ifs Don't use redundant comparisons Make sure you check for values
that are equal Account for out of range values
Program style Put {}s on a line by themselves indent {}s 2-3 spaces, statements
one more than that All code outside if statements
should line up All code inside of if statements
should line up.
More complicated embedded ifsif (x < 3) if (y < 6) cout << "x and y between 3 and 6"; else cout << "x < 3; y >= 6";else if (y > 6) cout << "x and y not in 3-6 range"; else cout << "x >= 3; y <= 6";
You do it Writing if statements (on the same
paper you used earlier)
Loops
2.7-2.20
Repetition/Iteration Do some (series of) actions as long
as some condition exists “drive until you see a stop sign”
action repeated: drive condition: seeing a stop sign
Two parts of a loop: when to stop, what to repeat
Parts of a loop Condition: tells loop when to stop.
Critical that loop stops. Repeated actions: reason for doing
loop Update condition inside loop (get
closer to loop stopping eventually) Initialization: what is necessary to
do before loop is entered
Writing Loops
Answer the questions: What is the condition that will end the
loop? What actions should be repeated How can I update the condition inside
the loop so that it will stop eventually? What variables do I need to initialize
before the loop begins?
Ending Loops when program is running
ctrl-c end input/outputctrl-d end of filectrl-z stop job
Loops in C++ while do-while for
All loops can be written using only the while statement.
while statementwhile (condition)
action;usually:while (condition) { action; }Semantics: as long as condition is true, go
into loop, do series of actions, then go back up and check condition
C++ while
while (condition){ … C++ statements; ….
}
condition is boolean expression we know about
C++ statements we know about
while cautions could execute loop 0 times make sure loop stops all the same cautions as ifs
must have ()s no ; after () watch for expressions inside condition
that are not intended to be boolean expressions (especially = vs ==)
Sample while Sum the numbers 1-3 Do it the same way you would,
with an accumulator
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
1 ??
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
1 0
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3 is
" << sum << endl;
// count <= 3 is true, so go into loop
Sum numbers 1-3
1 0
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
1 0+1=1
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
1+1=2 1
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3 is
" << sum << endl;
// count <= 3 is true, so go into loop
Sum numbers 1-3
2 1
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
2 1+2=3
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
2+1=3 3
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3 is
" << sum << endl;
// count <= 3 is true, so go into loop
Sum numbers 1-3
3 3
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; } cout << "The sum of integers from 1 to
3 is " << sum << endl;
Sum numbers 1-3
3 3+3=6
count sum
count = 1;sum = 0; while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3
is " << sum << endl;
Sum numbers 1-3
3+1=4 6
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3 is
" << sum << endl;
// count <= 3 is false, so skip loop
Sum numbers 1-3
4 6
count sum
count = 1;sum = 0;while (count <= 3) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to 3 is
" << sum << endl;
The sum of integers from 1 to 3 is 6.
Sum numbers 1-3
4 6
count sum
Modify loop so it goes n timescount = 1;cout << "Enter an integer I should sum to> :";cin >> n;sum = 0;while (count <= n) {sum = sum + count; count = count + 1; }cout << "The sum of integers from 1 to " << n
<< " is " << sum << endl;
many common kinds of loops Count controlled – know how many time
you go through loop before you enter (not before you run the program)
validation – keep going until user enters a valid value
sentinel – keep going until a stopping value is reached
event-controlled – general. keep going until some event occurs.
Template for Count ControlledMemorize the templates
Init counter to 0 while (count < n) // n is number of times through loop { // all actions in loop count = count + 1; }
Count-controlled loop hints often implemented as a for
statement init counter before entering loop increment counter as the last
statement in the loop comparison is <= if count starts at
1 and < if count starts at 0.
Write a loop to get answer to A/B/C question
answer = 'P';while ((answer != 'A') && (answer != 'B') &&
(answer != 'C')) { cout << "Enter your answer (must be " << "A, B, or C> "; cin >> answer; answer = toupper(answer); //in <cctype> }
Another ABC versioncout << "Enter your answer ";cout << "(please enter A, B, or C)> ";cin >> answer; // if A, B, or C, loop is skippedanswer = toupper(answer); // help user somewhile ((answer != 'A') && (answer != 'B') &&
(answer != 'C')) { cout << " Your answer must be an A, " << "B, or C. Please enter again> "; cin >> answer; answer = toupper(answer); // in <cctype> }
Validation loop templatecout << "Enter a value> ";cin >> value;// vv1 .. vvn are all of the valid valueswhile ((value != vv1) && … (value != vvn)) {cout << "Your entry is invalid."; cout << "Enter a " << vv1 << ", " << … << "vvn> "; cin >> value; }
Validation loop hints prompt and cin immediately before
loop (or initialize to invalid value)
condition is (value != okvalue) && (value != otherokvalue) … put prompt and cin immediately
before condition is checked (at bottom of loop)
hints for writing loops Determine what kind of loop Write the template for that kind of
loop Determine the condition Determine what inside the loop will
update the condition Determine other things to do in loop Does condition need to be initialized?
Your turn On a piece of paper that you can
give me, write a loop to ensure that the user has entered a single digit (read the value in as a character). You may do range checking (>= 0 and < 10) or check each value
Discuss with 2 others
Write a loop to find the maximum of a list of numbers First, find max of 10 numbers
count controlled loop, so use count controlled template:Init counter to 0 while (count < n) // n is number of times through loop { // all actions in loop count = count + 1; }
Filling in Max finding loop
count = 0; // Init counter to 0 while (count < 10) // 10 is number of times through loop { // read a number and save max count = count + 1; }cout << "The maximum of the numbers you " << "entered is " << max << endl;
Filling in Max-Finding loopcount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; // save max count = count + 1; }cout << "The maximum of the numbers you " << " entered is " << max << endl;
Finding max
same way as you finding max – start with one number being max, then compare each new number to max:
if (number > max) // max holds max so far
max = number;
// else otherwise, DO NOTHING!!!
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you" << " entered is " << max << endl;
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
0 ??
count max
??
number
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
0 ??
count max
0 < 10 true
??
number
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
0 ??
count max
Enter a number>
??
number
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
0 ??
count max
Enter a number> 23
23
number
Write a count controlled loop to find max of 10 numberscount = 0; // Init counter to 0 while (count < 10) { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
0 ??
count max
number > max ??? we don’t know. max is not initialized
23
number
Finding max in a loop Lessons
always initialize variables if necessary (number not initialized, but ok)
Always trace through/step through program to look for problems
Fixes Initialize max to be very low number so it
will be replaced immediately Read in a number before going into the loop
Write a count controlled loop to find max of 10 numbers
int count = 0; // can initialize when declareddouble number, max;cout << "Enter a number> ";cin >> max; // put number right into maxcount = 1; // Init counter to 1 because 1 number readwhile (count < 10) // don't do <= { cout << "Enter a number> "; cin >> number; if (number > max) // max holds max so far
max = number;
count = count + 1; }cout << "The maximum of the numbers you entered " << " is " << max << endl;
Your turn Write a count controlled loop to
find the minimum of n numbers (ask the user to enter n first)
Sentinel Controlled Loops Keep going until some value is entered. Template:cout << "Enter a value> ";cin >> value;while (value != sentinel) { // do loop processing cout << "enter a value> "; cin >> value; }
Write a loop to sum values until –1 is entered templatecout << "Enter a value> ";cin >> value;while (value != sentinel) { // do loop processing cout << "enter a
value> "; cin >> value; }
sum = 0;cout << "Enter a value> ";cin >> value;while (value != -1) { sum = sum + value; cout << "enter a value> "; cin >> value; }
More Your Turn Write a loop to find the max number
until a 0 is entered Write a loop to find the max of 6
numbers Write a loop that finds the smallest
of 8 numbers Write a loop that validates user
input until user enters a letter (use isalpha)
Write a loop to find the max number until a 0 is enteredcout << "Enter a value>
";cin >> value;while (value != sentinel) { // do loop processing cout << "enter a value>
";
cin >> value; }
cout << "Enter a value> ";cin >> value;max = value;while (value !=0) { if (value > max) max = value; cout << "enter a value> ";
cin >> value; }
Write a loop to find the max of 6 numbers
count = 0;max = -99999999;while (count < 6){cout << "Enter a number>
"; cin >> number; if (number > max) max = number;count = count + 1;}
Init counter to 0 while (count < n) // n is number of
times through loop { // all actions in
loop count = count + 1; }
Write a loop to find the min of 8 numbers
count = 0;min = 99999999;while (count < 8){cout << "Enter a number>
";
cin >> number; if (number < min) min = number;count = count + 1;}
Init counter to 0 while (count < n) // n is number of
times through loop { // all actions in
loop count = count + 1; }
Write code that validates user input for a letter (use isalpha)template:cout << "Enter a value> ";cin >> value;// vv1 .. vvn are all of the valid
valueswhile ((value != vv1) && …
(value != vvn)) {cout << "Your entry is
invalid."; cout << "Enter a " << vv1
<< ", " << … << "vvn> "; cin >> value; }
cout << "Enter a value> ";cin >> value;while (!isalpha(value)) {cout << "Your entry is
invalid."; cout << "Enter a letter> "; cin >> value; }
Review -- We know count-controlled loop, sentinel-
controlled loops, validation loops finding max or min in a series of
numbers
Need to know: how to do other common things in
loops
Accumlate data in loops sum = sum + newnumber; sum = sum + count; product = product + factor power = power * factor if (newnumber should replace
savedvalue) savedvalue = newnumber
Accumulation shortcuts count++ < -- > count = count + 1 ++count < -- > count = count + 1 can be part of another statement. count++ (postincrement) increment
done after the rest of the statement ++count (preincrement) more
efficient. done before the rest of the statement
More accumulation shortcuts total += value is the same as
total += value total -= decrement is the same as
total = total – decrement product = product * factor is the same as
product *= factor quotient /= divisor, remainder %= divisor is also legal
--stepdown, stepdown-- is same as stepdown = stepdown - 1
Lots of operators so far Look at precedence Note associativity
commaleft to right,
assignmentright to left= += -= *= /= %=
logical ORleft to right||
logical ANDleft to right&&
equalityleft to right== !=
relationalleft to right< <= > >=
insertion extraction
left to right<< >>
additiveleft to right+ -
multiplicativeleft to right* / %
unaryright to left++ -- (pre) + - !
unaryleft to right++ -- (post)
parensleft to right()
TypeAssociativityOperator
for loops mainly for count-controlled loops warning: i not visible outside loop
for (int i=0; i < nbrtimestoloop; ++i){// do processing}
while-for equivalence
for (int i=0; i < nbrtimestoloop; ++i)
{// do processing}
int i=0;while (i <
nbrtimestoloop){// do processing++i;}
Find min of 8 numbers -- forint count = 0;min = 99999999;while (count < 8){cout << "Enter a number>
";
cin >> number; if (number < min) min = number;++count;}
min = 99999999;for (int count =0; count
< 8; ++count){cout << "Enter a
number> ";
cin >> number; if (number < min) min = number;}
How to format code for loops indent statements within loop use { }s almost all of the time (not
always with for loops) put update at end of loop
Functions with Reference Parmeters
Sections 3.17, 3.10, 3.11
Parameter Reviewint getsmaller(int x, int y){ if (x>y) return y; else return x;}
int main{ int a=0, b=2, c; c = getsmaller(a, b);}
0 2
0 2
Use of functions function call
name of function, name of parameters no types use return value
function header and definition names and types of parameters return value type
function prototype types of parameters (names optional)
return value type
Names of Parameters
int getsmaller(int x, int y){ if (x>y) return y; else return x;}int main{ int a=0, b=2, c; c = getsmaller(a, b);}
formal parametersin function header
Actual parameters in function call
Write a program that reads 2 floats and calculates the largest, sum, and average. Write and use three functions: large2, sum2, average2. At least one of these functions should call another function.
Discuss your answer with 2 others.
#include <iostream>#include <cstdlib>
using namespace std;
float average2(float, float);float large2(float, float);float sum2(float, float);
int main(){ float a, b, average, larger, sum; cout << “Enter two numbers> ”; cin >> a >> b; average = average2(a, b); larger = large2(a, b); sum = sum2(a, b); cout << “The two integers are ” << a << “and ” << b << “. Their average is ” << average << “; the larger is ” << larger << “; the sum is ” << sum << “.” << endl; return EXIT_SUCCESS;}
float large2(float x, float y){ if (x > y) return x; else return y;}
float small2(float x, float y){ temp = large2(x, y); if (temp == x) return y;else return x;} float average2(float x, float y){ return (x+y)/2;}
Input Parmeters All of the parameters so far have had a
starting value that the function used. When the function was complete and
control returned to the caller, the value of the actual parameters had not changed:
y=4.0; sqrt(y) -- y is unchanged x=2.0; pow(y, x) -- x and y are unchanged
These are called input parameters (have a value at the beginning; that value is unchanged when function is done)
Non-input Parametersletter = getletter();
no parameters. reads and returns letter char
letter = toupper(letter);
one parameter. reads and puts letter char in the parameter
getletter(letter);
one parameter. reads and puts letter char in the parameter
toupper(letter);
one parameter. letter has an initial value which is (may be) changed
Input, Output, Input-Output Parameters
letter = toupper(letter); // input parameter
one parameter. reads and puts letter char in the parameter
getletter(letter); // output parameter
one parameter. reads and puts letter char in the parameter
toupper(letter); // input-output parameter
one parameter. letter has an initial value which is (may be) changed
Value and Reference Parameters
Value parameters copy the value of the actual parameter to the value of the formal parameter
letter = toupper(letter); // input parameter
Reference parameters do NOT copy the value. Instead, the formal parameter is a pointer to the actual parameter
getletter(letter); // output parameter
Input parameters may be value; output, input-output parameters must be reference
Reference Parameters
& in function header and prototype no change to function call
void getletter(char&); // for prototypevoid getletter(char &letter) // for
headergetletter(myletter); for call
#include <iostream>#include <cstdlib>
using namespace std;
void toupper(char&);void getletter(char&);void printletter(char);
int main(){char c;getletter(c);toupper(c);printletter(c);return EXIT_SUCCESS;}
void toupper(char &c){ if ((c >= 'a') && (c <='z')) c -= 32; return; }
void getletter(char &c){ c = '0'; while (!isalpha(c))
{ cout << "please enter a letter (a-z)> "; cin >> c;}
}
void printletter(char c){ cout << "letter is " << c << endl;}
Trace Reference Parameters
Your turn
Write a program to sum the number from 1 to 10. Use a function Sum
which has two parameters, the current number and the
currentsum. When the function returns, the sum has been
incremented by the current number.
Discuss your answer with 2 others.
File streams
Chapter 14.2-14.6, 12.1-12.4, 12.6-12.8
Remember redirection? It lets you read from a file
prompt> a.out <infile >outfile
We have substituted the disk file infile for the standard input file (keyboard)
and outfile for the standard output file (display)
Redirection isn't enoughWhat if we wanted to read from more than
one file at the same time? student registration file
prepare bill -> tuition bill
student info file
File Streams It’s really not much different than
using cin and cout. Why call it a STREAM?
All devices can be viewed simply as a stream of chars (like a river is a stream of water) whether it is an input or output stream.
How to use file streams Include <fstream> Declare input files as ifstream Declare output files as ofstream To read in, use >> To write out use << Keep going until eof is reached
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
const char * filename=”myfile.txt";
string word;
ifstream wordfile(filename);
if (!wordfile) // check to see if file is there.
{cout << "Error: no file name " << filename << endl;
return EXIT_FAILURE;
}
int count=0;
while (wordfile >> word) // keep going until eof.
{
cout << "Word is " << word << endl;
count++;
}
wordfile.close();
cout << "the number of words in the file is " << count << endl;
return EXIT_SUCCESS;
}
Using an output file The same as modifications to
input; instead of cout, use filename
make sure you format check for problems opening (file
will be erased if there)
Passing file streams as parameters Always pass as reference type is ifstream or ofstreamvoid getnextword(ifstream&, string&);
getnextword(infile, word);
void getnextword(ifstream &infile, string &word){ if (!infile.eof())
infile >> word;}
Write your own Write a program that reads word
from a file, writes them to a duplicate file, and counts the number of words. Use a function, writeword, which has two parameters, the file to be written to and the word being written (an input parameter)
More stream functions open, get, put, eof, fail, close
put and get are used for reading files a char at a time
THEY DO NOT SKIP SPACES etc! You can use cin type input ( >> ) but it
skips white space.Remember how cin does the same?
cerr, section 12.2.3 What if you wanted to output an error but
the person was redirecting the output to a file?
prompt> a.out >outfile
YOU WOULDN'T SEE THE ERROR! the cerr stream is a special kind of output
which would NOT be redirected to the standard output device.
cerrOriginal program that reads in words and printed
them to the screen could redirect output and produce the same results as second. But if you want to see errors no matter what, use cerr:
if (!wordfile) // check to see if file is there. {
cerr << "Error: no file name " << filename << endl; return EXIT_SUCCESS; }
Output manipulators a function called as though it were
being output, e.g., endl setw, precision, showpoint, scientific,
fixed can be used on any output stream, cout
or file some defined in iostream; some in
iomanip (those with parameters)
Output Manipulators
{float x;cout << setw(10) << x << endl;} endl we've seen setw(10) minimum of 10 spaces (x, like
all output is right justified)
Output flags
float x;cout << fixed << precision(2) << x << endl; or:
cout.setf (ios::fixed);cout.precision(2);cout << "x" << endl;
Output flags/manipulators Lots of them:
right, left, internal fill, setfill hex, octal, dec, showbase uppercase scientific, fixed, showpoint precision showposI will not expect you to memorize these for a
test; know they exist so you can look them up as needed
Input functions (get) get (can use with cin or any input stream)
cin.get(ch); // puts char in output parameter ch = cin.get() // returns the char as function
value cin.get(chararray, maxsize, <delimiter>)
// null character inserted into array as terminator
// null character remains in input stream// works like getline
Input functions getline (with cin or any input stream)
null character inserted in array at end delimiter read and discarded (UNLIKE get) cin.getline(chararray, size, <delimiter>)
member of istream class getline(istream, string, <delimiter>)
string is of string class. NO dot notation
More input functions ignore
istream.ignore(); // skips over one char istream.ignore(n); // skips over n chars istream.ignore(n, '?'); // skips over n chars, or
until a question mark whichever is first' examples:
cin.ignore(); ifstream ins; ins.ignore(1000, '\n'); // throw away next
return
Arrays
Chapter 4
What can't we do with single variables?
Sort 10 numbersint x,y,z,m,n,o,p,q, r,s;largest = x; if (y > x) largest = y;if (z > x) largest = z; … then get second largest, third largest, etc. To get 2nd largest, have largest, but no way
to say "n was the largest, so don’t look at n anymore"
what if 10,000 numbers?
Use arrays blocks of storage with many
elements all of the same kind char chararray[10];
'3''?' 'e''K''a' 'W' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
' ''3'‘a'
chararray[0] = 'R';
Accessing Elements in Arrays
'3''?' 'e''K''a' 'W' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
'e''?' 'e''K''R' 'W' 'X' 'R''Z'
10 42 3 5 6 87 9
chararray
chararray[3] = chararray[4];
int i=8; chararray[i] = 'Z';
‘0'‘e'
More accessing elements
'3''?' 'e''K''a' 'W' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
// NOTE: no chararray[10]. runtime array index out //of bounds error
chararray[3] = chararray[4] + 1; // 'e' + 1 == 'f'
'f''?' 'e''K''a' 'W' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
Array Overview element can be of any type (int, char,
bool, float, string) all elements the same type indexes always integers starting at 0 range of index is 0 – (size-1) can (should) have constant as a size
int arraysize = 10; // same as char chararray[10];
char chararry[arraysize];
Integer Arraysconst int arraysize = 10;int myarray[arraysize];myarray[0] = 3;myarrary[3] = 2;
myarray[myarray[3]] = 15;
myarray[myarray[3] + 4] = myarray[0];
myarray[myarray[3]+myarray[4]] = 63;
10 42 3 5 6 87 9
myarray
23 315
myarray[4] = 1;
163
Arrays in loops
myarray[0] = 0; myarray[1] = 0;myarray[2] = 0; myarray[3] = 0;myarray[4] = 0; myarray[5] = 0;myarray[6] = 0; myarray[7] = 0;myarray[8] = 0; myarray[9] = 0;ORfor ( int i=0; i< arraysize; ++i) myarray[i] = 0;
Your Turn Trace myarray[i] = 0 loop, then write: Write values for myarray
without a loop with a loop
Read values for myarray without a loop with a loop
Sum values in myarray without a loop with a loop
Array initialization
int x[10] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int x[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int x[10] = {3, 4, 5, 6, 7}; // index5-9 are 0
int x[5] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // syntax error
Array Elements as Parameters
10 42 3 5 6 87 9
myarray
3 2 315 63
• function call accesses individual elements using []s (like assign, etc. for individual elements:
•swap(myarray[3], myarray[5]);
10 42 3 5 6 87 9
myarray
3 63 315 2
Passing Array Elements as Parameters Prototype and Function Definition
Works as though the elements were not in an array (they're not in the definition)
prototype: void swap(int&, int&); // & for input/output. NO []s!!! definition – same as our previous swap
void swap(int &x, int&y){int temp; temp = x; x = y; y = temp;}
Passing Arrays as Parameters: Function Prototypes Arrays are passed by reference. no
choice. no & (not true for array values – e.g., void swap(int&, int&);
MUST have [ ]s. Do not include size void writearray(int[], int);
if array is not changed, use const void writearray(const int[], int);
no &,but stillpassed
byreference
Passing Arrays as Parameters:Function Definitions
void writearray(const int x[], int size) {for (int i=0;i<size;++i) cout << "Element " << i << " is " << x[i] << endl; }
no size, no &.Does have [ ]s
Passing Arrays as Parameters:Function Calls
int main(){ const int arraysize = 10; int myarray[arraysize]; readarray(myarray); // NO [ ]! writearrary(myarray);}
Your Turn Write a program that reads in 10
integers, swaps the first and last, the second and second to last, the third and third to last, and the fourth and fourth to last (reverses the array). Write the reversed array out. Use functions swap, readarray, writearray.
Character Arrays as Strings Array elements can only be
accessed individually, not as a whole: cin >> myarray; // is illegal
Want to be able to think of character arrays as all one chunk, e.g., "Hello"
'l''l' 'o''e''H' '\0' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
Character arrays as Strings: \0
• '\0' is a string terminator in a character array:
•cout << myarray will not work (if myarray is an integer array).
•cout << chararray WILL print "Hello" IF a '\0' terminator is there
•With '\0', you can cin and cout char arrays as chunks treating them like strings.
'l''l' 'o''e''H' '\0' 'X' ' ' '0' 'R'
10 42 3 5 6 87 9
chararray
Writing and Testing Programs
Drivers and StubsSupplement to text
Write and Test Parts Do not write entire programs at a time Write the whole algorithm in English,
pseudo-code Choose which part to implement Write that part Test that part Write another part (in another file).
Test that part When done with all parts, integrate all
parts (in one or many files)
How do I write one part? Choose a function to write Type it into a file (algorithm is
already written) Write a main section to test just
that function Compile and test
What about main? Write main Instead of writing each function,
have “stubs” – functions with the correct prototype, header and return type (can be a constant), but don’t do any calculation
Compile and Test main
Example
Write a program that prints the product of the absolute value of 2 integers. Each of the 2 integers will be calculated by reading in 3 integers and choosing the largest (so a total of 6 integers will be entered).
Write the algorithm – NOT C++
Algorithm
1. Read in 3 numbers2. Get the largest of those. Call it a.3. Get the absolute value of a. call it absa4. Read in 3 more numbers. 5. Get the largest of those. Call it b.6. Get the absolute value of b. Call it
absb7. Output the product of absa and absb
Algorithm (more detailed)1. Read in 3 numbers
Could have a separate function, but this is short, and we don’t know how to write a function to do this yet.
cin >> int1 >> int2 >> int3 (with labels)
2. Get the largest of those. Call it a. We’ll call this function max3. Takes 3
integers as parameters. Returns the largest.
3. Get the absolute value of a. call it absa We’ll call this function abs (already written in
some math library, but we’ll write out own).
Algorithm (continued)4. Read in 3 more numbers.
cin >> int1 >> int2 >> int3 (ok to call the same names as earlier)
5. Get the largest of those. Call it b. Call max3: b = max(int1, int2, int3)
6. Get the absolute value of b. Call it absb
Call abs: absb = abs(b)
7. Output the product of absa and absb cout << absa * absb (with labels)
Next First, write and test max3.cc Second, write and test abs.cc Third, write and test main Fourth, after all is tested, modify
main to use max3, abs, and test
Writing the functions
Write the algorithm for function max3.
Algorithm for max3
Now, write the function prototype and function definition.
1. Compare int1 and int2. Store larger in largest
2. Compare largest and int3. Store larger in largest
3. Return largest
Write prototype and definition for max3prototype:int max3(int, int, int);
max3 (in file max3.cc)
int max3(int int1, int int2, int int3){ int largest; if (int1 < int2) largest = int2;else largest = int1; // if int1 > or = to int2if (int3 > largest) largest = int3;return largest;
}
Test max3 Write a driver main function whose sole purpose
it to test a function calls the function with reasonable
values (input w/cin or constants – advantage of cin is you can run multiple tests)
prints the return value.
max3 driver#include <iostream>#include "max3.cc"
using namespace std;int max3(int, int, int);
int main(){ int int1, int2, int3; cout << “Enter 3 integers to test max3> "; cin >> int1 >> int2 >> int3; cout << "The result of max3 called with " << int1 << ", " << int2 ", " << ", and " << int3 << " is " << max3(int1, int2, int3) << endl;}
Write algorithm for abs
1. if input parameter (x) is positive, return x
2. otherwise, return x * -1
Write prototype and definition for absprototype: int abs(int);
definition in file abs.cc:int abs(int x){ if (x >= 0) return x; else return x*-1;}
Write driver to test abs#include <iostream>#include "abs.cc"using namespace std;int abs(int);int main(){ int x; cout << "Enter an integer to test abs> "; cin >> x; cout << "abs called with " << x << " returns " << abs(x) << endl;}
Write main function (algorithm below)
1. Read in 3 numberscin >> int1 >> int2 >> int3 (with labels)
2. Get the largest of those. Call it a. Call max3.
3. Get the absolute value of a. call it absa Call abs
4. Read in 3 more numbers. cin >> int1 >> int2 >> int3
5. Get the largest of those. Call it b. Call max3: b = max(int1, int2, int3)
6. Get the absolute value of b. Call it absb Call abs: absb = abs(b)
7. Output the product of absa and absb cout << absa * absb (with labels)
#include <iostream>// do NOT include max and absusing namespace std;int abs(int);int max(int, int, int);int main(){int int1, int2, int3, a, b, absa, absb; cout << "Enter three integers> "; // 1 cin >> int1 >> int2 >> int3; a = max3(int1, int2, int3); // 2// next cout debugging only cout << "Result of max3 call is: " << a << endl;absa = abs(a); // 3// next cout for debugging onlycout << "result of abs is " << absa << endl;
cout << "Enter three more integers> "; // 4
cin >> int1 >> int2 >> int3; b = max3(int1, int2, int3); // 5// next cout debugging only cout << "Result of max3 call is: " << b <<
endl;absb = abs(b); // 6// next cout for debugging onlycout << "result of abs is " << absb << endl;cout << "The answer is " << absa * absb
<< endl; // 7} // end main
int max3(int a, int b, int c){ cout << "in abs with parameters " << a << ", " << b
<< ", " << c < end; return 10;}
int abs(int x){ cout << "in x with parameter " << x << endl;
return x;}
Next First, write and test max3.cc Second, write and test abs.cc Third, write and test main Fourth, after all is tested, modify
main to use max3, abs, and test
Write the entire program modifying main and including max3 and abs
#include <iostream>include "abs.cc"include "max3.cc" using namespace std;int abs(int);int max(int, int, int);int main(){int int1, int2, int3, a, b, absa, absb; cout << "Enter three integers> "; // 1 cin >> int1 >> int2 >> int3; a = max3(int1, int2, int3); // 2// cout << "Result of max3 call is: " << a << endl;absa = abs(a); // 3// cout << "result of abs is " << absa << endl;cout << "Enter three more integers> "; // 4 cin >> int1 >> int2 >> int3; b = max3(int1, int2, int3); // 5// cout << "Result of max3 call is: " << b << endl;absb = abs(b); // 6//cout << "result of abs is " << absb << endl;cout << "The answer is " << absa * absb << endl; // 7} // end main