C Programming
C Programming
C Programming
Chapter Objectives
Define the terminology used in programming Explain the tasks performed by a programmer Understand the employment opportunities for programmers and software engineers Explain the history of programming languages Explain the sequence, selection, and repetition structures Write simple algorithms using the sequence, selection, and repetition structures
Programming a Computer
It is important to understand the relationship between the terms programs, programmers, and programming languages. Programs - The directions that humans give to computers
Programmers - The people who create these directions Programming Languages - Special languages used by programmers to communicate directions to a computer
Employment Opportunities
Computer software engineer: designs an appropriate solution to a users problem Computer programmer: codes a computer solution Coding is the process of translating a computer solution into a language a computer can understand Some positions call for both engineering and programming
Machine Languages
The first programmers had to write the program instructions using only combinations of 0s and 1s
Example: 0000 0101 1100 0000
Instructions written in 0s and 1s are called machine language or machine code Each type of machine has its own language Machine languages are the only way to communicate directly with the computer Programming in machine language: tedious and errorprone; requires highly trained programmers
An Introduction to Programming with C++, Seventh Edition 8
Assembly Languages
Assembly languages made writing code simpler than using only 0s and 1s Mnemonics symbols used to represent the actual machine language instructions Example: 00000101 vs. BALR Assembly programs require an assembler to convert instructions into machine code Easier to write programs in assembly language
But still tedious and requires highly trained programmers
High-Level Languages
High-level languages allow programmers to use Englishlike instructions Example: taxAmount = total * taxRate Each high-level language instruction is equivalent to more than one machine language instruction Compilers translate high-level instructions into 0s and 1s (machine language) Interpreters translate the program line by line as the program is running
10
An object-oriented program requires the programmer to focus on the objects that the program can use to accomplish its goal
Examples: C++, Visual Basic, Java, C#
Object-oriented programs allow for an object to be created that can be reused in more than one program
An Introduction to Programming with C++, Seventh Edition 11
Control Structures
All computer programs are written using one or more of three basic control structures: sequence, repetition, and selection. Another term used for control structures are logic structures, because they control the logic flow of the program.
While in every program that is written the sequence structure will be used, in most all programs all three control structures will be used.
12
13
15
16
18
Figure 1-4 Original algorithm and modified algorithm showing the repetition structure
An Introduction to Programming with C++, Seventh Edition 19
20
Figure 1-5 Algorithm showing the modified condition in the repetition structure
21
Summary
Programs are step-by-step instructions that tell a computer how to perform a task Programmers use programming languages to communicate with the computer First programming languages were machine language using 0s and 1s Assembly languages followed, using mnemonics High-level languages can be used to created procedureoriented or object-oriented programs
22
Summary (cont.)
An algorithm is a finite number of step-by-step instructions that accomplish a task Algorithms utilize three basic control structures: sequence, selection, and repetition The sequence structure directs the computer to process the program instructions, one after another, in the order in which they are listed The selection structure directs the computer to make a decision (evaluate a condition), and then take an appropriate action based upon that decision
An Introduction to Programming with C++, Seventh Edition 23
Summary (cont.)
The repetition structure, commonly called iteration or looping, directs the computer to repeat one or more program instructions until some condition is met The sequence structure is used in all programs Most programs also contain both the selection and repetition structures
24
25
26
27
Chapter Objectives
Explain the problem-solving process used to create a computer program Analyze a problem Complete an IPO chart Plan an algorithm using pseudocode and flowcharts Desk-check an algorithm
Problem Solving
People solve hundreds of simple problems every day without thinking about how they do it Understanding the thought process involved can help in solving more complex problems You can also use a similar process to design a computer solution to a problem (computer program)
Next, you plan, review, implement, and evaluate the solution After this, it may be necessary to modify the solution
Figure 2-1 Summary of the analysis and planning steps for the bill paying problem
An Introduction to Programming with C++, Seventh Edition 5
10
Figure 2-5 Partially completed IPO chart showing the input and output items
11
12
Figure 2-7 Problem specification that does not contain enough information
13
Figure 2-8 Problem specification in which the input is not explicitly stated
14
15
Figure 2-9 Problem specification and IPO chart for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 16
17
21
22
Figure 2-13 Treyson Mobley solution and partially completed desk-check table
23
25
Figure 2-18 Second set of input values entered in the desk-check table
Figure 2-19 Value of the second desk-checks processing item entered in the desk-check table
Figure 2-20 Value of the second desk-checks output item entered in the desk-check table
An Introduction to Programming with C++, Seventh Edition 26
27
28
29
30
Summary
Problem solving typically involves analyzing the problem and then planning, reviewing, implementing, evaluating, and modifying (if necessary) the solution Programmers use tools (IPO charts, pseudocode, flowcharts) to help them analyze problems and develop algorithms The first step in problem solving is to analyze the problem
First determine the output and then the input
31
Summary (contd.)
The second step is to plan the algorithm
Write the steps that will transform the input into the output Most algorithms begin with entering input data, then processing the data, then displaying the output
32
35
Chapter Objectives
Distinguish among a variable, a named constant, and a literal constant Explain how data is stored in memory Select an appropriate name, data type, and initial value for a memory location Declare a memory location in C++
Internal Memory
Computers internal memory is composed of memory locations, each with a unique numeric address Similar to collection of storage bins Each address can store one item at a time Address can contain numbers, text, or program instructions To use a memory location, programmer must reserve the address, called declaring
If constants contain more than one word, separate words with underscores
Example: TAX_RATE
If variables contain more than one word, capitalize the first letter of each word after the first (called camel case)
Example: adjustedGrossIncome
An Introduction to Programming with C++, Seventh Edition 10
Figure 3-3 Problem specification, IPO chart, and desk-check table from Chapter 2
An Introduction to Programming with C++, Seventh Edition 12
13
Figure 3-4 Names of the variables for the Treyson Mobley problem
14
15
bool data type stores Boolean values (true and false) short and int types store integers (numbers without a decimal place) Differences are range of values and memory used (int
has the greater of both)
An Introduction to Programming with C++, Seventh Edition 16
char type stores characters (letter, symbol, or number that will not be used in a calculation)
Only one character stored at a time
string data type is a user-defined data type (defined with a class, or group of instructions)
Can store zero or more characters
An Introduction to Programming with C++, Seventh Edition 17
1 byte = 8 bits 1 kilobyte (K / Kb) = 2^10 bytes = 1,024 bytes 1 megabyte (M / MB) = 2^20 bytes = 1,048,576 bytes 1 gigabyte (G / GB) = 2^30 bytes = 1,073,741,824 bytes 1 terabyte (T / TB) = 2^40 bytes = 1,099,511,627,776 bytes 1 petabyte (P / PB) = 2^50 bytes = 1,125,899,906,842,624 bytes 1 exabyte (E / EB) = 2^60 bytes = 1,152,921,504,606,846,976 bytes
An Introduction to Programming with C++, Seventh Edition 19
Figure 3-6 Data type assigned to each variable for the Treyson Mobley problem
20
Computer distinguishes between numbers and ASCII codes based on data type
An Introduction to Programming with C++, Seventh Edition 21
Figure 3-7 How to use the decimal (base 10) number system
22
23
25
Promoting will not usually have adverse effects, but demoting can (information is lost)
An Introduction to Programming with C++, Seventh Edition 27
Figure 3-10 Initial values for the variables in the Treyson Mobley problem
29
30
After variable is declared, you use its name to refer to it later in the program Initial value is optional but recommended If variable is not initialized, it contains the previous value of that memory location, which may be the wrong type (called a garbage value)
An Introduction to Programming with C++, Seventh Edition 31
is a named constant (value cannot be changed during runtime) Initial value required for constants, unlike variables As with variables, after declaring a constant, you can use its name to refer to it later in the program
32
34
Figure 3-12 C++ declaration statements for the variables in the Treyson Mobley problem
35
36
Summary
Fourth step in problem-solving process is coding the algorithm Memory location is declared for each input, processing, and output item in IPO chart Numeric data is stored in computers internal memory using binary number system Memory locations store one item at a time Memory locations data type determines how a value is stored and interpreted when retrieved
37
Summary (contd.)
Two types of memory locations: variables and named constants Memory locations are declared using a statement that assigns a name, data type, and initial value Initial value required for named constants but optional for variables (though recommended) Most memory locations initialized with literal constants, except bool (initialized with keywords true or false)
38
Summary (contd.)
Data type of literal constant assigned to memory location should be same as memory locations type If types dont match, implicit type conversion is used to either promote or demote so they match Promoting doesnt usually cause problems, but demoting can Syntax for declaring variables dataType variableName [= initialValue]; Syntax for declaring named constants const dataType constantName = value;
An Introduction to Programming with C++, Seventh Edition 39
Figure 3-14 Problem specification, IPO chart, and desk-check table for Lab 3-1
An Introduction to Programming with C++, Seventh Edition 40
41
42
Figure 3-21 IPO chart information and C++ instructions for Lab 3-5
An Introduction to Programming with C++, Seventh Edition 44
Objectives
Get numeric and character data from the keyboard Display information on the computer screen Write arithmetic expressions Type cast a value Write an assignment statement Code the algorithm into a program Desk-check a program Evaluate and modify a program
Figure 4-1 Problem specification, IPO chart information, and variable declaration
An Introduction to Programming with C++, Seventh Edition 4
Figure 4-2 Relationship among the keyboard, cin object, extraction operator, and internal memory
Figure 4-3 How to use cin and >> to get numeric or character data
An Introduction to Programming with C++, Seventh Edition 7
10
11
Figure 4-6 Prompts and output statement for the Treyson Mobley problem
An Introduction to Programming with C++, Seventh Edition 12
13
14
15
Figure 4-8 Expressions containing more than one operator having the same precedence
16
18
19
Assignment Statements
You use an assignment statement to assign a value to a variable while a program is running Syntax: variableName = expression
The = symbol is the assignment operator
Tells computer to evaluate expression on right side of assignment operator and store result in variable on left side of the operator
expression can include one or more literal constants, named constants, variables, or arithmetic operators
22
Remember:
Declaration statement creates a new variable Assignment statement assigns a new value to an existing variable
An Introduction to Programming with C++, Seventh Edition 23
%=
An Introduction to Programming with C++, Seventh Edition 27
28
Figure 4-15 Variable names and initial values entered in the programs desk-check table
An Introduction to Programming with C++, Seventh Edition 30
Figure 4-16 Input values entered in the programs desk -check table
Figure 4-17 Desk-check table showing the result of the total bill without liquor charge calculation
31
Figure 4-18 Desk-check table showing the result of the tip calculation
Figure 4-19 Programs desk-check table showing the results of the second desk-check
An Introduction to Programming with C++, Seventh Edition 32
33
Need a text editor to enter C++ instructions Instructions are called source code and are saved in source files with extension .cpp Need a compiler to translate source code into machine code (also called object code)
An Introduction to Programming with C++, Seventh Edition 34
Figure 4-20 Process by which source code is translated into executable code
An Introduction to Programming with C++, Seventh Edition 36
A #include directive allows you to merge the source code in one file with that in another file The #include <iostream> is required when using the cin or cout stream objects
Not a statement, so no semicolon needed at the end
An Introduction to Programming with C++, Seventh Edition 37
38
40
43
Summary
Fourth step in problem-solving process is coding the algorithm into a program C++ uses stream objects for standard input/output operations Use cin with extraction operator (>>) to get numeric or character data from the keyboard Use cout with insertion operator (<<) to display information on the screen The endl stream manipulator advances cursor to next line
An Introduction to Programming with C++, Seventh Edition 44
Summary (contd.)
You do calculations by writing arithmetic expressions using arithmetic operators Each operator has a precedence: determines the order of evaluation in an expression Parentheses are used to override this order Compiler implicitly casts data types when possible, but you should explicitly cast to ensure correctness Use the static_cast operator to explicitly cast variables from one data type to another
45
Summary (contd.)
An assignment statement assigns a value to a variable during runtime The expression on the right side of the assignment operator (=) in an assignment statement is stored in the variable on its left Fifth step of the problem-solving process is to deskcheck the program using the same data used to deskcheck the algorithm The sixth step is to evaluate and modify (if necessary) the program
An Introduction to Programming with C++, Seventh Edition 46
Summary (contd.)
Errors (called bugs) can either be syntax errors or logic errors You need a text editor and compiler to enter C++ instructions and compile them into a program C++ instructions are called source code and are saved in source files with the extension .cpp The compiler translates source code into machine code, also called object code A linker produces an executable file that contains all machine code necessary to run a C++ program
An Introduction to Programming with C++, Seventh Edition 47
Summary (contd.)
Programmers use comments to document a program internally
Comments are not processed by the compiler
The #include <filename> directive allows you to include multiple source files in a program The using namespace std; directive tells the compiler where definitions of standard C++ keywords and classes are in internal memory A namespace is a special area in the computers internal memory
An Introduction to Programming with C++, Seventh Edition 48
Summary (contd.)
Execution of every C++ program begins with the main() function The first line of a function is the function header The function body follows the header and is enclosed in braces Some functions return a data type; others return void Arithmetic assignment operators can be used to abbreviate certain assignment statements with arithmetic operators in them
An Introduction to Programming with C++, Seventh Edition 49
51
52
53
54
Objectives
Include the selection structure in pseudocode and in a flowchart Code a selection structure using the if statement Include comparison operators in a selection structures condition Include logical operators in a selection structures condition Format numeric output
Making Decisions
With only the sequence structure, all instructions are executed in order A selection structure is needed when a decision must be made (based on some condition) before selecting an instruction to execute A selection structures condition must be phrased as a Boolean expression (evaluates to true or false)
True path
Instructions followed when condition evaluates to true
False path
Instructions followed when condition evaluates to false
An Introduction to Programming with C++, Seventh Edition 4
Figure 5-2 A problem that requires the sequence structure and a single-alternative selection structure
An Introduction to Programming with C++, Seventh Edition 6
Figure 5-3 A problem that requires the sequence structure and a dual-alternative selection structure
An Introduction to Programming with C++, Seventh Edition 7
Selection structures have one flowline leading in and two leading out
T line leading out points to true path F line leading out points to false path
An Introduction to Programming with C++, Seventh Edition 8
[else
one or more statements (false path)]
Keyword if and condition are required Portion in brackets (else clause) is optional
Only used for dual-alternative selection structures
An Introduction to Programming with C++, Seventh Edition 11
Comparison Operators
Comparison operators are used to compare two values that have the same data type
less than (<) less than or equal to (<=) greater than (>) greater than or equal to (>=) equal to (==) not equal to (!=)
15
16
17
Figure 5-8 Evaluation steps for an expression containing arithmetic and comparison operators
19
20
Figure 5-9 IPO chart information and C++ instructions for the swapping program
An Introduction to Programming with C++, Seventh Edition 21
22
23
24
25
Figure 5-13 IPO chart information and C++ instructions for the sum or difference program
An Introduction to Programming with C++, Seventh Edition 26
27
28
Logical Operators
Logical operators allow you to combine two or more conditions (sub-conditions) into one compound condition Also called as Boolean operators (always evaluate to true or false) Two most common are And (&&) and Or (||) All sub-conditions must be true for a compound condition using And to be true Only one of the sub-conditions must be true for a compound condition using Or to be true
An Introduction to Programming with C++, Seventh Edition 29
31
34
35
Figure 5-18 Examples of C++ instructions for the gross pay program
An Introduction to Programming with C++, Seventh Edition 36
Figure 5-19 First sample run of the gross pay programs code
Figure 5-20 Second sample run of the gross pay programs code
37
Pass/Fail Program
Example problem description is given in which program must output Pass if user enters P or p, and Fail otherwise Character comparisons are case sensitive in C++ Program must check separately whether the user entered P or p Dual-alternative selection structure is used to implement program Compound condition with Or operator is used to perform check
An Introduction to Programming with C++, Seventh Edition 38
Summary of Operators
Figure 5-24 Listing and an example of arithmetic, comparison, and logical operators
An Introduction to Programming with C++, Seventh Edition 41
43
Large real numbers (more than six digits before decimal place) displayed in e notation
Example: 1,225,000.00 displayed as 1.225e+006
Number is rounded and truncated if there are more than six digits
Example: 123.3456789 is displayed as 123.345679
An Introduction to Programming with C++, Seventh Edition 47
Figure 5-26 How to use the fixed and scientific stream manipulators
An Introduction to Programming with C++, Seventh Edition 49
Summary
Selection structure used when you want a program to make a decision before choosing next instruction Selection structures condition must evaluate to true or false In single-alternative and dual-alternative selection structures, the instructions followed when the condition is true are placed in the true path In dual-alternative selection structures, the instructions followed when the condition is false are placed in the false path
An Introduction to Programming with C++, Seventh Edition 51
Summary (contd.)
A diamond (decision symbol) is used to represent a selection structures condition in a flowchart Each selection structure has one flowline going into the diamond and two coming out (T line represents the true path, and F line the false path) The if statement is used to code most selection structures True or false paths with more than one statement must be entered as a statement block (enclosed in {})
52
Summary (contd.)
Good practice to end if and else statements with a comment (//end if) Comparison operators are used to compare values Expressions using them evaluate to true or false Comparison operators have precedence ordering similar to arithmetic operators Dont use == and != to compare real numbers Local variables can only be used in the statement block in which they are declared
53
Summary (contd.)
Expressions with logical operators evaluate to true or false And (&&) and Or (||) are logical operators, which also have precedence Arithmetic operators are evaluated first in an expression, followed by comparison operators and then logical operators Character comparisons are case sensitive toupper and tolower functions temporarily convert a character to upper or lowercase
An Introduction to Programming with C++, Seventh Edition 54
Summary (contd.)
The fixed and scientific stream manipulators allow you to format real numbers The setprecision manipulator allows you to specify the number of decimal places that appear fixed and scientific are defined in the iostream file setprecision is defined in the iomanip file
55
58
60
Objectives
Include a nested selection structure in pseudocode and in a flowchart Code a nested selection structure Recognize common logic errors in selection structures Include a multiple-alternative selection structure in pseudocode and in a flowchart Code a multiple-alternative selection structure in C++
Making Decisions
True and false paths of a selection structure can contain other selection structures Inner selection structures are referred to as nested selection structures; contained (nested) within an outer selection structure Nested selection structures are used when more than one decision needs to be made before choosing an instruction Inner (nested) selection structures are indented within their outer selection structures
An Introduction to Programming with C++, Seventh Edition 3
11
Figure 6-8 Modified problem specification for the health club problem from Chapter 5s Lab 5-2
An Introduction to Programming with C++, Seventh Edition 12
Figure 6-8 Modified problem specification for the health club problem from Chapter 5s Lab 5-2 (contd)
13
14
16
17
20
Figure 6-17 Correct algorithm and incorrect algorithm containing the first logic error
21
Figure 6-18 Desk-check table for the incorrect algorithm in Figure 6-17
22
Figure 6-19 Correct algorithm and an incorrect algorithm containing the second logic error
An Introduction to Programming with C++, Seventh Edition 23
Figure 6-20 Desk-check table for the incorrect algorithm in Figure 6-19
24
25
Figure 6-21 Correct algorithm and an incorrect algorithm containing the third logic error
An Introduction to Programming with C++, Seventh Edition 26
27
Figure 6-25 IPO chart for the Kindlon High School problem
30
Figure 6-27 Two ways of coding the multiple-alternative selection structure from Figures 6-25 and 6-26
An Introduction to Programming with C++, Seventh Edition 32
34
39
Figure 6-29 IPO chart and C++ instructions for the Warren Company problem
An Introduction to Programming with C++, Seventh Edition 40
Summary
Can nest a selection structure within true or false path of another selection structure Three common logic errors when writing selection structures
Using a compound condition instead of a nested selection structure Reversing the inner and outer selection structures Using an unnecessary nested selection structure
42
Summary (contd.)
Some solutions require selection structures that choose from multiple alternatives; called multiple-alternative or extended selection structures Can code these either with if/else statements or the switch statement Diamond is used to represent multiple-alternative selection structures in a flowchart Has multiple flowlines leading out; each representing a possible path and marked with appropriate values
43
Summary (contd.)
In a switch statement, the data type of the value in each case clause must be compatible with data type of selector expression Selector expression must evaluate to value of type bool, char, short, int, or long Most case clauses contain a break statement; tells the computer to leave the switch statement Good practice to mark end of switch statement with a comment (//end switch)
44
Figure 6-32 Problem specification and calculation examples for Lab 6-2
An Introduction to Programming with C++, Seventh Edition 46
If the sales are less than zero, display The sales cannot be less than zero. If the code is not 1, 2, or 3, display Invalid Code
An Introduction to Programming with C++, Seventh Edition 47
49
Objectives
Differentiate between a pretest loop and a posttest loop Include a pretest loop in pseudocode Include a pretest loop in a flowchart Code a pretest loop using the C++ while statement Utilize counter and accumulator variables Code a pretest loop using the C++ for statement
Figure 7-1 A problem that requires the sequence and selection structures
Figure 7-2 A problem that requires the sequence and repetition structures
An Introduction to Programming with C++, Seventh Edition 7
Figure 7-4 Problem specification and IPO chart for the Totally Sweet Shoppe program
An Introduction to Programming with C++, Seventh Edition 10
Figure 7-5 Problem specification and IPO chart for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 11
12
13
14
Figure 7-8 Input and output items entered in the desk-check table
Figure 7-10 First employees information recorded in the desk -check table
An Introduction to Programming with C++, Seventh Edition 16
Figure 7-11 Second employees information recorded in the desk -check table
17
Must supply looping condition (Boolean expression) condition can contain constants, variables, functions, arithmetic operators, comparison operators, and logical operators
An Introduction to Programming with C++, Seventh Edition 18
19
20
Figure 7-14 IPO chart information and C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 23
24
25
27
28
Figure 7-17 IPO chart information and C++ instructions for the Sales Express program
An Introduction to Programming with C++, Seventh Edition 29
Figure 7-17 IPO chart information and C++ instructions for the Sales Express program (contd)
An Introduction to Programming with C++, Seventh Edition 30
Figure 7-19 Desk-check table after the first sales amount is entered
Figure 7-20 Desk-check showing the first update to the counter and accumulator variables
32
Figure 7-21 Desk-check table after the second update to the counter and accumulator variables
33
34
35
Figure 7-25 Problem specification for the Jasper Music Company program
36
Figure 7-25 IPO chart information and C++ instructions for the Jasper Music Company program
An Introduction to Programming with C++, Seventh Edition 37
42
Good programming practice to place a comment, such as //end for, to mark the end of a for loop
An Introduction to Programming with C++, Seventh Edition 43
Figure 7-33 Processing steps for the code shown in Example 1 in Figure 7-32
45
Figure 7-34 Problem specification for the Holmes Supply Company program
An Introduction to Programming with C++, Seventh Edition 46
Figure 7-34 IPO chart information and C++ instructions for the Holmes Supply Company program
An Introduction to Programming with C++, Seventh Edition 47
Figure 7-35 Results of processing the declaration statements and initialization argument
Figure 7-36 Desk-check table after update argument is processed first time
Figure 7-37 Desk-check table after update argument is processed second time
An Introduction to Programming with C++, Seventh Edition 48
Figure 7-38 Desk-check table after update argument is processed third time
Figure 7-40 IPO chart information and C++ instructions for the Colfax Sales program
An Introduction to Programming with C++, Seventh Edition 51
Figure 7-41 Processing steps for the code in Figure 7-40 (contd.)
53
54
55
56
Figure 7-44 IPO chart information and modified C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 57
Figure 7-45 Processing steps for the code shown in Figure 7-44
An Introduction to Programming with C++, Seventh Edition 58
Summary
Use the repetition structure (or loop) to repeatedly process one or more instructions Loop repeats as long as looping condition is true (or until loop exit condition has been met) A repetition structure can be pretest or posttest In a pretest loop, the loop condition is evaluated before instructions in loop body are processed In a posttest loop, the evaluation occurs after instructions in loop body are processed
59
Summary (contd.)
Condition appears at the beginning of a pretest loop must be a Boolean expression If condition evaluates to true, the instructions in the loop body are processed; otherwise, the loop body instructions are skipped Some loops require the user to enter a special sentinel value to end the loop Sentinel values should be easily distinguishable from valid data recognized by the program Other loops are terminated by using a counter
An Introduction to Programming with C++, Seventh Edition 60
Summary (contd.)
Input instruction that appears above a pretest loops condition is the priming read
Sets up the loop by getting first value from user
Input instruction that appears within the loop is the update read
Gets the remaining values (if any) from user
In most flowcharts, diamond (decision symbol) is used to represent a repetition structures condition
61
Summary (contd.)
Counters and accumulators are used in repetition structures to calculate totals and averages All counters and accumulators must be initialized and updated Counters are updated by a constant value Accumulators are updated by a variable amount You can use either the while statement or the for statement to code a pretest loop in C++
62
63
67
Objectives
Include a posttest loop in pseudocode Include a posttest loop in a flowchart Code a posttest loop using the C++ do while statement Nest repetition structures Raise a number to a power using the pow function
Posttest Loops
Repetition structures can be either pretest or posttest loops Pretest loop condition evaluated before instructions are processed Posttest loop condition evaluated after instructions are processed Posttest loops instructions are always processed at least once Pretest loops instructions may never be processed
Figure 8-1 Problem specification, illustrations, and solutions containing pretest and posttest loops
An Introduction to Programming with C++, Seventh Edition 4
Figure 8-3 Wheels & More problem specification & algorithms (continues)
An Introduction to Programming with C++, Seventh Edition 7
Figure 8-3 Wheels & More problem specification & algorithms (continued)
An Introduction to Programming with C++, Seventh Edition 8
Figure 8-4 Input and output items entered in the desk-check table
Figure 8-5 First hours worked and gross pay amounts recorded in the desk-check table
} while (condition); Some programmers use a comment (such as: //begin loop) to mark beginning of loop
An Introduction to Programming with C++, Seventh Edition 10
Programmer must also provide statements to be executed when condition evaluates to true Braces are required around statements if there are more than one
11
13
Figure 8-10 IPO chart information and C++ instructions for the Wheels & More program
An Introduction to Programming with C++, Seventh Edition 14
15
16
17
Figure 8-14 Modified problem specification and solution that requires a nested loop
19
20
Figure 8-15 Problem specification IPO chart information and C++ instructions for the asterisks program
An Introduction to Programming with C++, Seventh Edition 21
Figure 8-15 IPO chart information and C++ instructions for the asterisks program (contd.)
An Introduction to Programming with C++, Seventh Edition 22
Figure 8-18 Problem specification, IPO chart information, and C++ instructions for the modified asterisks program
24
Figure 8-18 Problem specification, IPO chart information, and C++ instructions for the modified asterisks program (cont.)
An Introduction to Programming with C++, Seventh Edition 25
Figure 8-19 Desk-check table and output after the nested loops cout statement is processed the first time
Figure 8-20 Desk-check table and output after the nested loops cout statement is processed the second time
An Introduction to Programming with C++, Seventh Edition 26
Figure 8-22 Desk-check table and output after the nested loop ends the second time
An Introduction to Programming with C++, Seventh Edition 27
Figure 8-23 Desk-check table and output after the nested loop ends the third time
28
29
30
Figure 8-25 Problem specification, sample calculations, IPO chart, and desk-check table for the savings calculator program
An Introduction to Programming with C++, Seventh Edition 31
33
35
Figure 8-28 IPO chart information and C++ instructions for the savings calculator program
36
Figure 8-28 IPO chart information and C++ instructions for the savings calculator program
37
39
40
Figure 8-31 IPO chart information and C++ instructions for the modified savings calculator program
An Introduction to Programming with C++, Seventh Edition 41
Figure 8-31 Modified IPO chart information and C++ instructions (contd.)
An Introduction to Programming with C++, Seventh Edition 42
Summary
A repetition structure can be either a pretest loop or a posttest loop In a pretest loop, the loop condition is evaluated before the instructions in the loop are processed In a posttest loop, the evaluation occurs after the instructions within the loop are processed Use the do while statement to code a posttest loop in C++ Use either the while statement or the for statement to code a pretest loop in C++
An Introduction to Programming with C++, Seventh Edition 46
Summary (contd.)
Repetition structures can be nested, which means one loop (called the inner or nested loop) can be placed inside another loop (called the outer loop) For nested repetition structures to work correctly, the entire inner loop must be contained within the outer loop You can use the built-in C++ pow function to raise a number to a power The pow function returns the result as a double
47
48
50
52
Objectives
Use the sqrt function to return the square root of a number Generate random numbers Create and invoke a function that returns a value Pass information by value to a function Write a function prototype Understand a variables scope and lifetime
Functions
A function is a block of code that performs a task Every C++ program contains at least one function (main)
Most contain many functions
Some functions are built-in functions (part of C++): defined in language libraries Others, called program-defined functions, are written by programmers; defined in a program Functions allow for blocks of code to be used many times in a program without having to duplicate code
Functions (contd.)
Functions also allow large, complex programs to be broken down into small, manageable sub-tasks Each sub-task is solved by a function, and thus different people can write different functions Many functions can then be combined into a single program Typically, main is used to call other functions, but any function can call any other function
Functions (contd.)
Value-Returning Functions
All functions are either value-returning or void All value-returning functions perform a task and then return precisely one value In most cases, the value is returned to the statement that called the function Typically, a statement that calls a function assigns the return value to a variable
However, a return value could also be used in a comparison or calculation or could be printed to the screen
An Introduction to Programming with C++, Seventh Edition 6
pow function can be used to square sqrt function can be used to take square root Both are built-in value-returning functions
Figure 9-2 Problem specification, calculation example, and IPO chart for the hypotenuse program
An Introduction to Programming with C++, Seventh Edition 8
10
Figure 9-5 IPO chart information and C++ instructions for the hypotenuse program
An Introduction to Programming with C++, Seventh Edition 12
14
15
16
19
Expression:
lowerBound + rand() % (upperBound lowerBound + 1)
20
Figure 9-11 How to generate random integers within a specific range (contd.)
An Introduction to Programming with C++, Seventh Edition 23
24
25
Figure 9-13 IPO chart information and C++ instructions for the random addition problems program
27
Figure 9-13 IPO chart information and C++ instructions for the random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 28
30
31
After return statement is processed, program execution continues in calling function Good idea to include comment (such as //end of functionName) to mark end of function
An Introduction to Programming with C++, Seventh Edition 33
Figure 9-16 IPO charts for modified random addition problems program
34
Figure 9-16 IPO charts for modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 35
36
37
Calling a Function
A function must be called (invoked) to perform its task main is automatically called when program is run Other functions must be called by a statement Syntax for calling a function: functionName([argumentList]); argumentList is list of actual arguments (if any)
An actual argument can be a variable, named constant, literal constant, or keyword
38
A call to a void function is an independent statement because void functions do not return values
39
40
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program
44
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
45
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 46
Figure 9-20 IPO chart information and C++ instructions for the modified random addition problems program (contd.)
An Introduction to Programming with C++, Seventh Edition 47
Function Prototypes
When a function definition appears below the main function, you must enter a function prototype above the main function A function prototype is a statement that specifies the functions name, data type of its return value, and data type of each of its formal parameters (if any)
Names for the formal parameters are not required
Programmers usually place function prototypes at beginning of program, after the #include directives
48
51
52
56
Figure 9-25 Problem specification and IPO charts for area calculator program
57
Figure 9-25 Problem specification and IPO charts for the area calculator program (contd.)
An Introduction to Programming with C++, Seventh Edition 58
59
Figure 9-28 Desk-check table after statements on lines 12 through 19 are processed
61
62
63
64
You should avoid using global variables unless necessary If more than one function needs to access the same variable, it is better to create a local variable in one function and pass it to other functions that need it
65
66
Figure 9-31 Problem specification, IPO chart information, and C++ code for the main function
An Introduction to Programming with C++, Seventh Edition 67
Figure 9-32 IPO chart information and C++ code for the getSales function
68
Figure 9-33 IPO chart information and C++ code for the getBonus function
69
70
71
Figure 9-36 Desk-check table after variable declaration statements on lines 14 & 15 are processed
An Introduction to Programming with C++, Seventh Edition 72
Figure 9-38 Desk-check table after the sales amount is returned to the main function
An Introduction to Programming with C++, Seventh Edition 73
Summary
Functions
Allow programmers to avoid duplicating code Allow for large, complex programs to be broken into small, manageable tasks
Some functions are built into the language, and others are program-defined All functions are either value-returning or void A value-returning function returns one value
Value returned to statement that called the function
Summary (contd.)
Use the sqrt function to find the square root of a number Items in parentheses in a function call are called actual arguments The rand function is used to generate random numbers
Returns an integer between 0 and RAND_MAX
77
Summary (contd.)
Function definition composed of header and body Header specifies function name, return data type, and formal parameter names and types (if any)
Data types and ordering of formal parameters must match data types and ordering of actual arguments
Summary (contd.)
You call a function by including its name and actual arguments (if any) in a statement Variables in C++ are passed by value by default A function prototype must be provided for each function defined below the main function Scope of a variable indicates where in the program it can be used Lifetime of a variable indicates how long it will stay in internal memory
79
Summary (contd.)
Local variables can be used only within the function in which they are declared or in whose parameterList they appear
Remain in memory until the function ends
If more than one memory location have the same name, position of the statement in which the name is used determines which location is used
80
81
83
85
Objectives
Create a void function Invoke a void function Pass information by reference to a function
Functions
Recall that value-returning functions perform a task and then return a single value Void functions also perform tasks but do not return a value A void function may be used to do something like display information on the screen
Doesnt need to return a value
Functions (contd.)
Function body does not contain a return statement Call a void function by including its name and actual arguments (if any) in a statement Call to a void function appears as a self-contained statement, not part of another statement Execution is same as for value-returning functions
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 8
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 9
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 10
Figure 10-4 IPO chart information and C++ instructions for the ABC Company program (contd.)
An Introduction to Programming with C++, Seventh Edition 11
14
15
16
Figure 10-9 Desk-check table after the first three statements in the main function are processed
Figure 10-10 Desk-check table after the displayAge function header is processed
An Introduction to Programming with C++, Seventh Edition 18
Void functions use variables passed by reference to send information back to the calling function, instead of a return value
An Introduction to Programming with C++, Seventh Edition 21
Figure 10-14 Desk-check table after the declaration statement in the main function is processed
Figure 10-15 Desk-check table after the getAge function header is processed
An Introduction to Programming with C++, Seventh Edition 23
Figure 10-16 Desk-check table after the statements in the getAge function are processed
Figure 10-18 Desk-check table after the computer processes the displayAge function header
26
27
Figure 10-22 IPO chart information and C++ instructions for the salary program
An Introduction to Programming with C++, Seventh Edition 28
Figure 10-22 IPO chart information and C++ instructions for the salary program (contd.)
29
31
Figure 10-24 Desk-check table after the statements on lines 15 through 24 are processed
Figure 10-25 Desk-check table after the computer processes the getNewPayInfo function header
An Introduction to Programming with C++, Seventh Edition 32
Figure 10-26 Desk-check table after the computer processes the statements in the getNewPayInfo function body
34
Summary
All functions are either void or value-returning Value-returning functions return one value Void functions do not return a value Function header of a void function begins with the keyword void instead of a return data type Function body of a void function does not contain a return statement You call a void function by including its name and actual arguments in a statement
35
Summary (contd.)
A call to a void function appears as a statement by itself rather than as part of another statement Variables can be passed to functions either by value (the default) or by reference When a variable is passed by value, only a copy of the variables value is passed
Receiving function is not given access to the variable, so it cannot change the variables contents Computer uses data type and name of formal parameter to store a copy of the value
An Introduction to Programming with C++, Seventh Edition 36
Summary (contd.)
When a variable is passed by reference, the variables address in memory is passed
Receiving function can change variables contents Computer assigns name of formal parameter to memory location variable then has two names
To pass by reference you include the address-of operator (&) before the name of the formal parameter in function header If function appears below main, you must also include the & in the functions prototype
An Introduction to Programming with C++, Seventh Edition 37
Figure 10-31 Problem specification and a sample calculation for Lab 10-2
39
40
41
42
Objectives
Declare and initialize a one-dimensional array Enter data into a one-dimensional array Display the contents of a one-dimensional array Pass a one-dimensional array to a function Calculate the total and average of the values in a onedimensional array
Objectives (contd.)
Search a one-dimensional array Access an individual element in a one-dimensional array Find the highest value in a one-dimensional array Explain the bubble sort algorithm Use parallel one-dimensional arrays
Arrays
A simple variable (also called a scalar variable) is unrelated to any other variable in memory Sometimes variables are related to each other Easier and more efficient to treat these as a group A group of related variables with the same data type is referred to as an array
Arrays (contd.)
Storing data in an array increases the efficiency of a program
Data can be accessed from internal memory faster than it can be from a file on a disk Once stored in an array, data can be used as many times as necessary without having to enter it again
Variables in an array can be used like any other Most commonly used arrays in business applications are one-dimensional and two-dimensional
One-Dimensional Arrays
Variables in an array are stored in consecutive locations in computers internal memory Each variable in an array has the same name and data type You distinguish one variable in a one-dimensional array from another variable in the same array by using a unique integer, called a subscript A subscript indicates a variables position in the array and is assigned by the computer when the array is created
An Introduction to Programming with C++, Seventh Edition 6
Figure 11-3 Problem specification and IPO chart for the XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition 10
12
13
15
Figure 11-5 How to use an assignment statement to assign data to a one-dimensional array
An Introduction to Programming with C++, Seventh Edition 16
Figure 11-5 How to use an assignment statement to assign data to a one-dimensional array (cont.)
An Introduction to Programming with C++, Seventh Edition 17
Figure 11-6 How to use the extraction operator to store data in a one-dimensional array
18
Figure 11-6 How to use the extraction operator to store data in a one-dimensional array (cont.)
19
20
21
22
23
Figure 11-8 IPO chart information and C++ instructions for the XYZ Companys sales program
An Introduction to Programming with C++, Seventh Edition 24
26
Figure 11-11 Desk-check table after the array declaration statement is processed
Figure 11-12 Desk-check table after the initialization argument on line 15 is processed
An Introduction to Programming with C++, Seventh Edition 27
Figure 11-17 Desk-check table after for loop on lines 15-20 ends
An Introduction to Programming with C++, Seventh Edition 29
Figure 11-18 Desk-check table after the initialization argument on line 23 is processed
Figure 11-19 Desk-check table after the for loop on lines 23 through 27 ends
An Introduction to Programming with C++, Seventh Edition 30
31
Indicate that you are passing an array by entering formal parameters name and data type, followed by empty square brackets
Address-of operator (&) is not needed in function header or function prototype, since arrays are passed by reference by default
An Introduction to Programming with C++, Seventh Edition 32
33
Figure 11-21 Completed desk-check table for the XYZ Companys modified sales program
An Introduction to Programming with C++, Seventh Edition 35
36
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program
An Introduction to Programming with C++, Seventh Edition 37
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program (contd.)
An Introduction to Programming with C++, Seventh Edition 38
Figure 11-22 Problem specification, IPO chart information, and C++ instructions for the Moonbucks Coffee program (contd.)
An Introduction to Programming with C++, Seventh Edition 39
42
43
Figure 11-25 Problem specification, IPO chart information, and C++ instructions for the JK motors program
An Introduction to Programming with C++, Seventh Edition 44
Figure 11-25 Problem specification, IPO chart information, and C++ instructions for the JK motors program (contd.)
An Introduction to Programming with C++, Seventh Edition 45
47
48
49
Figure 11-28 Problem specification, IPO chart information, and C++ instructions for the hourly rate program
An Introduction to Programming with C++, Seventh Edition 50
Figure 11-28 Problem specification, IPO chart information, and C++ instructions for the hourly rate program (contd.)
An Introduction to Programming with C++, Seventh Edition 51
53
54
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program
An Introduction to Programming with C++, Seventh Edition 55
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition 56
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
57
Figure 11-31 Problem specification, IPO chart information, and C++ instructions for the random numbers program (contd.)
An Introduction to Programming with C++, Seventh Edition 58
59
62
Figure 11-34 Desk-check table after the for loop on lines 24 through 26 ends
An Introduction to Programming with C++, Seventh Edition 63
Figure 11-35 Desk-check table after the displayArray function header is processed
An Introduction to Programming with C++, Seventh Edition 64
Figure 11-37 Desk-check table after the declaration statements on lines 52 and 55 are processed
An Introduction to Programming with C++, Seventh Edition 66
Figure 11-38 Desk-check table showing the fourth elements value entered in the high variable
An Introduction to Programming with C++, Seventh Edition 67
68
69
70
Figure 11-40 Array values before, during, and after the bubble sort
71
Figure 11-42 Desk-check table after the declaration statements on lines 11 through 16 are processed
74
Figure 11-43 Desk-check table after nested loop is processed first time
75
Figure 11-44 Desk-check table after nested loop is processed second time
76
Figure 11-45 Desk-check table after nested loop is processed third time
77
Figure 11-46 Desk-check table after outer loop is processed first time
78
Figure 11-47 Desk-check table after the instructions on lines 21 and 23 are processed
An Introduction to Programming with C++, Seventh Edition 79
Figure 11-48 Desk-check table after the instructions in the nested loop are processed
An Introduction to Programming with C++, Seventh Edition 80
Figure 11-49 Desk-check table after the instructions in the nested loop are processed again
An Introduction to Programming with C++, Seventh Edition 81
83
Two arrays are referred to as parallel arrays if their elements are related by their position in the arrays
84
Figure 11-52 Problem specification and IPO chart information for the club membership program
An Introduction to Programming with C++, Seventh Edition 85
Figure 11-52 Problem specification and IPO chart information for the club membership program (cont.)
An Introduction to Programming with C++, Seventh Edition 86
Figure 11-53 IPO chart information and C++ instructions for the club membership program
87
Figure 11-53 IPO chart information and C++ instructions for the club membership program (cont.)
88
90
91
Summary
An array is a group of variables that have the same name and data type One- and two-dimensional arrays are the most common types Arrays are often used to store related data in internal memory: more efficient to access than from disk Must declare an array before using it After declaration, you can use an assignment statement or extraction operator to enter data into it
92
Summary (contd.)
Each element of a one-dimensional array is assigned a unique number, called a subscript First element is assigned a subscript of 0, second a subscript of 1, and so on Last subscript of a one-dimensional array is always one number less than the number of elements You refer to an element by the arrays name followed by the subscript in square brackets Parallel arrays are two or more arrays whose elements are related by their position in the arrays
An Introduction to Programming with C++, Seventh Edition 93
94
95
main function should display an error message when user enters a menu choice other than 1, 2, or 3 and should then display the menu again Test the program appropriately
96
97
98