Exhaustive & Repetitive Ch. 1-5; CS 1336 (C++)

Ace your homework & exams now with Quizwiz!

-named constant -const -uppercase

A ________ is like a variable, but its content is read-only and cannot be changed while the program is running. It looks just like a regular variable definition except that the word ________ appears before the data type name, and the name of the variable is written in all ___________ letters.

Statement

A complete instruction that causes the computer to perform some actions.

loop

A control structure that causes a statement or group of statements to repeat.

Psuedocode

A cross between human language and a programming language.

Hierarchy Chart

A diagram that graphically depicts the structure of a program.

Flowchart

A diagram that shows the logical flow of a program.

Stub

A dummy function used in place of an actual function -Include a message indicating it was called

Text file

A file that contains data that has been encoded as text, using a scheme such as ASCII or Unicode.

Binary File

A file that contains data that has not been converted to text.

Input File

A file that data is read from.

Output File

A file that data is written to.

<cmath>

A header file needed in order to work with some of the math library functions such as pow( )

<fstream>

A header file that contains all the declarations necessary for file operations.

1.18 Describe the difference between a key word and a programmer-defined symbol.

A key word has a special purpose and is defined as part of a programming language. A programmer-defined symbol is a word or name defined by the programmer.

1.20 Describe the difference between a program line and a statement.

A line is a single line as it appears in the body of a program. A statement is a complete instruction that causes the computer to perform an action. It may be written on 1 or more lines.

Literal

A literal is a piece of data that is written directly into a program's code. ex: number = 5; this statement assigned the literal value 5 to the variable number. Another common use of literals is to display something on the screen. Like "The value of number is" -Literals can be characters, strings, or numeric values.

The value of a default argument must be a(n) _________.

A literal value or a named constant

Nested Loop

A loop that is inside another loop.

Count-controlled loop

A loop that repeats a specific number of times. (for). It must posses three elements: 1. An initialized counter variable 2. Test the counter by comparing it to a max value. 3. Update the counter during each iteration.

Program

A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs.

Punctuation

A semicolon in C++ is similar to a period in English. It marks the end of a complete sentence (or statement, as it is called in programming).

Sentinel

A special value that marks the end of a list of values and cannot be mistaken as a member of the list.

endl;

A stream manipulator that starts a new line in cout.

___ is a dummy function that is called instead of the actual function it represents.

A stub

Running total

A sum of numbers that accumulates with each iteration of a loop.

Formal parameter

A variable declared in the function heading

Assuming dataFile is a file stream object, the statement: dataFile.close(); A. closes a file B. is legal but risks losing valuable data C. is illegal in C++ D. needs a filename argument execute correctly

A. closes a file

namespace std;

Accesses entities apart of the namespace standard.

An argument can also be called an?

Actual parameter or an actual argument

-Be careful not to reverse the beginning symbol with the ending symbol. -Be sure not to forget the ending symbol.

Advice When Using Multi-Line Comments:

File Stream Object

An *object* that is associated with a specific *file*, and provides a way for the program to work with that file.

-initialization -const -compiler

An ________ value must be given when defining a constant with the _______ qualifier, or an error will result when the program is compiled. A _________ error will also result if there are any statements in the program that attempt to change the value of a named constant.

Null Statement

An empty statement that does nothing.

Assignment (=)

An operator that copies the value on its right into the variable name on its left. i.e. number = 5;

changes

Another advantage to this approach is that widespread ________ can be easily made to the program.

free-flowing

Another aspect of programming style is how to handle statements that are too long to fit on one line. Because C++ is a _________ language, it is usually possible to spread a statement over several lines.

module

Another name for a function

arguments

Another name for parameters

The sizeof operator gives the size of?

Any data type or variable

1.10 Word processing programs, spreadsheet programs, e-mail programs, Web browsers, and game programs belong to what category of software?

Application software or application programs

ALU of the CPU

Arithmetic and Logic Unit. It is designed to perform mathematical operations.

Internally, the CPU consist of the _____ and the _____.

Arithmetic and Logic unit, Control Unit

1.3 Internally, the CPU consists of what two units?

Arithmetic and logic unit (ALU) and control unit

Null terminator/null character (\0)

Automatically placed at the end of string literals. Placed at the end of string literals to differentiate them from character literals.

This statement may be used to stop a loop's current iteration and begin the next one: A. break B. continue C. terminate D. reiterate

B. continue

Why is it easier to write a program in a high - level language then in machine language?

Because Machine Language consists of 1's and 0's. (0010011100101001)

1.21 Why are variables called "variable"?

Because their contents may be changed while the program is running.

2. Visualize the program running on the computer.

Before you create a program on the computer, you should first create it in your mind. Step 2 is the visualization of the program. Try to imagine what the computer screen looks like while the program is running. For instance, here is the screen produced by the pay-calculating program: How many hours did you work? 10 How much do you get paid per hour? 15 You earned $ 150 In this step, you must put yourself in the shoes of the user. What messages should the program display? What questions should it ask?

-addition -subtraction -multiplication -division -modulus

Binary Operators:

Expressions that have a true or false value

Boolean expressions

Numeric Data Types

Broken up into two types: integer and floating point.

operators

C++ offers a multitude of ________ for manipulating data.

The job of the _____ is to fetch instructions, carry out the operations commanded by the instructions, and produce some outcome or resultant information.

CPU

The job of the __________ is to fetch instructions, carry out the operations commanded by the instructions, and produce some outcome or resultant information.

CPU

5 major hardware components

CPU Main memory Secondary storage devices Input Output

Breaking out of a loop

Can use break to terminate execution of a loop -When used in an inner loop, break terminates that loop only. Execution continues with the outer loop -

#include

Causes the contents of another file to be inserted into the program. Must always contain the name of a file.

iostream

Contains file that allows C++ program to display output on the screen and read input from the keyboard.

Infinite Loop

Continues to repeat until the program is interrupted.

Two parts of the CPU

Control Unit & arithmetic and logic unit.

What happens when a function exits?

Control goes back to the function that called it.

Loop control variable

Controls the number of times that a loop iterates.

Coercion:

Conversion of an operand to another data type

Promotion:

Convert to a higher type

Demotion:

Convert to a lower type

Control Unit of a CPU

Coordinates all of the computer's operations. Determines where to get the next instruction and regulates other major components of the computer with control signals.

In a for statement, this expression is executed only once. A. validation B. null C. test D. initialization

D. initialization

Arguments

Data being sent to a function.

local declaration

Declaring a variable inside a function. That variable is accessible only in the function where it was declared.

count--

Decrement: count = count - 1

_________ arguments are passed to parameters automatically if no argument is provided in the function call.

Default

Floating Point Data Type

Define variables that can hold real numbers. Allows fractional values. Usually represented in E notation.

sizeof

Determine the size of a data type on any system.

Be careful not to use invalid subscripts. Why?

Doing so can corrupt other memory locations, crash program, or lock up computer, and cause elusive bugs.

What has the highest precedence for Logical Operators?

! has highest precedence, followed by &&, then ||

Preprocessor directives begin with?

#

Files: What is Needed

#include <fstream> ifstream - for input ofstream- for output fstream- for both -define file stream objects datatype variablename; ifstream infile;

The following program contains many syntax errors. Locate as many as you can. */ What's wrong with this program? */ #include iostream using namespace std; int main(); } int a, b, c \\ Define 3 integers a = 3 b = 4 c = a + b Cout >> "The value of c is " >> C; return 0; {

#include <iostream> using namespace std; int main() { int a, b, c; // Define 3 integers a =3; b =4; c= a + b; cout << " The value of c is " << c; return(0);

Write the necessary preprocessor directive to enable the use of the C++ string class .

#include <string>

if the sub-expression on the left of the ________ logical operator, the right sub-expression is not checked

&&

the ______ logical operator works best when testing a number to determine if it is within a range

&&

Write a character literal representing the (upper case) letter A .

'A'

In prefix mode:

(++val, --val) the operator increments or decrements, then returns the value of the variable

When do you use a for loop?

*The for loop is a pretest loop* -Built-in expressions for initializing, testing, and updating -Situations where the exact number of iterations is known

When do you use a while loop?

*The while loop is a conditional pretest loop* - Iterates as long as a certain condition exits - Validating input - Reading lists of data terminated by a sentinel

Floating-Point Literals can be represented in?

- Fixed point(decimal) notation: 31.4159 - E notation: 3.14159E1

Identifiers

- letters, digits, underscore - cannot begin with a digit - Constants all UPPER_CASE

Type Casting Standards:

-C-Style cast: data type name in () cout << ch << " is " << (int)ch; -Prestandard C++ cast: value in () cout << ch << " is " << int(ch); -Both are still supported in C++, although static_cast is preferred

Reference Variable Rules

-Each reference parameter must contain & -Space between type and & is unimportant -Must use & in both prototype and header -Argument passed to reference parameter must be a variable - cannot be an expression or constant -Use when appropriate - don't use when argument should not be changed by function, or if function needs to return only 1 value

What must the compiler know about the function before it is called?

-Name -Return type -Number of parameters -Data type of each parameter

Comments

-Notes of explanation that document lines or sections of a program. -Part of the program, but the complier ignores them. -Intended for people who may be reading the source code. -Can also be used to explain complex procedures in your code.

cmath header file:

-Take double as input, return a double Commonly used functions: sin Sine cos Cosine tan Tangent sqrt Square root log Natural (e) log abs Absolute value (takes and returns an int)

Sentinels

-a special value that marks the end of a list of data. -can be used to terminate if you dont know how many times values will be entered -Should be special value that cannot be confused with a valid value cout << "Enter the number of points your team scored, when finished enter -1"; cin >> points; while (points!= -1) { }

The floating-point data types are?

-float -double -long double - Hold real numbers - Stored in a form similar to scientific notation - All floating-point numbers are signed

variables (int command)

-int number; This is called a variable definition. It tells the compiler the variable's name and the type of data it will hold. Notice that the definition gives the data type first, then the name of the variable, and ends with a semicolon. This variable's name is number. The word int stands for integer, so number may only be used to hold integer numbers. -number = 5; This is an assignment statement, and the = sign is called the assignment operator. This operator copies the value on its right (5) into the variable named on its left (number). This line does not print anything on the computer's screen. It runs silently behind the scenes, storing a value in RAM. After this line executes, number will be set to 5.

program contains:

-key words -programmer-defined identifiers -operators -punctuation -syntax

Hierarchy of Types:

-long double -double -float -unsigned long -long -unsigned int -int *Ranked by largest number they can hold*

Global variables (not constants) are automatically initialized to?

0 (numeric) or NULL (character) when the variable is defined.

How many bytes are needed to store: "" ?

1

How many bytes are needed to store: 'n' ?

1

What is the output of the following code? int w = 98; int x = 99; int y = 0; int z = 1; if (x >= 99) { if (x < 99) cout << y << endl; else cout << z << endl; } else { if (x == 99) cout << x << endl; else cout << w << endl; } 98 99 0 1

1

3 ways to use a function's value

1) Save it for future calculation 2) Use the value in a calculation 3) Print the value

Possible default values

1) constants 2) global variables 3) function calls

For loop

1. Initializes a counter variable; 2. Tests an Expression; 3. Updates the Expression (Best used if testing for "false").

File Use in a Program

1. Open the file 2. Process the file 3. Close the file

2.17 What will the following code display? int number; number = 3.625; cout << number;

3

you use the ______ operator to determine whether one string object is greater than another string object

>

1.28 What is pseudocode?

A "language" that is a cross between human language and programming languages that is used to express algorithms.

Library Function

A "routine" that performs a specific operation.

Input values should always be checked for: a. Appropriate range b. Reasonableness c. Division by zero, if division is taking place d. All of the above e. None of the above

d. All of the above

The total number of digits that appear before and after the decimal point is sometimes referred to as: Select one: a. floating points b. significant digits c. precisions d. B and C e. None of these

d. B and C (significant digits and precisions)

What is the output of this code? string s = "hello"; s *= s; cout << s << endl; a. hello b. hello hello c. hellohello d. This code will not compile

d. This code will not compile

This statement will pause the screen, until the [Enter] key is pressed. a. cin.getline(); b. cin.input(); c. cin; d. cin.get();

d. cin.get();

The strcmp function requires which library to be included? a. cmath b. iostream c. string d. cstring

d. cstring

What will be the output of the following code segment after the user enters 0 at the keyboard? int x = -1; cout << "Enter a 0 or a 1 from the keyboard: "; cin >> x; if (x) cout << "true" << endl; else cout << "false" << endl; a. x b. true c. Nothing will be displayed d. false

d. false

Every complete C++ program must have a ________. Select one: a. symbolic constant b. cout statement c. comment d. function named main e. preprocessor directive

d. function named main

5.8.. #51174 Define a function called min that takes two parameters containing integer values and returns the smaller integer of the two. If they have equal value, return either one.

def min(int1,int2): >>> if int1<int2: >>> >>> return int1 >>> elif int2<int1: >>> >>> return int2 >>> else: >>> >>> return int1 or int2

==

equal to

cout

ex: cout << "Programming is great fun!"; This line displays a message on the screen. You will read more about cout and the << operator later in this chapter. The message "Programming is great fun!" is printed without the quotation marks. In programming terms, the group of characters inside the quotation marks is called a string literal, a string constant, or simply a string.

Every C++ program must have?

function main

void functions

functions that do not have a data type

Value-returning functions

functions that have a data type

value- returning functions

functions that have a return type

external variable

global variable declared after the definition of a given function. Allows the function to access it using keyword "extern" function must NOT contain any identifiers with the same name as the global variable.

>

greater than

>=

greater than or equal to

_____ languages are close to the level of humans in terms of readability.

high-level

Write an if statement that prints the message "The number is valid" if the variable speed is within the range 0 through 200

if (speed >= 0 && speed <= 200) cout << "The number is valid.";

What header file must be included in programs using cin?

iostream

a variable with _____ scope is only visible when the program is executing in the block containing the variables definition

local

_____ languages are close to the level of the computer.

low-level

Write a statement to set the value of num to 4 (num is a variable that has already been declared ).

num = 4;

| |

or ; A or B or both

Two or more functions may have the same name, as long as their _________ are different.

parameter lists

Computer Science

science of problem solving involving a computer

the part of the program that has access to the variable

scope

Algorithm

strategy for solving a problem

What is the value of the following expression? true && true true false -1 +1

true

Postfix

val++, val--; -the operator returns the value of the variable THEN increments/decrements

Coding

Expressing algorithms in a programming language

Boolean Expressions

Expressions that are either true or false.

T or F Variable names may begin with a number

F

T or F You cannot initialize a named constant that is declared with the const modifier

F

Arithmetic operators that share the same precedence have right to left associativity. T/F

False

If you use a C++ key word as an identifier, your program will compile, link, but not execute. True False

False

If you want to know the length of the string that is stored in a string object, you can call the object's size member function. T/F

False

T/F Programs are commonly referred to as "hardware".

False

The fixed manipulator causes a number to be displayed in scientific notation. T/F

False

You must furnish an argument with a function call. T/F

False

A _____ is a diagram that graphically illustrates the structure of the program.

Flowchart

Value-returning function

Functions that use the "return" statement to return a value of a specific data type to the main function

_________ variables are defined outside all functions and are accessible to any function within their scope.

Global

_________ variables provide an easy way to share large amounts of data among all the functions in a program.

Global

Short Circuit Evaluation

If the sub-expression on the left side of an && operator is false, the expression on the right side will not be checked. If the sub-expression on the left side of an || operator is true, the expression on the right will not be checked.

count++

Increment: count = count + 1

Variable Definition

Indicates the variable's name and the type of data it will hold.

_____ is information a program gathers from the outside world.

Input

__________ is information a program gathers from the outside world.

Input

1.24 What are the three primary activities of a program?

Input, processing, and output

Where do you define parameter variables?

Inside the parentheses of a function header.

2.25 Is the following assignment statement valid or invalid? If it is invalid, why? 72 = amount;

Invalid. The value on the left of the = operator must be an 1value, such as a variable name.

Object-oriented Programming

Is centered on the object. An object is a programming element that contains data and the procedures that operate on the data. It is a self-contained unit.

Single precision

Is usually 4 bytes in size (float data type).

(Computer) Input Device

Keyboard, mouse, scanner, microphone, etc

Type Case Expression

Lets you manually promote or demote a value.

setprecision( )

Limits the number of significant digits

A(n) _________ variable is de ned inside a function and is not accessible outside the function.

Local

4. Check the model for logical errors

Logical errors, also called logic errors, are mistakes that cause a program to produce erroneous results. Examples of logical errors would be using the wrong variable's value in a computation or performing order-dependent actions in the wrong order. Once a model of the program has been created, it should be checked for logical errors.

Do changes to a function parameter always affect the original argument as well?

No, not in if called by value.

Is this function prototype legal: int funcTwo(int length = 1, int width, int height = 1);

No. All default parameters must be on the right hand side of the formal parameter list.

Syntax Error

Not following rules of language (missing semi-colon, etc.) Program will not compile.

8. Link the program to create an executable file

Once the source code compiles with no errors, it can be linked with the libraries specified by the program #include statements to create an executable file. If an error occurs during the linking process, it is likely that the program has failed to include a needed library file. The needed file must be included and the program relinked.

Unsigned Data Types

Only store non-negative values.

1.19 Describe the difference between operators and punctuation symbols.

Operators perform operations on one or more operands. Punctuation symbols mark the beginning or ending of a statement, or separate items in a list.

Operators

Perform operations on one or more operands. (+, -, *, /)

Computers can do many different jobs because they can be __________.

Programmed

Application Software

Programs that make a computer useful for everyday tasks. (MS Word, MS Powerpoint, etc)

reverse() member function is used for?

Reverse the order of the elements in a vector Ex: vec1.reverse();

STL stands for?

Standard Template Library

-compiler's -syntax -object

The _________ job is to check for _________ errors and, if there are not, generate _________ code.

What must NOT be included in a function call?

The data types of the actual parameters

Execute

The electronic signal (the instructions) from the CPU is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation.

-scope -definition

The first rule of ________ you should learn is that a variable cannot be used in any part of the program before the _________.

The _________ is the part of a function definition that shows the function name, return type, and parameter list.

The function header

Operating System

The most fundamental set of programs on a computer. Controls the internal operations of the computers hardware, manages all devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer.

What must be included in a function call?

The name of the function and its actual parameters

scope

The part of the program that has access to the variable and where the variable may be used. Every variable has one.

Scope

The part of the program where the variable may be used.

Hardware

The physical components that a computer is made of. Such as the CPU, Main Memory, Secondary Storage, Input Devices & Output devices.

Input validation

The process of inspecting data given to a program by a user and determining if it is valid.

1.25 What four items should you identify when defining what a program is to do?

The program's purpose, the information to be input, the processing to take place, and the desired output

Procedural Programming

The programmer constructs procedures (or functions). The procedures are collections of programming statements that perform a specific task.

Priming Read

The read operation that takes place just before a loop. It provides the first value for the loop to test.

multi-line comment

The second type of comment in C++ is the ___________.

Formatting

The way a value is printed.

-variations -initialize

There are always _________ on a theme. C++ allows you to define several variables and only ________ some of them.

Switch Statement

This statement lets the value of a variable or expression determine where the program will branch.

Microprocessor

Today's CPU's. Small chips that can be held in the palm of your hand.

Compiler

Translates source code into machine language. A compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language).

A static variable that is defined within a function is initialized only once, the first time the function is called. T/F

True

An example of a secondary storage device is a hard drive True False

True

An expression that has any integer value other than 0 is considered true by an if statement. T/F

True

As a rule of style, when writing an if statement you should indent the conditionally-executed statements. True False

True

Both of the following if statements perform the same operation. if (sales > 10000) commissionRate = 0.15; if (sales > 10000) commissionRate = 0.15; True False

True

T/F The term "bit" stands for binary digit.

True

You may use the exit() function to terminate a program, regardless of which control mechanism is executing T/F

True

You should be careful when using the equality operator to compare floating point values because of potential round-off errors. True False

True

when using the equality operator to compare integer values there will be potential round-off errors. True False

True

unsigned short int

Typically 2 bytes in size. Ranges from 0 to +65,535.

The negation operator is?

Unary

( )

Used in naming a function, such as main.

Arguments

Values passed to function

Type coercion

When C++ is working with an operator, it strives to convert the operands to the same type.

String Literals

When double quotation marks are placed around a word. They are sent to cout and printed exactly as they appear. Series of characters stored in consecutive memory locations.

-compiler -characters -compiler

When the _________ reads a program it processes it as one long stream of _________. The _________ doesn't care that each statement is on a separate line, or that spaces separate operators from operands.

fixed-point notation

When the fixed manipulator is used, all floating-point numbers that are subsequently printed will be displayed with the number of digits to the right of the decimal point specified by the setprecision manipulator.

Round-Off Error

When two values are different, but because of rounding are comparing to be of equal value. (This happens mostly with floating-point numbers. You should use < or > rather than ==).

11. Validate the results of the program

When you believe you have corrected all errors, enter test data to verify that the program solves the original problem.

Overuse of global variables can lead to problems.

Will make debugging and understanding the program difficult

Random Access File or Direct Access File

You can jump directly to the desired data in this type of file without reading the data that comes before it.

What is the one restriction on default values?

You cannot assign a constant value to a reference parameter

-unary -operand

______ operators only require a single ________.

What is the value stored at x, given the statements: int x; x = 3 / static_cast<int>(4.5 + 6.4); a. 0 b. 0.3 c. 0.275229 d. 3.3

a. 0

Thhis stream manipulator forces cout to print the digits in fixed-point notation. a. fixed b. setw(2) c. setfixed(2) d. setprecision(2)

a. fixed

Running Totals

accumulated sum of numbers from each repetition. an accumulator holds a running total sum += num;

&&

and; both the requirements must be met

Parallel Arrays

arrays of the same length but with different component data types

In C++ the = operator indicates: equality assignment subtraction negation None of these

assignment

If you place a semicolon after the statement: if (x < y) a. The compiler will interpret the semicolon as a null statement b. The code will not compile c. The if statement will always evaluate to false d. All of the above e. None of the above

b. The code will not compile

This manipulator is used to establish a field width for the value immediately following it. a. set_field b. setw c. iomanip d. field_width

b. setw

top-down design

begins with overall task and then refines it into smaller subtasks and each subtask is refined into smaller subtasks and so on, used in hierarchy charts

bit

binary digit

bit

binary digit, tiny electrical components that can hold either a positive or negative charge

useful for evaluating conditions that are either true or false

bool variables

for an if statement to conditionally execute a group of statements, the statements must be enclosed in a set of

braces

Without this statement appearing in a switch construct, the program "falls through" all of the statements below the one with the matching case expression. break exit switch scope None of these

break

a program will "fall through" a case section if it is missing the _______ statement

break

In memory, C++ automatically places a ________ at the end of string literals. Select one: a. Semicolon b. Quotation marks c. Null terminator d. Newline escape sequence e. None of these

c. Null terminator \0

Declare a character variable named c .

char c;

high-level language

closer to human language

compiler

converts source program into machine instructions

the ______ logical operator has higher precedence than the other logical operators

!

static local variables

-retain their contents between function calls -are defined and initialized only the first time function is executed -0 is the default initialization value

The variable receiving the value must appear on the left side of the = operator. WHAT DOESNT WORK?

// ERROR 12 = item;

2.21 Assuming the char data type uses 1 byte of memory, how many bytes do each of the following literals use? 'Q' "Q" "Sales" '\n'

1 byte, 2 bytes, 6 bytes, 1 byte

2.27 What will be assigned to x in each of the following statements? A) x = 8 + 3; B) x = 8 - 3; C) x = 8 * 3; D) x = 8 % 3;

11, 5, 24, 2

Write a literal representing the largest character value . Suppose we are using unsigned one-byte characters .

255

2.16 How would the following number in scientific notation be represented in E notation? 6.31 x 10^17

6.31E17

Write a literal representing the character whose ASCII value is 65 .

65

Byte

8 bits

stream insertion operator

<<; takes information from a variable and puts it into a stream

Flag

A boolean (or integer) variable that signals when a condition exists.

function stub

A function that is not fully coded, used for debugging.

1.5 What is a memory address? What is its purpose?

A memory address is a unique number assigned to each storage location in memory. Its purpose is to allow data stored in RAM to be located.

Program

A set of instructions that a computer follows to perform a task.

Program

A set of instructions that specifies all the steps necessary to solve the problem

Continue Statement

A statement that causes a loop to stop its current iteration and begin the next one.

What is the output of the following code segment? n = 1; for ( ; n <= 5; ) { cout << n << ' '; n++; } A. 1 2 3 4 5 B. 2 3 4 5 6 C. 1 1 1 ... and on forever D. 1 2 3 4

A. 1 2 3 4 5

Look at the following function prototype. int myFunction(double); What is the data type of the function's return value? A. int B. double C. void D. Can't tell from the prototype

A. int

The while loop is this type of loop. A. pre-test B. limited C. post-test D. infinite

A. pre-test

Where MUST default parameters be placed in the formal parameter list?

All default parameters must be the right-most parameters in the formal parameter list

Input values should always be checked for: appropriate range reasonableness division by zero, if division is taking place All of these None of these

All of these

string class

Allows the programmer to create a string type variable.

Divide and Conquer

Also known as top-down design. When a task is broken down into subtasks.

style

Although you are free to develop your own _________, you should adhere to common programming practices. By doing so, you will write programs that visually make sense to other programmers.

rvalue

Any expression that has a value.

Values that are sent into a function are called _________.

Arguments

To write data to a file, you define an object of this data type. A. fstream B. ofstream C. outputFile D. ifstream

B. ofstream

Why is it easier to write a program in a high - level language then in machine language?

Because Machine Language consists of 1's and 0's. (0010011100101001) and high-level language is similar to human language

Using the string class

Because a char variable can store only one character in its memory location, another data type is needed for a variable able to hold an entire string. Although C++ does not have a built-in data type able to do this, Standard C++ provides something called the string class that allows the programmer to create a string type variable. 1. The first step in using the string class is to #include the string header file. This is accomplished with the following preprocessor directive: #include <string> 2. The next step is to define a string type variable, called a string object. Defining a string object is similar to defining a variable of a primitive type. For example, the following statement defines a string object named movieTitle. string movieTitle; 3. You can assign a string literal to movieTitle with the assignment operator, like this. movieTitle = "Wheels of Fury"; 4. And you can use cout to display the value of the movieTitle object, as shown here. cout << "My favorite movie is " << movieTitle << endl;

When do preprocessor directives execute?

Before the compiler compiles your program

-auto -initialization

C++ 11 introduces an alternative way to define variables, using the __________ key word and an _________ value.

When you use a value as an array subscript...?

C++ does not check it to make sure it is a valid subscript -In other words, you can use subscripts that are beyond the bounds of the array.

To read data from a file, you define an object of this data type. A. ofstream B. outputFile C. ifstream D. fstream

C. ifstream

floor function

Calculates largest whole number that is less than or equal to its argument.

Char hold what?

Characters or very small integer values -Usually 1 byte of memory -Numeric value of character from the character set is stored in memory -Enclosed in single quote marks

Iteration

Each repetition of a loop.

{ }

Encloses a group of statements, such as the contents of a function.

swap(vec2) member function is used for?

Exchange the contents of two vectors Ex: vec1.swap(vec2);

Conditional Loop

Executes as long as a particular condition exists.

T/F Machine language is an example of a high-level language.

False

T/F Pseudocode is a form of program statement that will always evaluate to "false."

False

T/F The preprocessor executes after the compiler.

False

The C++ compiler has a built-in safety mechanism to prevent while blocks from entering an endless loop. T/F

False

The following code correctly determines whether x contains a value in the range of 0 through 100. if (x >= 0 && <= 100) True False

False

This code compiles without errors: int main () { int x = 3; if( x > 2 ) { int y = 0; } int x = 3; T/F

False

When a function is called, flow of control moves to the function's prototype. T/F

False

When a program uses the setw manipulator, the iosetwidth header file must be included in a preprocessor directive. T/F

False - Uses <iomanip>

% requires integers:

For both operands

A parameter can also be called a?

Formal parameter or a formal argument

-three -unary -binary -ternary

Generally, there are _______ types of operators: __________, ___________, and _________. These terms reflect the number of __________ an ____________ requires.

String literal/string constant

Group of characters inside quotation marks.

A(n) __________ is a diagram that graphically illustrates the structure of a program.

Hierarchy chart

__________ languages are close to the level of humans in terms of readability.

High-level languages

Syntax Errors

Illegal uses of key words, operators, punctuation and other language elements.

-assignment statement - -operator

In an ____________, C++ requires the name of the variable receiving the assignment to appear on the ________ side of the _____________.

loop header

It consists of the key word (while/for) followed by an expression enclosed in parenthesis.

What is the advantage of breaking your application s code into several small procedures?

It makes the program easier to manage.

Using cin with the >> operator to input strings can cause problems:

It passes over and ignores any leading whitespace characters (spaces, tabs, or line breaks) *To work around this problem, you can use a C++ function named getline.*

What does the auto key word tell the compiler to do?

It tells the compiler to determine the variable's data type from the initialization value -auto interestRate= 12.0; - double -auto stockCode = 'D'; - char -auto customerNum = 459L; -long

1.30 Describe what a compiler does with a program's source code.

It translates each source code statement into statements into the appropriate machine language statements.

When a function uses a mixture of parameters with and without default arguments, the parameters with default arguments must be defined _________.

Last

What is the difference between a syntax error and a logical error?

Logical errors are mistakes that cause a program to produce erroneous results. Examples or logical errors would be using the wrong variable's value in a computation or performing order-dependent actions int the wrong order. A syntax error is an error in the source code of a program. Since computer programs must follow strict syntax to compile correctly, any aspects of the code that do not conform to the syntax of the programming language will produce a syntax error.

__________ languages are close to the level of the computer.

Low-level language

Object Code

Machine Code. Machine language instructions..

_____ is the only language computers really process.

Machine Language

-single-line -multi-line -convenience

Many programmers use a combination of ________ comments and ___________ comments in the programs. _________ usually dictates which style to use.

Punctuation Characters

Mark the beginning or ending of a statement, or seperate items in a list.

-forward slash followed by an asterick -asterick followed by a forward slash

Multi-line comments start with a ________ and end with _______. Everything between these markers is ignored.

Programmer-Defined Identifiers

Names made up by the programmer that refer to variables or programming routines.

6. Compile the source code

Next the saved source code is ready to be compiled. The compiler will translate the source code to machine language.

Does this line contain a valid comment? /* This is a //*// First Rate Program //*//

No

2.11 Is the variable name "Sales" the same as "sales"? Why or why not?

No, variable names are case sensitive

Can void function calls be used in expressions?

No. Since the call returns no value, a void call must be a stand-alone statement.

Is this a legal function overload: (1) void interest (int x, double y) (2) double interest (int base, double power)

No. There are the same number of formal parameters, and they have the exact same data types

cout continued

On modern computers, running graphical operating systems such as Windows or Mac OS, console output is usually displayed in a window such as the one shown in Figure 2-1. C++ provides an object named cout that is used to produce console output. (You can think of the word cout as meaning console output.) - cout is classified as a stream object, which means it works with streams of data. To print a message on the screen, you send a stream of characters to cout. - The << operator is used to send the string "Programming is great fun!" to cout. When the << symbol is used this way, it is called the stream-insertion operator. The item immediately to the right of the operator is inserted into the output stream that is sent to cout to be displayed on the screen.

portability

One of the problems of ___________ is the lack of common sizes of data types on all machines.

2.6 Which of the following are legal C++ assignment statements? a. a = 7 b. 7 = a c. 7 = 7

Only statement a is legal. The left-hand side of an assignment statement must be a variable, not a literal.

1.7 What are the two general categories of software?

Operating systems and application software

_____ are characters or symbols that perform operations on one or more operands.

Operators

__________ are characters or symbols that perform operations on one or more operands.

Operators

_____ is information a program sends to the outside world.

Output

__________ is information a program sends to the outside world.

Output

output - using the cout command

Output is information that a program sends to the outside world. It can be words or graphics displayed on a screen, a report sent to the printer, data stored in a file, or information sent to any output device connected to the computer. cout << "How many hours did you work? "; cout << "How much do you get paid per hour? "; cout << "You have earned $" << pay << endl; Lines 10, 14, and 21 all use the cout (pronounced "see out") object to display messages on the computer's screen.

Default parameter

Parameter that is initialized in the formal parameter list. If no value is given for that parameter, the initialized value is used.

Special variables that hold copies of function arguments are called _________.

Parameters

If you are writing a function that accepts an argument and you want to make sure the function cannot change the value of the argument, what do you do?

Pass by value

!

Performs a logical NOT operation. It takes an operand and reverses its truth or falsehood.

Utility Program

Performs a specialize task that enhances the computers operation or safeguards data. (Virus scanners, data back-up programs, etc.

power function

Performs operation x^y Syntax: pow(x,y)

Literal

Piece of data that is written directly into a program's code. Common use is to assign a value to a variable.

How to differentiate global identifier "cost" from local identifier "cost"

Place :: before the global identifier cost -- local identifier ::cost -- global identifier

Identifier

Programmer-Defined name that represents some element of a program (such as variable names).

Since computers can't be programmed in natural human language, algorithms must be written in a(n) __________ language.

Programming language

-identifiers -spaces -tabs -blank lines -punctuation

Programming styles refers to the way a programmer uses _________, _________, _________, _________, and _________ characters to visually arrange a program's source code. These are some, but not all, of the elements of programming style.

Main Memory

RAM or Random Access Memory.

RAM

Random Access Memory

Preprocessor

Reads source code, searching for lines that begin with the # symbol, and then modifying the source code.

Another name for Key words is?

Reserved words

capacity() member function is used for?

Returns the maximum number of elements a vector can store without allocating more memory Ex: maxElements = vec1.capacity();

at(i) member function is used for?

Returns the value of the element at position i in the vector Ex: cout << vec1.at(i);

Syntax

Rules that must be followed when constructing a program.

Scope of a function name

Same as the scope of a global identifier. same rules apply.

Secondary storage (hard drive or disk drive)

Secondary storage is a type of memory that can hold data for long periods of time—even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded into main memory as needed. The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a disk drive mounted inside their case.

Every Complete statement ends with ?

Semicolon

cin.ignore()

Skips next value

bool Data Type

Small integer variables that holds true or false values.

Bool variables are stored as what?

Small integers, so 1 for true and 0 for false

Steps to get from Source Code to Executable Code

Source Code ->Preprocessor=Modified Source Code -> Compiler=Object Code(Machine Language) -> Linker -> Executable.

1.16 Explain what is stored in a source file, an object file, and an executable file.

Source file: Contains program statements written by the programmer. Object file: Contains machine language instructions generated by the compiler Executable file: Contains code ready to run on the computer. Includes the machine language from an object file and the necessary code from library routines.

How would a static local variable be useful?

Static variables are not destroyed when a function returns. They exist for the lifetime of the program even though their scope is only in the function.

Variables

Store and work with data in the computer's memory. With no limit as to how many characters can be used.

Character Literals (char letter;)

Store one character enclosed in single quotation marks. Not compatible with strings since they only store one character.

What is the difference between a syntax error and a logical error?

Syntax Errors are illegal uses of key word, operators, punctuation, and other language elements. Logical Errors are mistakes that cause the program to produce erroneous results.

What type of software controls the internal operations of the computers hardware?

System Software

T or F A variable must be defined before it can be used?

T

auto (key word)

Tells the compiler to determine the variable's data type from the initialization value. Intended to simplify the syntax of declarations that are more complex.

Pretest Loop

Tests its expression before each iteration. (while & for).

1.14 What does portability mean?

That a program may be written on one type of computer and run on another type

Fetch

The CPU's control unit fetches, from main memory, the next instruction in the sequence of program instructions.

-= -assignment operator

The _____ symbol is called the __________.

-auto -initialization

The ______ key word tells the complier to determine the variable's data type from the ________ value.

-auto -syntax

The _______ key word is intended to simplify the _______ of declarations that are more complex.

-name -operator

The _______ of the data type or variable is placed inside the parentheses that follow the _________.

-complier -error

The _______ reads your program from top to bottom. If it encounters a statement that uses a variable before the variable is defined, an _______ will result. To correct the program, the variable definition must be put before any statement that uses it.

-assignment statement -rvalue -lvalue

The ________ takes the value of the ______ and puts it in the memory location of the object identified by the _________.

addition

The _________ operator returns the sum of its sum operands.

-syntax -key words -semicolons -commas -braces

The _________ rules of C++ dictate how and when to place _________, _________, _________, _________, and other components of the language.

-multi-line -single-line

The __________ comment is inconvenient for writing _________ comments because you must type both a beginning and ending comment symbol.

bool data type

The bool data type allows you to create variables that hold true or false values. Although it appears that it is storing the words true and false in this variable, it is actually storing 1 or 0. This is because true is a special integer variable whose value is 1 and false is a special integer variable whose value is 0, as you can see from the program output. 1 // This program uses Boolean variables. 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 bool boolValue; 8 9 boolValue = true; 10 cout << boolValue << endl; 11 12 boolValue = false; 13 cout << boolValue << endl; 14 return 0; 15 } Program output: 1 0

1.2 List the five major hardware components of a computer system.

The central processing unit (CPU), main memory (RAM), secondary storage devices, input devices, and output devices

Char Data Type

The char data type is used to store individual characters. A variable of this type can hold only a single character and, on most systems, uses just one byte of memory. ex: char letter = 'A'; Notice that while a character literal is enclosed in single quotation marks, a string literal is enclosed in double quotation marks.

Object File

The file machine code or object code is stored in. This is produced by the compiler.

Source File

The file source code is saved in.

Function prototype

The function heading without the body, terminated by a semicolon.

-right -= -rvalue

The operand on the _______ side of the _______ symbol must be an ________.

1.8 What fundamental set of programs controls the internal operations of the computer's hardware?

The operating system

Postfix Mode

The operator is placed after the variable. The increment or decrement will happen last.

Prefix Mode

The operator is placed before the variable. The increment or decrement will happen first.

Central Processing Unit/CPU

The part of a computer that actually runs programs.

1.15 Explain the operations carried out by the preprocessor, compiler, and linker.

The preprocessor reads the source file, searching for commands that begin with the # symbol. These are commands that cause the preprocessor to modify the source file in some way. The compiler translates each source code instruction into the appropriate machine language instruction and creates an object file. The linker combines the object file with necessary library routines to create an executable file.

body of a loop

The statement that is repeated if the condition is true.

-operator -unsigned

This ________ can be invoked anywhere you can use an ________ integer, including in mathematical operations.

-// -multi-line comment -comment

Unlike a comment started with ________. A ____________ can span several lines. This makes it more convenient to write large blocks of __________ because you do not have to mark every line.

Negation operator

Using the minus sign (-) prior to a number to indicate a negative value.

long int

Usually 4 bytes in size. Ranges from -2,147,483,648 to +2,147,4833,647.

Source Code Translation

When a C++ program is written, it must be typed into the computer and saved to a file. A text editor, which is similar to a word processing program, is used for this task. The statements written by the programmer are called source code, and the file they are saved in is called the source file. During the first phase of translation, a program called the preprocessor reads the source code looking for commands or directives to follow. During the next phase the compiler steps through the preprocessed source code, translating each source code instruction into the appropriate machine language instruction. This process will uncover any syntax errors that may be in the program. If the program is free of syntax errors, the compiler stores the translated machine language instructions, which are called object code, in an object file.

Promoted

When a value is converted to a higher data type.

Closing files

When finished using the file, close it with the close member function: infile.close(); outfile.close();

different formal parameter lists

When two or more functions with the same name have a different number of formal parameters, or if they have the same number of parameters, the data type of the parameters differs in at least one position

Integer Division

When you divide an integer by another integer in C++, the result is always an integer.

When is function overloading used?

When you need to perform the same action for different sets of data.

Key Words

Words that have a special meaning that may only be used for their intended purpose. Also known as reserved words.

The character escape sequence to represent a backslash is:

\\

nested block

a block declared within another block

Variables

a variable is a named storage location for holding data. Variables allow you to store and work with data in the computer's memory. ex: 1 // This program has a variable. 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 int number; 8 9 number = 5; 10 cout << "The value of number is " << number << endl; 11 12 number = 7; 13 cout << "Now the value of number is " << number << endl; 14 15 return 0; 16 } output: The value of number is 5 Now the value of number is 7

actual parameter

a variable or expression listed in a call to a function

Counters

a variable that is incremented or decremented each time a loop repeats. must be initializes before entering loop

What is the output of the following code? unsigned short int i = 0; i--; cout << i << endl; a. 65535 b. This code will not compile c. 0 d. -1

a. 65535

Assuming you are using a system with 1-byte characters, how many bytes of memory will the following string literal occupy? "William" Select one: a. 8 b. 14 c. 7 d. 1

a. 8

Relational operators allow you to ________ numbers. a. Compare b. Add c. Multiply d. Average

a. Compare

These are data items whose values do not change while the program is running. Select one: a. Literals b. Variables c. Comments d. Integers e. None of these

a. Literals

Which character signifies the beginning of an escape sequence? Select one: a. \ b. # c. { d. / e. //

a. \

When using the sqrt function you must include this header file. a. cmath b. cstring c. iomanip d. cstdlib e. iostream

a. cmath

During which stage does the central processing unit retrieve from main memory the next instruction in the sequence of program instructions? a.fetch b.decode c.execute d.portability stage e.None of the above

a. fetch

push_back() member function is used for?

add element to a full array or to an array that had no defined size: Ex: scores.push_back(75);

A statement that starts with a # symbol is called a: Select one: a. Comment b. Function c. Preprocessor directive d. Key word e. None of these

c. Preprocessor directive

A program has the following variable definitions. long miles; int feet; double inches; Write a single cin statement that reads a value into each of the variables.

cin >> miles >> feet> inches;

procedures

collections of programming statements that perform a specific task

linker

combines the object file with the necessary library routines

5.7..#51147 Assume that to_the_power_of is a function that expects two int parameters and returns the value of the first parameter raised to the power of the second parameter. Write a statement that calls to_the_power_of to compute the value of cube_side raised to the power of 3 and that associates this value with cube_volume. Instructor Notes: Write a statement that calls the function to_the_power_of, passing the parameters cube_side and 3, assigning the result to a variable cube_volume. KJ

cube_volume = to_the_power_of(cube_side,3)

What value is assigned to x after the following assignment statement is executed? int x = -3 + 4 % 6 / 5; Select one: a. 2 b. 0 c. 1 d. -3

d. -3

5.8..#51140 Write the definition of a function add which receives two parameters containing integer values and returns their sum.

def add(int1,int2): >>> result=int1+int2 >>> return result

5.2 .#51136 Write a definition of the function printDottedLine, which has no parameters and doesn't return anything. The function prints to standard output a single line consisting of 5 periods (".").

def printDottedLine(): >>> print(".....") **Remember to tab (>>>) or space

5.8..#51154 Define a function called signOf that takes a parameter containing an integer value and returns a 1 if the parameter is positive, 0 if the parameter is 0, and -1 if the parameter is negative.

def signOf(int): >>> if int>0: >>> >>> return 1 >>> elif int==0: >>> >>> return 0 >>> else: >>> >>> return -1

the trailing else in an if/else statement has a similar purpose as the _______ section of a switch statement

default

Each repetition of a loop is known as a(n) __________.

iteration

What will be displayed on the screen? Variable j = 10 Variable k = 2 Variable l = 4 store value of j times k in j store value of k times l in l add j and l, store in k what is k?

k = 28

Words that have special meaning in a programming language are called __________ words.

key

<

less than

the line in the program that begins with a # is called a

preprocessor directive

5.5..#51144 Assume that print_error_description is a function that expects one int parameter and returns no value. Write a statement that invokes the function print_error_description, passing it the value 14. print_error_description(14)

print_error_description(14)

5.5..#51145 Given print_larger, a function that expects two parameters and returns no value and given two variables, sales1 and sales2, that have already been defined, write a statement that calls print_larger, passing it sales1 and sales2.

print_larger(sales1, sales2);

5.2.#51143 Assume that print_todays_date is a function that uses no parameters and returns no value. Write a statement that calls (invokes) this function.

print_todays_date()

Input Validation

process of inspecting data that is given to the program as input and determining if valid

Since computers can't be programmed in natural human language, algorithms must be written in a _____ language.

program

desk-checking

programmer starts reading the program, or a portion of the program, and steps through each statement

Words or names defined by the programmer are called _____.

programmer-defined identifiers

object-oriented programming (OOP)

programming centered on objects

object

programming element that contains data and the procedures that operate on the data

microprocessers

small chips that the CPU is

Bit

smallest piece of memory

Function call

statement that causes a function to run in a program. Consists of the function name and the actual parameter list

Function definition

statements that make up a function -Definition includes: -return type: data type of the value that function returns to the part of the program that called it -name: name of the function. Function names follow same rules as variables -parameter list: variables containing values passed to the function -body: statements that perform the function's task, enclosed in {}

source code

statements written by the programmer

By default, global identifiers are...

static variables

The rules that must be followed when constructing a program are called _____.

syntax

The rules that must be followed when constructing a program are called __________.

syntax

Inside the for loop's parentheses, the second expression is the

test

IDEs (Integrated Development Environments)

text editor, compiler, debugger, and other utilities integrated into a package with a single set of menus

Parameters (arguments)

the values that are passed in a function call

The default section of a switch statement performs a similar task as the ________ portion of an if/else if statement. conditional break trailing else All of these None of these

trailing else

object code

translated machine language that the compiler stores in an object file

compiler

translates each source code instruction into the appropriate machine language instruction and finds syntax errors

Write a literal representing the true value .

true

a conditonally executed satament should be indented one level from the if statement

true

a variable defined in an inner block may not have the same name a a variable defined in the outer block

true

all lines in a block should be indented one level

true

the if statement regards and expression with a nonzero value as

true

the scope of a variable is limited to the block in which it is defined

true

when an if statement is nested in the if part of another statement, the only time the inner if is executed is hwen the expression of outer if is true

true

you can use the relational operators to compare string objects

true

a relational expression is either _______ or ___________

true false

Global identifier

variable or constant declared outside of every function definition

software

what programs are commonly referred to as

What will be displayed on the screen? Variable x =0 Variable y =5 Add 1 to x Add 1 to y Add x and y, store result in y What is y?

y = 7

You cannot use a range-based for loop to modify the contents of an array unless...?

you declare the range variable as a reference.

Rewrite the following if/else statements as conditional expressions if ( x > y ) z = 1; else z = 20;

z = x > y ? 1 : 20

When a relational expression is false, it has the value ________. one zero zero, one, or minus one less than zero None of these

zero

{ }

{ - This is called a left-brace, or an opening brace, and it is associated with the beginning of the function main. All the statements that make up a function are enclosed in a set of braces. If you look at the third line down from the opening brace, you'll see the closing brace. Everything between the two braces is the contents of the function main. }

if the sub-expression on the left of the ____ operator is true, the right sub-expression is not checked

||

the ______ logical operator works best when testing a number to determine if it is outside a range

||

2.5 On paper, write a program that will display your name on the first line, your street address on the second line, your city, state, and ZIP code on the third line, and your telephone number on the fourth line. Test your program by entering, compiling, and running it.

#include <iostream> using namespace std; int main() { cout << "Teresa Jones\n"; cout << "127 West 423rd Street\n"; cout << "San Antonio, TX 78204\n"; cout << "555-475-1212\n"; }

2.18 Write a program that defines an integer variable named age and a double variable named weight. Store your age and weight as literals in the variables. The program should display these values on the screen in a manner similar to the following: Program Output My age is 26 and my weight is 168.5 pounds. (Feel free to lie to the computer about your age and weight. It will never know!)

#include <iostream> using namespace std; int main() { int age; double weight; age = 26; weight = 168.5; cout << "My age is " << age << " and my weight is "; cout << weight << " pounds. \n"; return 0; }

Write a character literal representing a comma.

','

Write a character literal representing the digit 1 .

'1'

2.20 Which of the following is a character literal? 'B' "B"

'B'

Stream extraction operator

(>>) Gets characters from the stream object on its left and stores them in the variable whose name appears on its right.

In postfix mode:

(val++, val--) the operator returns the value of the variable, then increments or decrements

What does c_str return?

*It returns the contents of the object formatted as a null-terminated C-string.* -Here is the general format of how you call the c_str function: stringObject.c_str()

When do you use a do-while loop?

*The do-while loop is a conditional posttest loop* -Always iterates at least once -Repeating a menu

What his used to exit a switch statement?

*break* exits a switch statement

For switch statements, what is optional but recommended?

*default* is optional but recommended

Increment and Decrement Operators

++ -- Pre ++val; Post val++;

Prefix Mode

++val, --val; - The operator increments/ decrements THEN returns the value of the variable

Compound Operators

+=, -=, *=, /=, %=. Also known as combined assignment operators and arithmetic assignment operators.

In an expression with more than one operator, evaluate in this order:

- (unary negation), in order, left to right - * / %, in order, left to right - + -, in order, left to right

endl & \n

- Every time cout encounters an endl stream manipulator it advances the output to the beginning of the next line for subsequent printing. The manipulator can be inserted anywhere in the stream of characters sent to cout, as long as it is outside the double quotes. Notice that an endl is also used at the end of the last line of output. ex: cout << "The following items were top sellers" << endl; cout << "during the month of June:" << endl; output: The following items were top sellers during the month of June: -------------------------------------------------------- -The second way to cause subsequent output to begin on a new line is to insert a \n inside a string that is being output. ex: cout << "The following items were top sellers\n"; cout << "during the month of June:\n";

Reference Variables as Parameters

-A mechanism that allows a function to work with the original argument from the function call, not a copy of the argument -Allows the function to modify values stored in the calling environment -Provides a way for the function to 'return' more than one value

auto keyword

-C++ 11 introduces an alternative way to define variables by using the auto key word and an initialization value. Here is an example: auto amount = 100; -Notice that the name of the variable has the key word auto in front of it, instead of a data type. This tells the compiler to determine the variable's data type from the initialization value. In this example the initialization value, 100, is an int, so amount will be an int variable. Here are other examples: auto stockCode = 'D'; auto customerNum = 459L; The variable stockCode will be a char because its initialization value, 'D', is a char and the variable customerNum will be a long int because its initialization value, 459L, is a long.

Notes on Increment and Decrement:

-Can be used in expressions: result = num1++ + --num2; -Must be applied to something that has a location in memory. Cannot have: result = (num1 + num2)++; -Can be used in relational expressions: if (++num > limit) *pre- and post-operations will cause different comparisons*

STL Vector

-Can hold values of any type: vector<int> scores; -Automatically adds space as more is needed - no need to determine size at definition -Can use [] to access elements

Sending Data into a function:

-Can pass values into a function at time of call: c = pow(a, b);

Breaking out of a loop:

-Can use *break* to terminate execution of a loop - NOT RECOMMENDED -If used in inner loop, terminates inner loop and goes to outer loop

When to use reference variables and how to change them?

-Changes to a reference variable are made to the variable it refers to -Use reference variables to implement passing parameters by reference

programming style

-Programming style refers to the way a programmer uses identifiers, spaces, tabs, blank lines, and punctuation characters to visually arrange a program's source code. These are some, but not all, of the elements of programming style. -Programming style refers to the way source code is visually arranged. Ideally, it is a consistent method of putting spaces and indentions in a program so visual cues are created. These cues quickly tell a programmer important information about a program. good programming style ex: cout << "The Fahrenheit temperature is " << fahrenheit << " and the Celsius temperature is " << celsius << endl; -Because C++ is a free-flowing language, it is usually possible to spread a statement over several lines like this cout example.

To read a single character:

-Use cin: char ch; cout << "Strike any key to continue"; cin >> ch; Problem: will skip over blanks, tabs, <CR> -Use cin.get(): cin.get(ch); *Will read the next character entered, even whitespace*

The continue statement does what?

-Use continue to go to end of loop and prepare for next repetition - while, do-while loops: go to test, repeat loop if test passes - for loop: perform update step, then test, then repeat loop if test passes

Type Casting

-Used for manual data type conversion -Useful for floating point division using ints: Ex: double m; m = static_cast<double>(y2-y1) /(x2-x1); -Useful to see int value of a char variable: Ex: char ch = 'C'; cout << ch << " is " << static_cast<int>(ch);

The range-based for loop automatically knows the number of elements in an array.

-You do not have to use a counter variable. -You do not have to worry about stepping outside the bounds of the array.

Declaring Vectors

-You must #include<vector> -Declare a vector to hold int element: vector<int> scores; -Declare a vector with initial size 30: vector<int> scores(30); -Declare a vector and initialize all elements to 0: vector<int> scores(30, 0); -Declare a vector initialized to size and contents of another vector: vector<int> finals(scores);

Stream Manipulator that affects values until changed again?

-fixed: use decimal notation for floating-point values -setprecision(x): when used with fixed, print floating-point value using x digits after the decimal. Without. fixed, print floating- point value using x significant digits -showpoint: always print decimal for floating-point values

TEST IF FILE OPENED

-the file itself can be tested as a boolean value true---> open succeed false ---> open failed if (!infile) { cout << "failed"; }

For each function argument:

-the prototype must include the data type of each parameter inside its parentheses -the header must include a declaration for each parameter in its () //prototype void evenOrOdd(int); //header void evenOrOdd(int num) //call evenOrOdd(val);

Size of an array

-the total number of bytes allocated for it The size of an array is (number of elements) * (size of each element)

The __________ and __________ loops will not iterate at all if their test expressions are false to start with.

-while -for

2.1 The following C++ program will not compile because the lines have been mixed up. Rearrange the lines in the correct order. Test the program by entering it on the computer, compiling it, and running it. int main() } // A crazy mixed up program #include <iostream> return 0; cout << "In 1492 Columbus sailed the ocean blue."; { using namespace std;

// A crazy mixed up program #include <iostream> using namespace std; int main() { cout << "In 1492 Columbus sailed the ocean blue"; return 0; }

2.2 On paper, write a program that will display your name on the screen. Use program 2-1 as your guide. Place a comment with today's date at the top of the program. Test your program by entering, compiling, and running it.

// Insert current date here #include <iostream> using namespace std; int main() { cout << "Teresa Jones"; return 0; }

2.24 Write a program that stores your name, address, and phone number in three separate string objects. Then display their contents on the screen.

// Substitute your name, address, and phone // number for those shown in this program. #inlcude <iostream> #include <string> using namespace std; int main() { string name, address, phone address = "George Davis"; phone = "555-6767"; cout << name << end1; cout << address << end1; count << phone << end1; return 0; }

How many spaces printed out by this statement: cout << "how" << "now" << "brown" << "cow" << "?";

0

What is the value of donuts after the following code executes? 12 10 0 1

0

How many bytes are needed to store: '\n' ?

1

escape sequence example

1 // Another well-adjusted printing program 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 cout << "The following items were top sellers\n"; 8 cout << "during the month of June:\n"; 9 cout << "Computer games\nCoffee"; 10 cout << "\nAspirin\n"; 11 return 0; 12 } output: The following items were top sellers during the month of June: Computer games Coffee Aspirin \n is an example of an escape sequence. Escape sequences are written as a backslash character (\) followed by a control character and are used to control the way output is displayed. There are many escape sequences in C++. The newline escape sequence (\n) is just one of them. When cout encounters \n in a string, it doesn't print it on the screen. Instead it interprets it as a special command to advance the output cursor to the next line. You have probably noticed that inserting the escape sequence requires less typing than inserting endl. That's why some programmers prefer it.

What will the following program segment display? int funny = 7, serious = 15; funny = serious%2; if (funny != 1) { funny = 0; serious = 0; } else if (funny == 2) { funny = 10; serious = 10; } else { funny = 1; serious = 1; } cout << funny << " " << serious << endl; 7 15 0 0 10 10 1 1 None of these

1 1

Two functions are said to have "different formal parameter lists" if both functions have...

1) A different number of formal parameters or 2) Same number of formal parameters, and the parameter types differ in at least one position

4 number systems

1) Decimal- base 10 2) Binary- base 2 3) Octal- base 8 4) Hexadecimal- base 16

Advantages of Functions

1) Focus on one part at a time 2) Different people can develop different functions simultaneously 3) Can be written once, used multiple times 4) Enhances a program's readability

4 rules for Global identifiers to be accessible by a function

1) The identifier is declared before the function definition 2) The function name is different from the identifier name 3) All function parameters have names different from the identifier 4) All local identifiers have names different from the identifier.

4 Problem Solving Steps

1) Understand the problem 2) Design a solution 3) Implement the solution 4) Test the solution and fix mistakes

2 types of formal parameters

1) Value parameters 2) Reference parameters

Two types of functions in C++

1) Value-returning functions 2) Void functions

Where can a local identifier be accessed

1) Within the block where it was declared 2) Within any blocks nested inside the block where it was declared

Coercion Rules:

1) char, short, unsigned short automatically promoted to int 2) When operating on values of different data types, the lower one is promoted to the type of the higher one. 3) When using the = operator, the type of expression on right will be converted to type of variable on left

Steps on creating a program

1. Define what the program is to do. 2. Visualize the program running on the computer. 3. Use design tools to create a model of the program. 4. Check the model for logical errors. 5. Write the program source code. 6. Compile the source code. 7. Correct any errors found during the compilation. 8. Link the program to create an executable file. 9. Run the program using test data for input. 10. Correct any errors found while running the program. Repeat steps 4 through 10 as many times as necessary. 11. Validate the results of the program.

Calculating gross pay example

1. Display a message on the screen asking "How many hours did you work?" 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3. Display a message on the screen asking "How much do you get paid per hour?" 4.Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5. Multiply the number of hours by the amount paid per hour, and store the result in memory. 6.Display a message on the screen that tells the amount of money earned. The message must include the result of the calculation performed in step 5.

What is the value of donuts after the following code executes? int donuts = 10; if(donuts != 10) donuts = 0: else donuts += 2; 12 10 0 2

12

What is the output of the following segment of code if 4 is input by the user when asked to enter a number? int num; int total = 0; cout << "Enter a number from 1 to 100: "; cin >> num; switch (num) { case 1: case 2: total = 5; case 3: total = 10; case 4: total = total + 3; case 8: total = total + 6; default: total = total + 4; } cout << total << endl; 0 3 13 28 None of these

13

After execution of the following code, what will be the value of input_value if the value 0 is entered at the keyboard at run time? cin >> input_value; if (input_value > 5) input_value = input_value + 5; else if (input_value > 2) input_value = input_value + 10; else input_value = input_value + 15; 15 10 25 0 5

15

What will the value of x be after the following statements execute? int x = 0; int y = 5; int z = 4; x = y + z * 2; 13 18 0 None of the above

18

How many bytes are needed to store: "\n", ?

2

How many bytes are needed to store: "n" ?

2

Assume "value" is an integer variable. If the user enters 3.14 in response to the following statement, what will be stored in "value? cin >> value;

3

Given the following code segment, what is output after "result = "? int x = 1, y = 1, z = 1; y = y + z; x = x + y; cout << "result = " << (x < y ? y : x) << endl; 0 1 2 3 None of these

3

How many bytes are needed to store: "\\n" ?

3

What's the difference in UNICODE value between '3' and '0'? (consult a table of UNICODE values):

3

Assuming x is 5, y is 6, and z is 8, which of the following is false? 1. x == 5; 2. 7 <= (x+2); 3. z <= 4; 4. (1+x) != y; 5. x >= 8; 6. x >= 0; 7. x <= (y*2); 3, 4, 6, 7 are false. Only 5 is false. 3 and 4 are false. All are false. None of these

3 and 4 are false.

What's the difference in UNICODE value between 'E' and 'A'? (consult a table of UNICODE values):

4

What's the difference in UNICODE value between 'e' and 'a'? (consult a table of UNICODE values):

4

How many spaces printed out by this statement: cout << "abc\ndef\tghi\njkl" << endl << endl << "mno\n\npqr\n";

6

What's the difference in UNICODE value between '6' and '0'? (consult a table of UNICODE values):

6

2.19 What are the ASCII codes for the following characters? (Refer to Appendix A.) C F W

67, 70, 87

Which line in the following program will cause a compiler error? 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int number = 5; 7 8 if (number >= 0 && <= 100) 9 cout << "passed.\n"; 10 else 11 cout << "failed.\n"; 12 return 0; 13 } 6 8 10 9

8

byte

8 bits. Enough memory to store only a letter of the alphabet or a small number.

Which value can be entered to cause the following code segment to display the message "That number is acceptable." int number; cin >> number; if (number > 10 && number < 100) cout << "That number is acceptable. \n"; else cout << "That number is not acceptable.\n"; 100 10 99 0 All of these

99

2.10 Which of the following are illegal C++ variable names, and why? x 99bottles july97 theSalesFigureForFiscalYear98 r&d grade_report

99bottles: Variable names cannot begin with a number r&d: Variable names may only use alphabetic letters, digits, and underscores.

1.27 What is a hierarchy chart?

A chart that depicts the logical steps of the program in a hierarchical fashion

A C++ Program

A collection of functions

Main Memory and bytes

A computer's memory is divided into tiny storage cells known as bytes. One byte is enough memory to store just a single letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren't actual "switches," however, at least not in the conventional sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position and a negative charge as a switch in the off position.

Executable File

A file, usually with an .exe extension, containing instructions that tell a computer how to perform a specific task.

Driver

A function that test another function by calling it -Various arguments are passed and return values are tested

Why is the use of global variables not recommended?

A global variable can be accessed by most functions within a program. If something goes wrong with that variable, it will be a lot more difficult to find where in the program the error occurred.

Function

A group of one or more programming statements that collectively has a name.

Block of Code

A group of statements enclosed inside a set of braces.

Hierarchy Chart

A hierarchy chart is a diagram that graphically depicts the structure of a program. It has boxes that represent each step in the program. The boxes are connected in a way that illustrates their relationship to one another. It is a useful tool for planning each operation a program must perform and the order in which the operations are to occur.

Run-time Library

A library of prewritten code for performing the common operations or sometimes difficult tasks. For example, the library contains hardware-specific code for displaying messages on the screen and reading input from the keyboard.

1.13 What is the difference between a high-level language and a low-level language?

A low-level language is close to the level of the computer and resembles the system's numeric machine language. A high-level language is closer to the level of human readability and resembles natural languages.

1.31 What is a logic error?

A mistake that causes a program to produce erroneous results. A logic error occurs when what the programmer means for the program to do does not match what the code actually

Variable

A named storage location in the computers memory for holding a piece of information.

Integer Literal

A numeric literal that is treated as an int.

Programmer/Software Developer

A person with the training and skills necessary to design, create, and test computer programs.

While Loop

A pretest loop. It is especially useful for validating input. (Best used when testing for "true").

cpu - fetch/decode/execute cycle

A program is a sequence of instructions stored in the computer's memory. When a computer is running a program, the CPU is engaged in a process known formally as the fetch/decode/execute cycle. Fetch - The CPU's control unit fetches, from main memory, the next instruction in the sequence of program instructions. Decode - The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal. Execute - The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation.

Program

A program is a set of instructions that a computer follows to perform a task.

Portability

A program that can be written on one type of computer and then run on many other types of systems.

Linker*

A program that combines the object file (machine code) with the necessary library routines (prewritten codes from the compiler's library). Then turns it into an executable file.

Decision Structure

A program that executes some statements only under certain circumstances. A specific action is taken only when a specific condition exists.

driver

A program used to test a function

1.17 What is an integrated development environment?

A programming environment that includes a text editor, compiler, debugger, and other utilities, integrated into one package.

High-level Programming Language

A programming language that uses both natural language constructs and mathematical notation.*Closer to the level of human-readability.

expression

A programming statement that has a value. It usually consists of an operator and its operands.

Strings hold what?

A series of characters in consecutive memory locations -Stored with the null terminator, \0, at the end

Algorithm

A set of well defined steps for performing a task or solving a problem.

1.11 What is an algorithm?

A set of well-defined steps for performing a task or solving a problem

File Buffer

A small "holding section" of memory that file-bound data is first written to.

sizeof

A special operator called __________ will report the number of bytes of memory used by any data type of variable.

Statement

A statement is a complete instruction that causes the computer to perform some action. Here is the statement that appears in line 10 cout << "How many hours did you work? "; It causes the computer to display the message "How many hours did you work?" on the screen.

Break Statement

A statement that causes a loop to terminate early.

flash memory*

A type of nonvolatile computer memory that can be electrically erased and rewritten repeatedly. (Definition not from the book).

1.9 What do you call a program that performs a specialized task, such as a virus scanner, a file-compression program, or a data-backup program?

A utility program

assignment statement

A value is stored in a variable with an _______________.

lvalue

A value that may appear on the left side of an assignment operator.

lvalue

A value that may appear on the left side of an assignment operator. Most of the time this will be a variable name.

Variables

A variable is a named storage location in the computer's memory for holding a piece of data. Variables are symbolic names that represent locations in the computer's random-access memory (RAM). When information is stored in a variable, it is actually stored in RAM.

Actual parameter

A variable or expression listed in a call to a function

Counter

A variable that is regularly incremented or decremented each time a loop iterates.

Scope

A variable's scope is the part of the program that has access to the variable. -Every variable has a scope. The scope of a variable is the part of the program where it may be used.

What will the following programs display on the screen? A) #include <iostream> using namespace std; int main() { cout << "Be careful!\n"; cout << "This might/n be a trick "; cout << "question. \n"; return 0; } B) #include <iostream> using namespace std; int main() { int a, x = 23; a = x % 2; cout << x << endl << a << endl; return 0; }

A) Becareful! This might/n be a trick question. B) 23 11

2.12 Refer to the data types listed in table 2-6 for these questions. A) If a variable needs to hold numbers in the range 32 to 6,000 what data type would be best? B) If a variable needs to hold numbers in the range -40,000 to 40,000, what data type would be best? C) 20 and 20L are both integer literals. Does one use more memory than the other, and if so which one, or do they both use the same number of bytes?

A) short or unsigned short

User-controlled loop

Allows the user to decide the number of iterations. (The do-while is a good choice for repeating a menu).

Menu-Driven Program

Allows the user to determine the course of action by selecting it from a list of actions.

Algorithm

An algorithm is a set of well-defined steps for performing a task or solving a problem. Collectively, these instructions are called an algorithm. Notice these steps are ordered sequentially. Step 1 should be performed before step 2, and so forth. It is important that these instructions be performed in their proper sequence. 1. Display a message on the screen asking "How many hours did you work?" 2. Wait for the user to enter the number of hours worked. Once the user enters a number, store it in memory. 3.Display a message on the screen asking "How much do you get paid per hour?" 4.Wait for the user to enter an hourly pay rate. Once the user enters a number, store it in memory. 5.Multiply the number of hours by the amount paid per hour, and store the result in memory. 6.Display a message on the screen that tells the amount of money earned. The message must include the result of the calculation performed in step 5.

What is the difference between an argument and a parameter variable?

An argument variable is a variable which is used to send a value to the functions. Don't write data type. A parameter variable is a variable which is used to accept a value into the functions. Data type before the parameter variable.

1.32 What is a run-time error?

An error that occurs while the program is running when the system is asked to perform an action it cannot carry out.

Test Expression

An expression that controls the execution of the loop. As long as it is true, the body of the loop will repeat.

Relational Expression

An expression used to determine whether a specific relationship exists between two values.

Explain the difference between an object file and an executable file?

An object file is the location that holds the translated machine language. Once the Linker has finished, it becomes an executable file.

Internally, the CPU consist of the _____ and the _____.

Arithmetic and Logic Control Unit

Initialization

Assigning values to variables as part of the definition.

Assignment Operation

Assigns or copies a value into a variable.

Assignment Operation

Assigns, or copies, a value into a variable.

How to declare a reference parameter

Attach & after the dataType of the parameter in the formal parameter list.

Why must programs written in a high - level language be translated into machine language before they can be run?

Because a computer's CPU can only understand Machine Language.

1.1 Why is the computer used by so many different people, in so many different professions?

Because computers can be programmed to do so many different tasks

Why do local variables lose their values between calls to the function in which they are defined?

Because they are created in memory when the function begins execution, and are destroyed when the function ends.

How can you override the default automatic for local variables?

By using the keyword "static" in the variable declaration Example: "int x" becomes "static int x"

What will the following segment of code output if 11 is entered at the keyboard? int number; cin >> number; if (number > 0) cout << "C++"; else cout << "Soccer"; cout << " is "; cour << "fun" << endl; C++ is fun Soccer is fun C++ C++fun Soccerfun

C++

Arithmetic Operators

C++ provides many operators for manipulating data. Generally, there are three types of operators: unary, binary, and ternary. These terms reflect the number of operands an operator requires. page 62 in textbook for examples.

Look at the following function prototype: int myFunction(double, double, double); How many parameter variables does this function have? A. 1 B. 2 C. 3 D. Can't tell from the prototype

C. 3

Assuming outFile is a file stream object and number is a variable, which statement writes the contents of number to the file associated with outFile? A. number >> outFile; B. outFile >> number; C. outFile << number; D. write(outFile, number);

C. outFile << number;

continue statement

Can use continue to go to end of loop and prepare for next repetition. while, do-while loops: go to test, repeat loop if test passes for loop: perform update step, then test, then repeat loop if test passes

The exit() Function

Causes a program to terminate -Can be called from any function -Can pass an int value to operating system to indicate status of program termination -Usually used for abnormal termination of program -Requires cstdlib header file

Other cards to look at...

Chapter 5b --> https://quizlet.com/102343526/chapter-5b-flash-cards/ Python ch 5 --> https://quizlet.com/165811975/python-ch-5-flash-cards/ CMPT 140CodeLab 2 --> https://quizlet.com/161914978/cmpt-140-codelab-2-flash-cards/

Comments

Comments are part of the program, but the compiler ignores them. They are intended for people who may be reading the source code. -In addition to telling what the program does and describing the purpose of variables, comments can also be used to explain complex procedures in your code and to provide information such as who wrote the program and when it was written or last modified.

Function header (heading)

Consists of 4 parts: 1) Name of function 2) parameters 3) data type of each parameter 4) data type of the return value Syntax: returnType Name ( dataType parameter, dataType parameter, ...)

The Programming Process

Consists of several steps, which include design, creating, testing and debugging.

Conditional Expression

Consists of three sub-expressions separated by the ? and : symbols.

What is the output of the following code segment? n = 1; while (n <= 5) cout << n << ' '; n++; A. 1 2 3 4 5 B. 1 2 3 4 C. 2 3 4 5 6 D. 1 1 1...and on forever

D. 1 1 1...and on forever

How is a reference variable defined?

Defined with an ampersand (&) Ex: void getDimensions(int&, int&);

TRUE or FALSE: Both of the following if statement perform the same operations. if (calls == 20) rate *=0.5; if (calls = 20) rate *= 0.5;

FALSE, the first statement checks if calls are equal o 20 and the second statement assigns a value of 20 to the variable calls.

TRUE or FALSE: The following if/else statements cause the same output to display. if (x > y) cout << "x is the greater. \n" else cout << "x is not the greater. \n" if (y <=x) cout << "x is not the greater. \n" else cout << "x is the greater. \n"

FALSE. The first if statement only checks that x is greater than y in order to output x is the greater. The second if statement checks that y is less than or equal to x or just alike if x is greater than or equal to y to output a different message stating x is not the greater.

A function's return data type must be the same as the function's parameter(s). T/F

False

A local variable and a global variable may not have the same name within the same program. T/F

False

A statement that starts with a # is called a comment True False

False

Local int variables are initialized to zero (0) by default. T/F

False

1.4 Describe the steps in the fetch/decode/execute cycle.

Fetch: The CPU's control unit fetches the program's next instruction from main memory Decode: The control unit decodes the instruction, which is encoded in the form of a number. An electrical signal is generated Execute:The signal is routed to the appropriate component of the computer, which causes a device to perform an operation

Value parameter

Formal parameter that receives a copy of the content of the corresponding actual parameter

Reference parameter

Formal parameter that receives the memory location of the corresponding actual parameter

A(n) _________ eliminates the need to place a function definition before all calls to the function.

Function prototype

Void function

Function that lacks a return statement. Performs some action, but does not return a value to the main function.

1.29 What is the difference between high-level pseudocode and detailed pseudocode?

High-level pseudocode just lists the steps a program must carry out. Detailed pseudocode shows the variables, logic, and cocmputations needed to create the program.

Default Argument Validation

If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: int getSum(int, int=0, int=0);// OK int getSum(int, int=0, int); // NO When an argument is omitted from a function call, all arguments after it must also be omitted: sum = getSum(num1, num2); // OK sum = getSum(num1, , num3);//NO

7. Correct any errors found during compilation

If the compiler reports any errors, they must be corrected and the code recompiled. This step is repeated until the program is free of compile-time errors.

Associativity

If two operators have the same precedence they move left to right.

sizeOf operator

If you are not sure what the sizes of data types are on your computer, C++ provides a way to find out. A special operator called sizeof will report the number of bytes of memory used by any data type or variable. The name of the data type or variable is placed inside the parentheses that follow the operator. The operator "returns" the number of bytes used by that item. This operator can be used anywhere you can use an unsigned integer ex: cout << "An apple can be eaten in " << sizeof(apple) << " bytes!\n"; cout << "The size of a long integer is " << sizeof(long) << " bytes.\n";

-left -= -lvalue

In C++ terminology, the operand on the _____ side of the ______ symbol must be an _______.

-division -floating-point -floating-point

In order for a __________ operation to return to a __________ value, one of the operands must be of a __________ data type.

The following program will run, but the user will have difficulty understanding what to do. How would you improve the program? // This program multiplies two numbers and displays the result. #include <iostream> using namespace std; int main() { double first, second, product; cin >> first >> second; product = first * second; cout << product; return 0; }

Include one or more cout statements explaining what values the user should enter.

Header file

Included at the head or top of a program.

IPO

Input, Processing, Output. The three primary activities of a program.

2.28 Is the following an example of integer division or floating-point division? What value will be displayed? cout << 16 / 3;

Integer division. The value 5 will be displayed.

IDE

Integrated Development Environment. Consist of a text editor, compiler, debugger & other utilities.

Indentation and spacing

Is for human readers of a program, not the compiler.

&&

Is known as the logical AND operator. (Best one to use to check if a number is INSIDE a range).

||

Is known as the logical OR operator. (Best one to use to check if a number is OUTSIDE a range).

Volatile Memory

Is used only for temporary storage while a computer program is running. (RAM).

Variable Definition

Is used to define one or more variables that will be used in the program and to indicate the type of data they will hold.

Double precision

Is usually 8 bytes in size (double data type).

annotating

It is crucial that you develop the habit of thoroughly ________ your code with descriptive comments.

-division -division -fractional

It is important to note that when both of the __________ operator's operands are integers, the result of the __________ will be an integer. If the result has a __________ part, it will be thrown away.

1.22 What happens to a variable's current contents when a new value is stored there?

It is overwritten by the new value. The old value is "lost"

Conditionally Executed

It is performed only when a certain condition exists.

Post-test loop

Its expression is tested AFTER each iteration. (do-while). It always performs at least one iteration. (Can be used as a user control loop).

If a function does not return a value what is its return type?

Its return type is void

Hardware components of a computer

Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of the following major components: The central processing unit (CPU) Main memory (random-access memory, or RAM) Secondary storage devices Input devices Output devices

__________ is the only language computers really process.

Machine language

Both main memory and secondary storage are types of memory. Describe the difference between the two.

Main memory (RAM) is used only for temporary storage while running a program. When the computer is turned off, the contents of RAM are erased. Secondary storage holds data for long periods of time-- even when there is no poewr to the computer. Stored and loaded into main memory when needed

Main Memory (RAM - Random Access Memory)

Main memory is commonly known as random-access memory or RAM. It is called this because the CPU is able to quickly access data stored at any random location in this memory. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. This is where the computer stores a program while the program is running, as well as the data that the program is working with. For example, suppose you are using a word processing program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in small chips.

Both main memory and secondary storage are types of memory. Describe the difference between the two.

Main memory is like RAM and Secondary Storage is like the Hard Drive.

Both main memory and secondary storage or types of memory. Describe the difference between the two.

Main memory is like RAM and Secondary Storage is like the Hard Drive.

Arithmetic Operators

Manipulate numeric values and perform arithmetic operators. Three types: unary, binary, and ternary.

//

Marks the beginning of a comment.

Read position

Marks the location of the next byte that will be *read* from a file.

5. Write the program source code

Once a model of the program (hierarchy chart, flowchart, or pseudocode) has been created, checked, and corrected, the programmer is ready to write the source code, using an actual computer programming language, such as C++. Most programmers write the code directly on the computer, typing it into a text editor or IDE.

9. Run the program using test data for input

Once an executable file is generated, the program is ready to be tested for run-time and logic errors. A run-time error occurs when the running program asks the computer to do something that is impossible, such as divide by zero. Normally a run-time error causes the program to abort. If the program runs, but fails to produce correct results, it likely contains one or more logic errors.

Integer and Long Integer Literals

One of the pleasing characteristics of the C++ language is that it allows you to control almost every aspect of your program. If you need to change the way something is stored in memory, tools are provided to do that. For example, what if you are in a situation where you have an integer literal that you need to store in memory as a long integer? C++ allows you to do this by placing the letter L at the end of the number. Here is an example: long amount; amount = 32L; ------------------------------------------------------- The first statement defines a long variable named amount. The second statement assigns the literal value 32 to the amount variable. Because the literal is written as 32L, it makes it a long integer literal. This means the assigned value is treated as a long. Likewise, if you want an integer literal to be treated as a long long int, you can append LL at the end of the number. Here is an example: long long amount; amount = 32LL;

Operators

Operators perform operations on one or more operands. An operand is usually a piece of data, like a number. The = and * symbols are both operators. pay = hours * rate; In other words, the statement says, "Make the pay variable equal to hours times rate" or "pay is assigned the value of hours times rate."

Which of the following is not one of the five major components of a computer system? Preprocessor CPU Main memory I/O devices Secondary Storage

Preprocessor

(Computer) Output Device

Printers, Monitors, Speakers, etc.

function overloading

Process of creating several functions with the same name but different formal parameter lists.

Logic Error

Program compiles. Output unexpected. You mean to add 6 + 3 and the answer is 18.

Run-time Error

Program compiles. Program crashes. Divide by zero. Null pointer error.

1.6 Explain why computers have both main memory and a secondary storage.

Program instructions and data are stored in main memory while the program is running. Main memory is volatile and loses its contents when power is removed from the computer. Secondary storage holds data for long periods of time-- even when there is no power to the computer

Computers can do many different jobs because they can be _____.

Programmed

Words or names defined by the programmer are called __________.

Programmer-Defined Identifiers (also called variables)

using namespace std;

Programs usually contain various types of items with unique names. In this chapter you will learn to create variables. In Chapter 6 you will learn to create functions. In Chapter 7 you will learn to create objects. Variables, functions, and objects are examples of program entities that must have names. C++ uses namespaces to organize the names of program entities. The statement using namespace std; declares that the program will be accessing entities whose names are part of the namespace called std. (Yes, even namespaces have names.) The program needs access to the std namespace because every name created by the iostream file is part of that namespace. In order for a program to use the entities in iostream, it must have access to the std namespace.

Purpose of a function prototype

Prototypes are placed before the main function so that the program can compile correctly when the function definitions are after the main function.

Pseudocode

Pseudocode is a cross between human language and a programming language. Although the computer can't understand pseudocode, programmers often find it helpful to write an algorithm using it. This is because pseudocode is similar to natural language, yet close enough to programming language that it can be easily converted later into program source code. By writing the algorithm in pseudocode first, the programmer can focus on just the logical steps the program must perform, without having to worry yet about syntax or about details such as how output will be displayed. Here is high-level pseudocode for the pay-calculating program: -Ask the user to input the number of hours worked -Input hours -Ask the user to input the hourly pay rate -Input rate -Set pay equal to hours times rate -Display pay

_____ characters or symbols mark the beginning or ending of programming statements, or separate items in a list.

Punctuation

__________ characters or symbols mark the beginning or ending of programming statements, or separate items in a list.

Punctuation

To store an integer constant in a long memory location, what needs to be put at the end of a number?

Put an 'L'

To store an integer constant in a long long memory location, what needs to be put at the end of a number?

Put an 'LL'

resize (n, val) member function is used for?

Resizes the vector so it contains n elements. If new elements are added, they are initialized to val. Ex: vec1.resize(5, 0);

setprecision( )

Set the total number of digits that will appear before and after the decimal point. It remains in effect until it is changed.

Filename Extensions

Short sequences of characters that appear at the end of a filename preceded by a period (known as a "dot").

Escape Sequence

Starts with a backslash (\) character and is followed by one or more control characters. They allow you to control the way output is displayed by embedding commands within the string itself.

Sequence Structures

Statements that are executed in a sequence, without branching off in another direction.

_________ local variables retain their value between function calls.

Static

What is the difference between system software and application software?

System Software includes the Operating Systems, Utility Programs, Software Development Tools. Application Software includes programs used by the user.

What is the difference between system software and application software?

System software contains the programs that control and manage the basic operations of a computer. Application software make the computer useful for everyday tasks.

operator

The ________ "returns" the number of bytes used by that item.

-modulus -remainder

The __________ operator divides an integer by another integer, and gives the ___________.

multiplication

The __________ operator returns the product of its two operands.

division

The __________ operator returns the quotient of its left operand divided by its right operand.

subtraction

The __________ operator returns the value of its right operand subtracted from its left operand.

modulus

The __________ operator, which only works with integer operands, returns the remainder of an integer division.

-operators -numeric -arithmetic

The are many __________ for manipulating _________ values and performing ________ operations.

CPU (Central Processing Unit)

The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU's job is to fetch instructions, follow the instructions, and produce some result. Internally, the central processing unit consists of two parts: the control unit and the arithmetic and logic unit (ALU). -The control unit coordinates all of the computer's operations. It is responsible for determining where to get the next instruction and for regulating the other major components of the computer with control signals. -The arithmetic and logic unit, as its name suggests, is designed to perform mathematical operations.

Where does cin read its input from?

The console (or keyboard)

Operands

The data that operators work with.

Initialization Expression

The first expression in a for loop. It is normally used to initialize a counter variable to its starting value. (It is only done once in the loop).

Decode

The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal.

Stream Insertion Operator (<<)

The item immediately to the right of the operator is sent to cout and then displayed on the screen. Always written as two less than signs with no space between them.

-const -read-only

The key word _______ is a qualifier that tells the complier to make the variable __________. Its value will remain constant throughout the program's execution. It is not required that the variable name be written in all __________ characters, but many programmers prefer to write them this way so they are easily distinguishable from regular variable names.

Trailing Else

The last else clause.

2.8 When the above main function runs, what will display on the screen?

The little number is 2 The big number is 2000

Machine language

The lowest level of computer languages and the only language understood by computers. A stream of binary binary numbers.

Input Validation

The process of inspecting data given to a program by the user and determining if it is valid.

Reading Data

The process of retrieving data from a file.

Writing Data

The process of saving data in a file.

Fetch-Decode-Execute Cycle

The process the CPU is engaged in when a computer is running a program. The three steps are repeated as long as there are instructions to perform.

1.33 Describe the process of desk-checking.

The programmer steps through each statement in the program from beginning to end. The contents of variables are recorded, and screen output is sketched.

System Software

The programs that control and manage the basic operations of a computer. Such as: Operating Systems, Utility Programs & Software Development Tools.

Explain why you cannot convert the following if else if statement into a switch statement. if (temp == 100) x = 0; else if (population > 100 ) x = 1; else if (rate < .1 ) x = -1;

The reason you cannot convert the following if else if statement into a switch statement is because the if else if statement tests the conditions of different variables and in order to use a switch statement we must be testing the conditions of the same variable.

What happens when a return statement is followed by several terms? (example: return a, b, c;)

The return statement will only return the last item in the list. (in the example, it would only return "c")

Body

The series of statements that executes the purpose of a function

Software Development Tools

The software tools that programmers use to create, modify, and test software. Compilers and integrated development environments.

Source Code

The statements written by the programmer.

What is the >> symbol called?

The stream extraction operator

2.22 What header file must you include in order to use string objects?

The string literal "Z" is being stored in the character variable "letter"

Precision or Significant Digits

The total number of digits that appear before and after the decimal point.

2.9 When the following main function runs, what will display on the screen? int main() { int number; number = 712; cout << "The value is " << "number" << end1; return 0; }

The value is number

What is the one condition on the expression returned by a function?

The value must be of the same dataType as the function. Ex. double powerfunc(double x, double y) must return a double type value.

2.26 What is wrong with the following program? How would you correct it? #include <iostream> using namespace std; int main() { critter = 62.7; double critter; cout << critter <<< end1; return 0; }

The variable critter is assigned a value before it is declared. You can correct the program by moving the statement critter = 62.7; to the line after the variable declaration

1.23 What must take place in a program before a variable is used?

The variable must be defined in a declaration

What is wrong with the following switch statement? switch (temp) { case temp < 0 : cout << "Temp is negative. \n"; break; case temp == 0 : cout << "Temp is zero. \n"; break; case temp > 0 : cout << "Temp is positive. \n"; break; }

The variable must be followed by an integer CONSTANT not a relational operator.

Accumulator

The variable used to keep a running total.

2.4 What output will the following lines of code display on the screen? cout << "The works of Wolfgang\ninclude the following:" ; cout << "\nThe Turkish March" << end1 ; cout << "and Symphony No. 40" ; cout << "in G minor." << end1 ;

The works of Wolfgang include the following: The Turkish March and Symphony No. 40 in G minor

Integer Data types

There are many different types of data. Variables are classified according to their data type, which determines the kind of information that may be stored in them. Integer variables can only hold whole numbers. Integers are at least as big as short integers. Long integers are at least as big as integers. Unsigned short integers are the same size as short integers. Unsigned integers are the same size as integers. Unsigned long integers are the same size as long integers. The long long int and the unsigned long long int data types are guaranteed to be at least 8 bytes (64 bits) in size. data types can also be defined in one line such as: int floors = 15, 9 rooms = 300, 10 suites = 30;

How are actual and formal parameters related?

There must be a one-to-one correspondence. A function must be called with the same number of parameters with which it was declared.

Integrated Development Environment (IDE)

These environments consist of a text editor, compiler, debugger, and other utilities integrated into a package with a single set of menus. Preprocessing, compiling, linking, and even executing a program is done with a single click of a button, or by selecting a single item from a menu.

Logical Operators

These operators connect two or more relational expression into one, or reverse the logic of an expression. (AND, OR NOT... && || !)

Relational Operators

These operators determine whether a specific relationship exists between two values.

Constants that begin with '0x' are what?

They are base 16

Constants that begin with '0' are what?

They are base 8

Floating-Point Literals are what by default?

They are double by default - Can be forced to be float (3.14159f) or long double (0.0000625L)

integer literals are stored as what by DEFAULT?

They are stored as ints

run-time library & linker

This collection of code, called the run-time library, is extensive. Programs almost always use some part of it. When the compiler generates an object file, however, it does not include machine code for any run-time library routines the programmer might have used. During the last phase of the translation process, another program called the linker combines the object file with the necessary library routines. Once the linker has finished with this step, an executable file is created. The executable file contains machine language instructions, or executable code, and is ready to run on the computer.

Division By Zero

This is mathematically impossible to perform and it normally causes a program to crash.

What will following segment of code output? int x = 5; if(x = 2) cout << "This is true!" << endl; esle cout << "This is false!" << endl; cout << "This is all folks!" << endl; This is true! This is false! This is true! This is false! This is true! This is all folks! None of these

This is true! This is all folks!

int main()

This marks the beginning of a function. A function can be thought of as a group of one or more programming statements that has a name. The name of this function is main, and the set of parentheses that follows the name indicates that it is a function. The word int stands for "integer." It indicates that the function sends an integer value back to the operating system when it is finished executing.

cout.fill( )

This member function of cout changes the fill character, which is a space by default. (fill characters are used when using setw( )).

Conditional Operator

This operator consists of the question mark (?) and colon (:). (A ternary operator).

1. Define what the program is to do

This step requires that you clearly identify the purpose of the program, the information that is to be input, the processing that is to take place, and the desired output. Here are the requirements for the example program: Purpose - To calculate the user's gross pay. Input - Number of hours worked, hourly pay rate. Processing - Multiply number of hours worked by hourly pay rate. The result is the user's gross pay. Output - Display a message indicating the user's gross pay.

How do you call a function?

To call a function, use the function name followed by () and ; Ex: printHeading();

Decrement

To decrease a value.

1.12 Why were computer programming languages invented?

To ease the task of programming. Programs may be written in a programming language, then converted to machine language.

1.26 What does it mean to "visualize a program running"? What is the value of doing this?

To imagine what the computer screen looks like while the program is running. This helps define input and output

Increment

To increase a value.

-forward slashes -complier

To place comments in a C++ program, place two ______________ where you want the comment to begin. The _________ ignores everything from that point to the end of the line.

Floating point constants are normally stored in memory as doubles True False

True

If the sub-expression on the left side of an && operator is false, the expression on the right side will not be checked. True False

True

If the sub-expression on the left side of the || operator is true, the expression on the right side will not be checked. True False

True

Initialization of static local variables only happens once, regardless of how many times the function in which they are defined is called.

True

It is possible for a function to have some parameters with default arguments and some without. T/F

True

One reason for using functions is to break programs into manageable units, or modules. T/F

True

T/F Functions can call other functions

True

T/F A CPU really only understands instructions that are written in machine language.

True

T/F An int is a driver function?

True

T/F In C++, key words are written in all lowercase letters

True

T/F When using prototypes, you can you place function definitions in any order in source file

True

The cin >> statement will stop reading input when it encounters a newline character. T/F

True

The following code correctly determines whether x contains a value out of the range of 0 through 100. if (x < 0 || x> 100) True False

True

The only difference between the get function and the >> operator is that get reads the first character typed, even if it is a space, tab, or the [Enter] key T/F

True

This code compiles without errors: int main () { int x = 3; if( x > 2 ) { int x = 3; } int y = 0; T/F

True

True or False: cin requires the user to press the [enter] key after entering data.

True

Variables need to be declared before they can be used. True False

True

What is the value of the following expression? (true || ((true || false) && false)) T/F

True

What is the value of the following expression? ((3 > 4) && (3 == (4 - 1))) || (2 > 0) T/F

True

When C++ is working with an operator, it strives to convert the operands to the same type. T/F

True

When the fixed manipulator is used, the value specified by the setprecision manipulator will be the number of digits to appear after the decimal point. T/F

True

When a function with default arguments is called and an argument is left out, all arguments that come after it must be left out as well.

True, as default arguments are very convenient, they are not totally flexible in their use.

static_cast<dataType>(value)

Type cast conversion. It lets you manually promote or demote a value.

short int

Typically 2 bytes in size. Ranges from -32,768 to +32,767.

Update the Expression

Typically a statement that increments/decrements a loop's counter variable.

How can several values be returned from a function into the main function?

Use a void function with several reference parameters. The function will execute, change the value of the parameters, and the new values will be assigned to the variables in the main function.

Console Out (cout)

Used to display information on the computer's screen.

setw( )

Used to establish print fields of specified width. Only works with the value that immediately follows it.

Customary location of user-defined functions

User defined functions are usually declared after the main function.

comments

Using descriptive text to explain portions of code. Comments do not change the way a program behaves, but are important for the programmer to remember what the code does. The // marks the beginning of a comment. ex: //hello this is a comment

unsigned int

Usually 4 bytes in size. Ranges from 0 to +4,294,967,295.

unsigned long int

Usually 4 bytes in size. Ranges from 0 to 4,294,967,295.

unsigned long long int

Usually 8 bytes in size. Ranges from 0 to 18,446,744,073,709,551,615.

long long int

Usually 8 bytes. Ranges -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

When only a copy of an argument is passed to a function, it is said to be passed by _________.

Value

parameters

Values required by a function to operate. Listed after a function's name.

_____________ represent storage locations in the computer's memory Literal Variable Comments Integers None of the above

Variable

Local scope or Block Scope

Variables defined inside a set of braces. They may only be used in the part of the program between their definition and the block's closing brace.

Parameters

Variables in a function that hold the values passed as arguments

2.7 List all the variables and literals that appear below. int main() { int little; int big; little = 2; big = 2000; cout << "The little number is " << little << end1 ; cout << "The big number is " << big << end1 ; return 0; }

Variables: "little" and "big" Literal: 2, 2000, "The little number is ", "The big number is", 0

If a function doesn't return a value, the word _________ will appear as its return type.

Void

preprocessor directives

When a line begins with a # it indicates it is a preprocessor directive. The preprocessor reads your program before it is compiled and only executes those lines beginning with a # symbol. Think of the preprocessor as a program that "sets up" your source code for the compiler. #include <iostream> The #include directive causes the preprocessor to include the contents of another file in the program. The word inside the brackets, iostream, is the name of the file that is to be included. The iostream file contains code that allows a C++ program to display output on the screen and read input from the keyboard. Because the cout statement (on line 7) prints output to the computer screen, we need to include this file. Its contents will be placed in the program at the point the #include statement appears. The iostream file is called a header file, so it should be included at the head, or top, of the program.

Demoted

When a value is converted to a lower data type.

Overflow

When a variable is assigned a number that is too large for its data type. (It will wrap around to its lowest possible value).

Underflow

When a variable is assigned a number that is too small for its data type.

Integer Division

When both operands are integers of a division statement.

-integer division -divison -remainder

When both operands of a division statement are integers, the statement will result in ______________. This means the result of the ___________ will be an integer as well. If there is a __________, it will be discarded.

10. Correct any errors found while running the program

When run-time or logic errors occur in a program, they must be corrected. You must identify the step where the error occurred and determine the cause. Desk-checking - is a process that can help locate these types of errors. The term desk-checking means the programmer starts reading the program, or a portion of the program, and steps through each statement. A sheet of paper is often used in this process to jot down the current contents of all variables and sketch what the screen looks like after each output operation. When a variable's contents change, or information is displayed on the screen, this is noted. By stepping through each statement in this manner, many errors can be located and corrected.

Scope

Where in a program an identifier can be accessed

3. Use Design Tools to Create a Model of the program

While planning a program, the programmer uses one or more design tools to create a model of the program. Three common design tools are hierarchy charts, flowcharts, and pseudocode.

Floating Point Numbers

Whole numbers are not adequate for many jobs. If you are writing a program that works with dollar amounts or precise measurements, you need a data type that allows fractional values. In programming terms, these are called floating-point numbers. The float data type is considered single precision. The double data type is usually twice as big as float, so it is considered double precision. As you've probably guessed, the long double is intended to be larger than the double. The exact sizes of these data types is dependent on the computer you are using. The only guarantees are -A double is at least as big as a float. -A long double is at least as big as a double. ex: float distance = 1.496E8; // in kilometers 8 double mass = 1.989E30; // in kilograms 9 10 cout << "The Sun is " << distance << " kilometers away.\n"; 11 cout << "The Sun\'s mass is " << mass << " kilograms.\n"; output: The Sun is 1.496e+008 kilometers away. The Sun's mass is 1.989e+030 kilograms Floating-point literals are normally stored in memory as doubles. If you need one to be stored as a float, you can append the letter F or f to the end of it. For example, the following literals would be stored as float numbers:. 1.2F, 45.907f

Stream Object

Works with streams of data (such as cout).

fixed

Write floating point values in fixed-point notation

Are arguments are passed to the function parameters in the order they appear in the function call?

Yes

Are function prototypes terminated with a semicolon.

Yes

Does this line contain a valid comment? int twoPi = 3.14459; /* holds the value of two times pi */

Yes

If other functions are defined before main, will the program still starts executing at function main?

Yes

In a function prototype, can the names of the parameter variables may be left out?

Yes

Is scope of a parameter is limited to the function which uses it?

Yes

Can functions have local variables with the same name?

Yes, as the local variables are destroyed when the function terminates.

Can the formal parameter list be empty?

Yes, but in that case empty parentheses () must be included.

Is this function prototype legal: int funcTwo(int width, int length = 1, int height = 1);

Yes.

Is this a legal function overload: (1) void interest (int x, double y) (2) void interest(double x, int y)

Yes. Same number of formal parameters, but their data types differ.

When a function accepts multiple arguments, does it matter in what order the arguments are passed in?

Yes. The first argument is passed into the parameter variable that appears first inside the function header's parentheses. Likewise, the second argument is passed into the second parameter, and so on.

Can return statements be used with void functions?

Yes. The return statement in this case is used to exit the function early.

Sequential Access File

You *access* the data from the beginning of the file to the end of the file.

Single & Multiple-line comments

You have already seen one way to place comments in a C++ program. As illustrated in programs throughout this chapter, you simply place two forward slashes (//) where you want the comment to begin. The compiler ignores everything from that point to the end of the line. This is called a single line comment. Example: 12. int employeeID; // Employee ID number 13. double payRate; // Employees hourly pay rate -------------------------------------------------------- -The second type of comment in C++ is the multi-line comment. Multi-line comments start with /* (a forward slash followed by an asterisk) and end with */ (an asterisk followed by a forward slash). Everything between these markers is ignored. Program 2-22 illustrates the use of both a multi-line comment and single line comments. The multi-line comment starts on line 1 with the /* symbol, and ends on line 6 with the */ symbol. Example: /* 2 PROGRAM: Payroll.cpp 3 Written by Herbert Dorfmann 4 This program calculates company payroll 5 Last modified: 8/20/2012 6 */ When using multi-line comments: Be careful not to reverse the beginning symbol with the ending symbol. Be sure not to forget the ending symbol.

variable initialization

You have also seen that it is possible to assign values to variables when they are defined. When a value is stored in a variable at the time it is defined, it is called initialization. If multiple variables are defined in the same statement, it is possible to initialize some of them without having to initialize all of them. Ex: 1 // This program shows variable initialization. 2 #include <iostream> 3 #include <string> 4 using namespace std; 5 6 int main() 7 { 8 string month = "February"; // month is initialized to "February" 9 int year, // year is not initialized 10 days = 29; // days is initialized to 29 11 12 year = 1776; // Now year is assigned a value 13 14 cout << "In " << year << " " << month 15 << " had " << days << " days.\n"; 16 17 return 0; 18 }

Unless you explicitly initialize global variables, they are automatically initialized to _________.

Zero

The character escape sequence to represent a double quote is:

\"

The character escape sequence to represent a single quote is:

\'

The character escape sequence to force the cursor to go to the next line is:

\n

The character escape sequence to force the cursor to advance forward to the next tab setting is:

\t

syntax

______ rules govern the way a language may be used.

-binary -two -assignment

_______ operators work with _____ operands. The ________ operator is in this category.

operators

_______ perform operations on data.

-ternary -three

________ operators require ________ operands.

-named constants -typographical

_________ can also help prevent __________ errors in a program's code.

literals

_________ may be given names that symbolically represent them in a program.

-programming -spaces -indentions

_________ style refers to the way source code is visually arranged. Ideally, it is a consistent method of putting _________ and _________ in a program so visual cues are created. These cues quickly tell a programmer important information about a program.

Function

a collection of statements to perform a task

what do // mark the beginning of?

a comment

statement

a complete instruction that causes the computer to perform some action

psuedocode

a cross between human language and programming language

local declaration

a declaration of a variable within a block of code for use only within that block

flowchart

a diagram that shows the logical flow of a program

hierarchy chart

a diagram the graphically depicts the structure of a program

value parameter

a formal parameter that receives a copy of the content of the corresponding actual parameter

Reference parameter

a formal parameter that receives the location (memory address) of the corresponding actual parameter.

reference parameter

a formal parameter that receives the location (memory address) of the corresponding actual parameter.

function prototype

a function heading without the body of the function

stub

a function that is not fully coded

signature

a functions name and its formal parameter list

external variable

a global variable declared within a function using the " extern " reserved word; the keyword "extern" indicates that the variable is declared elsewhere

run-time library

a library of prewritten code for performing common operations or sometimes-difficult taks

programmer (or software developer)

a person with the training and skills necessary to design, create and test computer programs

operand

a piece of data (i.e. a number)

portability

a program can be written on one type of computer and then run on many other types of systems

text editor

a program that a C++ program is typed into a computer and saved to a file

preprocessor

a program that reads the source code

driver

a program that tests a function

Software

a sequence of instructions written to solve problems

program

a set of instructions that a computer follows to perform a task

algorithm

a set of well defined steps for performing a task or solving a problem

Sentinel value

a special value that marks the end of a list of values

Variable

a storage location in memory

byte

a storage location that has enough memory to store only a letter of the alphabet or a small number (contains 8 bits)

secondary storage

a type of memory that can hold data for long periods of time - even when there is no power to the computer

Literal

a value that is written into the code of a program

automatic variable

a variable for which memory is allocated at block entry and deallocated at block exit.

static variable

a variable for which memory remains allocated as long as the program executes

Which statement will read an entire line of input into the following string object? a. getline(cin, address); b. cin << address; c. cin.get(address); d. cin address;

a. getline(cin, address);

When an if statement is placed within the conditionally-executed code of another if statement, this is known as: a. nesting b. complexity c. validation d. overloading

a. nesting

Values are stored in...?

adjacent memory locations

Global array

all elements initialized to 0 by default

Local array

all elements uninitialized by default

input - using the cin command

allows the user to enter two items of information: the number of hours worked and the hourly pay rate. Lines 11 and 15 use the cin (pronounced "see in") object to perform these input operations: cin >> hours; cin >> rate; Once information is gathered from the outside world, a program usually processes it in some manner. the hours worked and hourly pay rate are multiplied in line 18 to produce the value assigned to the variable pay: pay = hours * rate;

Reference variables are defined like regular variables, except there is a(n) _________ in front of the name.

ampersand(&)

global identifier

an identifier declared outside of every function definition

local identifier

an identifier declared within a function (or block)

parameter

an identifier in a function header, which acts within the function as a regular local variable; a parameter may be formal or actual

Implicit type conversion (coercion)

an integer and a floating point variable or constant are mixed in an operation, the integer is changed temporarily to its equivalent floating point

scope resolution operator (::)

an operator that, when used, causes a global variable declared before the definition of a function (block) to be accessed by the function (or block), even if the function or block has an identifier with the same name as the variable.

module

another name for a function

Given that x = 2, y = 1, and z = 0, what will the following cout statement display? cout << "answer = " << (x || !y && z) << endl; answer = 0 answer = 1 answer = 2 None of these

answer = 1

input

any information the computer collects from the outside world

output

any information the computer sends to the outside world

To copy one array to another, what do you do?

assign element-by-element: Ex: for (i = 0; i < ARRAY_SIZE; i++) newTests[i] = tests[i];

Each element in an array is...?

assigned a unique subscript - subscripts start at 0

address

assigned to each byte

perform operations on data

assignment operator

x = y

assignment operator

How is a value stored in a variable?

assignment statement

By default, local identifiers are...

automatic variables

What is the output of this code? cout << strcmp("aa","ab") << endl; a. 0 b. -1 c. 1 d. This code will not compile

b. -1

What will be the value of result after the following code has been executed? int a = 60; int b = 15; int result = 10; if (a = b) result *= 2; a. 120 b. 20 c. 10 d. This code will not compile

b. 20

Which line in the following program will cause a compiler error? 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int number = 5; 7 8 if (number >= 0 && <= 100) 9 cout << "passed.\n"; 10 else 11 cout << "failed.\n"; 12 return 0; 13 } a. 6 b. 8 c. 10 d. 9

b. 8

The ________ operator always follows the cin object, and the ________ operator follows the cout object. a. binary, unary b. >>, << c. <<, >> d. conditional, binary

b. >>, <<

This is a variable (usually a bool or an int) that signals when a condition exists. a. arithmetic operator b. flag c. relational operator d. float

b. flag

When a relational expression is false, it has the value ________. a. one b. zero c. zero, one, or. minus one d. less than zero e. None of the above

b. zero

The statement or block that is repeated is known as the __________ of the loop.

body

Declare a variable hasPassedTest , and initialize it to true .

bool hasPassedTest; hasPassedTest = true;

Declare a variable isACustomer , suitable for representing a true or false value .

bool isACustomer;

Modular programming

breaking a program up into smaller, manageable functions or modules

Explicit type conversion (type casting or type conversion)

by the programmer, using the general format: static_cast<DataType>(Value).

When this operator is used with string operands it concatenates them, or joins them together. a. & b. * c. + d. %

c. +

What is the output of this statement? cout << !true << endl; a. false b. true c. 0 d. !true

c. 0

What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 7 b. 10 c. 1 d. The string "x>=y" e. 0

c. 1

The computer's main memory is commonly known as: a.The hard disk b.The floppy disk c.RAM d.Secondary storage e.None of the above

c. RAM

Which data type typically requires only one byte of storage? Select one: a. double b. int c. char d. short e. float

c. char

What is the output of this code? string s = "hello"; s += s; cout << s << endl; a. hello b. hello hello c. hellohello d. This code will not compile

c. hellohello

The numeric data types in C++ can be broken into two general categories: Select one: a. numbers and characters b. singles and doubles c. integer and floating point d. real and unreal e. None of these

c. integer and floating point

A variable with __________ scope is only visible when the program is executing in the block containing the variable's definition. a. global b. limited c. local d. restricted

c. local

You can display the contents of a character array by sending its name to cout:

char fName[] = "Henry"; cout << fName << endl; *But, this ONLY works with character arrays!*

an expression using the conditional operator is called an _______ expression

conditional

linker

connect hardware-specific code to machine instructions, prodding an executable file

signature (of a function)

consists of the function name and its formal parameter list

Internally, the CPU consists of the __________ and the __________.

control unit / arithmetic and logic unit (ALU)

CPU (Central Processing Unit) contains what 2 units

control unit and ALU

operating system

controls the internal operations of a computer's hardware, manages all the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer

preprocessor

converts source file directives to source code program statements

Assume that word is a string variable . Write a statement to display the message "Today's Word-Of-The-Day is: " followed by the value of word on standard output .

cout << "Today's Word-Of-The-Day is: " << word ;

2.3 The following cout statement contains errors. Correct it so that it will display a list of colors, with one item per line. cout << "red /n" << "blue \ n" << "yellow" \n << "green";

cout << "red \n" << "blue \n" <<< "yellow \n" <<< "green";

% requires integers for both operands

cout << 13 % 5.0; // error

Assume that message is a string variable . Write a statement to display its value on standard output .

cout << message ;

Arrays must be accessed via individual elements:

cout << tests; // not legal

executable file

created after a linker finishes

function overloading(overloading a function name)

creating several functions with the same name but different formal parameter lists

5.8..#51156 Write the definition of a function add, that receives two int parameters and returns their sum.

def add(int1,int2): >>> return int1+int2 **Remember to tab (>>>) or space

5.8.. #51152 Write the definition of a function half which receives a variable containing an integer as a parameter and returns another variable containing an integer, whose value is closest to half that of the parameter. (Use integer division!) Instructor Notes: Write a definition for a function half which receives one parameter and returns half the parameter's value. Use regular division and convert the result to an int before returning it. KJ

def half(value): >>> return int(value/2)

5.8.. #51164 Define a function called isEven that takes a parameter containing an integer value and returns True if the parameter is even, and False otherwise.

def isEven(int): >>> if int%2==0: >>> >>> return True >>> else: >>> >>> return False

5.8.. #51157 Define a function called isPositive that takes a parameter containing an integer value and returns True if the parameter is positive or False if the parameter is negative or 0.

def isPositive(int): >>> if int>0: >>> >>> return True >>> else: >>> >>> return False

5.8.. #51159 Define a function called isSenior that takes a parameter containing an integer value and returns True if the parameter is greater than or equal to 65, and False otherwise.

def isSenior(int): >>> if int>=65: >>> >>> return True >>> else: >>> >>> return False

5.8..#51151 Write the definition of a function oneLess which receives a parameter containing an integer value and returns an integer whose value is one less than the value of the parameter.

def oneLess(int): >>> return int-1

5.8..#51142 Write the definition of a function oneMore which recieves a parameter containing an integer value and returns an integer that is one more than the value of the parameter. Instructor Notes: Write the definition of a function oneMore which receives one parameter (name of your choice) and returns a number that is one more than the value of the parameter. KJ

def oneMore(int): >>> return int+1

5.8.. #51141 [Functions >> functions and if statements] Write the definition of a function powerTo which receives two parameters, a double and an integer. If the second parameter is positive, the function returns the value of the first parameter raised to the power of the second. Otherwise, the function returns 0. Instructor Notes: Write the definition of a function powerTo which receives two parameters (names of your choice). If the second parameter is >= 0, return the value of the first parameter raised to the power of the second parameter. Otherwise, return 0.

def powerTo(adouble,aint): >>> if aint>=0: >>> >>> return adouble**aint >>> else: >>> >>> return 0

5.8..#51139 Write the definition of a function square which receives a parameter containing an integer value and returns the square of the value of the parameter. Instructor Notes: Write the definition of a function named square which receives one parameter and returns the value of the square of the parameter. You may call the parameter anything you like.

def square(int): >>> return int**2 **Remember to tab (>>>) or space

5.8..#51155 Write the definition of a function twice, that receives an int parameter and returns an int that is twice the value of the parameter. Instructor Notes: Write the definition for a function named twice. The function should receive a parameter and return the value that is twice the value of the parameter. You may call the parameter anything you like. KJ

def twice(int): >>> return 2*int **Remember to tab (>>>) or space

5.8..#51016 Write the definition of a function typing_speed, that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float). Instructor Notes: Write the definition of a function named typing_speed that receives two parameters, a variable that is the number of words typed and a second variable that is the length of time in seconds that typing occurred (variable names of your choice). The function should return the typing speed in words per minute. KJ

def typing_speed(num_words,time_interval): >>> num_words>=0 >>> time_interval>0 >>> result=float(60*num_words/time_interval) >>> return result **Remember to tab (>>>) or space

A variable must be _____ before it can be used in a program.

defined

A variable must be __________ before it can be used in a program.

defined

empty() member function is used for?

determining if a vector is empty: Ex: while (!scores.empty())

size() member function is used for?

determining the size of the vector: Ex: howbig = scores.size();

A(n) __________ is an example of a secondary storage device.

disk drive / USB

do while loop

do statement; while (expression); -will always execute at least once

Declare a numerical variable precise and initialize it to the value 1.09388641.

double precise = 1.09388641;

Given two double variables , bestValue and secondBestValue , write some code that swaps their values . Declare any additional variables as necessary.

double temp; temp = bestValue; bestValue = secondBestValue; secondBestValue = temp;

After execution of the following code, what will the value of input_value be if the value 0 is entered at the keyboard at run time? cin >> input_value; if (input_value > 5) input_value = input_value + 5; else if (input_value > 2) input_value = input_value + 10; else input_value = input_value + 15; a. 0 b. 25 c. 5 d. 10 e. 15

e. 15

Which escape sequence causes the cursor to move to the beginning of the current line? Select one: a. \t b. \a c. \n d. \b e. \r

e. \r

5.7..#51146 Given that add, a function that expects two int parameters and returns their sum, and given that two variables, euro_sales and asia_sales, have already been defined: Write a statement that calls add to compute the sum of euro_sales and asia_sales and that associates this value with a variable named eurasia_sales.

eurasia_sales =add(euro_sales,asia_sales)

Variable Definition (data types)

ex. double hours, rate, pay; The word double in the statement indicates that the variables hours, rate, and pay will be used to hold double precision floating-point numbers. This statement is called a variable definition. In C++, all variables must be defined before they can be used because the variable definition is what causes the variables to be created in memory.

The _________ function causes a program to terminate.

exit()

What will be the output of the following code segment after the user enters 0 at the keyboard? int x = -1; cout << "Enter a 0 or a 1 from the keyboard: "; cin >> x; if(x) cout << "true" << endl; else cout << "false" << endl; Nothing will be displayed. false x true

false

Write a literal representing the false value in C++.

false

its safe to assume that all uninitialized variables automatically start with 0 as their value

false

the = operator and the == operator perform the same operation when used in a Boolean expression

false

the if statement regards an expression with the value 0 as

false

when an if statement is nested in the else aprt of another statement as in an if/else if the only time the inner if is executed is when the expression of the outer if is true

false

the value of a relation expression is 0 is the expression is _______ or 1 if the expression is ___________

false true

3 data types that can represent floating point numbers

float or single precision (4 bytes) double or double precision (8 bytes) long double or long double precision (8 bytes)

Declare a variable temperature and initialize it to 98.6.

float temperature = 98.6;

Used to define variable that can hold real numbers; a data type that allows fractional values

floating-point data types

Object-Oriented programming:

focus is on objects, which contain data and the means to manipulate the data. Messages sent to objects to perform operations.

Procedural programming:

focus is on the process. Procedures/functions are written to process data.

for loop

for (initialization; test; update) statement; -pretest loop - can have multiple initializations and updates, just separate with commas -ANY OR ALL of the three for loop sections can be ommtted -IF OMITTED, it is taken as true -ONLY OMMIT if the initializations have already been done

output device

formats and presents output (i.e. monitors, printers, and speakers)

A group of one or more programming statements that collectively has a name

function

Either a function's _________ or its _________ must precede all calls to the function.

functions defintion or prototype

Write an if statement that performs the following logic: if the variable price is greater than 500, then assign 0.2 to the variable discountRate.

if (price > 500) discountRate = 0.2;

syntax errors

illegal uses of key words, operators, punctuation, and other language elements

Definition of the function

includes the name of the function, a listing of the parameters if any, the data type of each parameter, the data type the value computed (that is, the value returned) by the function, and the code required to accomplish the task .

function header (heading)

includes the name of the function, the number of parameters if any, the data type of each parameter, and the data type of the value returned by the function

Opening Files

infile.open("report.txt"); outfile.open("stats.txt"); -IF opening a file for output, the output file will be created if it doesnt exist. -if it does exist the old oe will be erased and new one will have the same name

Inside the for loop's parentheses, the first expression is the

initialization

assign values to variables as part of the definition

initialization

Nested loops with Inner and Outer

inner loop iterates through all repetitions for the outer loop -TOTAL repetitions for the inner body is the product of the # of repetitions of the two loops

The three primary activities of a program are __________, __________, and __________.

input / processing / output

When a program lets the user know that an invalid choice has been made, this is known as: input validation output correction compiler criticism output validation None of these

input validation

The three primary activities of a program are _____, _____, and _____.

input, processing, output

A program is a set of _____.

instructions

A program is a set of __________.

instructions that a computer follows to perform a task.

2.14 How would you combine the folowwing variables definition and assignment statement into a single statement? int apples ; apples = 20 ;

int apples = 20;

Declare an integer variable cardsInHand and initialize it to 13.

int cardsInHand = 13;

Can initialize some or all variables:

int length = 12, width = 5, area;

Declare and initialize the following variables : A variable monthOfYear , initialized to the value 11 A variable companyRevenue , initialized to the value 5666777 A variable firstClassTicketPrice , initialized to the value 6000 A variable totalPopulation , initialized to the value 1222333

int monthOfYear = 11, companyRevenue = 5666777, firstClassTicketPrice = 6000, totalPopulation = 1222333;

Write a statement that declares an int variable presidentialTerm and initializes it to 4.

int presidentialTerm = 4;

...

int temp; temp=firstPlaceWinner; firstPlaceWinner=secondPlaceWinner; secondPlaceWinner=temp;

2.15 how would you combine the following variable definitions into a single statement? int xCoord = 2; int yCoord = -4; int zCoord = 6;

int xCoord = 2, yCoord = -4, zCoord = 6;

Write a declaration of an int variable year and initialize it to 365.

int year = 365;

the expression that is tested by a switch statement must have a ______ value

integer

the expression following a case statement must be an

integer literal or constant

Default argument

is an argument that is passed automatically to a parameter if the argument is missing on the function call.

Words that have special meaning in a programming language are called _____.

key words

programming language

language that uses words instead of numbers

high-level languages

languages that are closer to the level of human-readability than computer-readability (easiest language for people to learn)

the logical operators have ______ associativity

left to right

<=

less than or equal to

Predefined functions are organized into...

libraries

return statement

line at the end of a function that causes it to send a value back to the main function.

If a function has a local variable with the same name as a global variable, only the _________ variable can be seen by the function.

local

executable code

machine language instructions that is ready to run on the computer

How many functions can main call?

main can call any number of functions

RAM (random access memory )

main memory, volatile

Comments are generally added to programs because

many programs are complicated and comments help explain what is going on

punctuation

mark the beginning or ending of a statement, or separate items in a list

What is a pretest?

means the expression is evaluated before the loop executes.

Local variables

memory for the formal parameters and variables declared in the body of a function

volatile memory

memory that is used only for temporary storage while a program is running

variable

named storage location in the computer's memory for holding a piece of information

C++ uses ___ to organize the names of program entities.

namespaces

the if/else if statement is actually a form of the ______ if statement

nested

When an if statement is placed within the conditionally-executed code of another if statement, this is known as: complexity overloading nesting validation None of these

nesting

!=

not equal to

C String

null terminated string -String literals are stored in memory as null-terminated C-strings, but string objects are not

binary numbers

numbers consisting of only 1s and 0s

off-by-one error

one fewer iteration or one too many

the data that operators work with

operands

scope resolution operator (::)

operator that overrides the limits on global variables caused by identifier names. Allows a global identifier to be used inside a function that otherwise would be forbidden

Using Files

outfile << "ceci is awesome"; write to file infile>> num; read from file -The stream extraction operator >> returns true when a value was successfully read, false otherwise. -Can be tested in a while loop to continue execution as long as values are successfully read from the file: while (inputFile >> number)

utility program

performs a specialized task that enhances the computer's operation or safeguards data

operators

performs operations on one or more operand

A program's ability to run on several different types of computer systems is called _____.

portability

A program's ability to run on several different types of computer systems is called __________.

portability

2^3 and 5^9

pow (2, 3) and pow (5, 9)

Reads your program before it is compiled and only executes those lines beginning with the # symbol

prepocessor directive

"sets up" your source code for the compiler

preprocessor directive

application software

programs that make the computer useful for everyday tasks

cstdlib header file:

rand(): returns a random number (int) between 0 and the largest int the compute holds. Yields same sequence of numbers each time program is run. srand(x): initializes random number generator with unsigned int x

Reference variables allow arguments to be passed by ____________.

reference

When used as parameters, _________ variables allow a function to access the parameter s original argument.

reference

scope

refers to where an identifier is accessible (visible) in a program

An expression using greater-than, less-than,greater-than-or equal to, less-than-or equal to, equal, or not-equal to operator is called an _________ expression

relational

pop_back member function is used for?

removes last element from vector: Ex: scores.pop_back();

clear() member function is used for?

removing all contents of a vector: Ex: scores.clear();

The _________ statement causes a function to end immediately.

return

How do you return a value from a function?

return 10; return ( functionName ());

syntax

rules that must be followed when constructing a program

disk drive

secondary storage that stores data by magnetically encoding it onto a circular disk

Every complete statement ends with a __________.

semicolon

5.5..#51074 Write the code to call a function whose name is send_number. There is one argument for this function, which is an int. Send 5 as an argument to the function.

send_number(5)

5.2.#51073 Write the code to call the function named send_signal. There are no parameters for this function.

send_signal()

5.5..#51076 Write the code to call a function named send_two and that expects two parameters: a float and an int. Invoke this function with 15.955 and 133 as arguments.

send_two(15.955,133)

5.5..#51075 Write the code to call a function named send_variable and that expects a single int parameter. Suppose a variable called x refers to an int. Pass this variable as an argument to send_variable.

send_variable(x);

setw( )

set space number. Allowing for text to look sharper

Stream Manipulator that affects just the next value?

setw(x): print in a field at least x spaces wide. Use more spaces if field is not wide enough

To declare the range variable as a reference variable what do you write?

simply write an ampersand (&) in front of its name in the loop header

machine language

stream of binary numbers

2.23 What header file must you include in order to use string objects?

string

Declare a string variable named empty and initialize it to the empty string .

string empty;

Declare a string variable named mailingAddress .

string mailingAddress;

Declare a string variable named oneSpace and initialize it to a string consisting of a single space.

string oneSpace; oneSpace = " ";

Declare a string variable named str and initialize it to Hello .

string str; str = "Hello";

Declare 3 string variables named winner , placed and show .

string winner, placed, show;

The two general categories of software are __________ and __________.

system software / application software System software: - Operating systems (controls the internal operations of the computer's hardware, manages all the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer) - Utility programs (A specialized task that enhances the computer's operation or safeguards data. Ex: virus scanners, file-compression programs, and data-backup programs) - Software development tools (tools that programmers use to create, modify, and test software. Compilers and IDE's [integrated development environments]) Application software: - Microsoft Word, Chrome, PowerPoint

body (of a function)

the code within the function required for accomplish the task

If you place a semicolon after the statement if (x < y) the code will not compile the compiler will interpret the semicolon as a null statement the if statement will always evaluate to false All of these None of these

the compiler will interpret the semicolon as a null statement

return type (of a function)

the data type of the value that the function returns; also called the data type of the function.

input device

the device that collects the information and sends it to the computer (i.e. Disk drivers, CD/DVD drives, USB drives)

truncated

the entire fractional component is cut off

source file

the file that source codes are saved in

control unit

the part of the CPU that coordinates all of the computer's operations

ALU (Arithmetic and Logic Unit)

the part of the CPU that is designed to perform mathematical operations

CPU (Central Processing Unit)

the part of the computer that actually runs programs

fetch / decode / execute cycle

the process that the CPU is engaged in when the computer is running a program

procedural programming

the programmer constructs procedures (or functions)

system software

the programs that control and manage the basic operations of a computer

in an if/else statement, the if part executes its statement or block if the expression is _______ , and the else part executes its statement or block if the expression is _______

true false

Return type or data type (of a function),

type of the value that the function returns.

2.13 Which integer data types can only hold non-negative values?

unsigned short, unsigned int, and unsigned long

Inside the for loop's parentheses, the third expression is the

update

low-level language

used for communication with computer hardware directly

software development tools

used to create, modify, and test sofware

variable definition

used to define one or more variables that will be used in the program and to indicate the type of data they will hold

Sentinel:

value in a list of values that indicates end of data

A _____ is a named storage location.

variable

A(n) __________ is a named storage location.

variable

formal parameter

variable declared in the function heading

Local identifier

variable declared within a function or block

automatic variable

variable for which memory is allocated at block entrance and immediately discarded at block exit

static variable

variable for which memory remains allocated for the entire duration of the program.

When a function terminates, it always branches back ___.

where it was called from.

main memory

where the computer stores a program while the program is running, as well as the data that the program is working with

The while loop

while (expression) statement; - must contain code to make expression become false. -can result in infinite loop

Function headers are terminated ____ a semicolon.

without

programmer-defined identifiers

words or names defined by the programmer

key words

words that have a special meaning and can only be used for their intended purpose

Which of the following expressions will determine whether x is less than or equal to y? x > y x =< y x <= y x >= y

x <= y

What will be displayed on the screen? Variable a = 1 Variable b = 10 Variable c = 100 Variable x = 0 Store the value of c times 3 in x Add the value of b times 6 to the value of x Add the value of a times 5 to the value of x what is x?

x = 365

x %= y

x = x % y

x *= y

x = x * y

x += y

x = x + y

x -= y

x = x - y

x /= y

x = x / y

The three rules to using the pow( ) function

1. Must include <cmath> header file. 2. The arguments that you pass should be doubles. 3. The variable used to store pow's the return value should be a double.

C++ Library

A collection of specialized functions.

cin

A standard input object that can be used to read data typed at the keyboard. (It causes a program to wait until data is typed at the keyboard and the enter key is pressed).

Assignment Statement

A value is stored in a variable.

Initialization

Assigning values to variables as apart of their definition. i.e. int number = 10;

<iomanip>

Header file that must be used for manipulating output. (i.e. when using setw( )).

Integer Data Type

Integers and whole numbers.

;

Marks the end of a programming statement.

\n

Newline escape sequence which advances the output cursor to the next line. Stored in memory as a single character.

rvalue

Operand on the right side of the assignment symbol.

Namespaces

Organizes the names of program entities,

Scope

Part of the program where the variable may be use.

sizeof ( sizeof(int) )

Reports the number of bytes of memory used by any data type or variable.

false

Represented by the value 0.

true

Represented by the value 1.

/* */

Represents a multi-line comment.

//

Represents a single-line comment.

Prompt

Tells the user what data he/she should enter.

int

Typically 4 bytes in size. Ranges from -2,147,483,648 to +2,147,483,647.

How many operands does each of the following types of operators require? - Unary - Binary - Ternary

Unary - one operand Binary - two operand Ternary - three operand

Write an if statement that performs the following logic: if the variable sales is greater than 50,000, then assign 0.25 to the comissionRate variable and assign 250 to the bonus variable.

if (sales > 50000) { comissionRate = 0.25; bonus = 250; }

Write an if/else statement that assigns 0.10 to commissionRate unless sales is greater than or equal to 50000.00, in which case it assigns 0.20 to comissionRate.

if (sales >= 50000.00) commissionRate = 0.20; else commissionRate = 0.10;

Write an if statement that prints the message "The number is not valid" if the variable speed is outside the range 0 through 200

if (speed <= 0 && speed >= 200) cout << "The number is not valid.";

Write an if statement that performs the following logic: if the variable x is equal to 20, then assign 0 to the variable y

if (x == 20) y = 0;

Write an if/ else statement that assigns 1 to x if y is equal to 100. Otherwise it should assign 0 to x.

if (y ==100) x = 1; else x = 0;

A _________ is like a variable, but its value is read-only and cannot be changed during the program's execution

named constant


Related study sets

Ch. 4 Physical Science study guide - Atomic Structure

View Set

True/False Westing Game Questions

View Set

accounting 201 chapter 5: receivables and sales

View Set

Chapter 10 Organizational Change and Leadership Processes

View Set

Med Surg Exam 3 Practice Questions

View Set

Topic 2.2 Transport Across Cell Membranes - 2.2.3 Diffusion

View Set

GERIZAL Module 2 BEFORE 19TH CENTURY

View Set