CMPSC 201 Exam 1 Flashcards

1
Q

What is a computer?

A

A programmable electronic device that can
store, retrieve and process data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Advantages of computers

A

Reliable, Fast, Does not tire,
Follows instructions (programs) precisely

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Disadvantages of computers

A

Not “smart”– cannot analyze problems
Follows instructions (programs) precisely

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What can a computer do?

A

Arithmetic, Comparisons/decision making, Communication-input, output, transfer of data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

CPU

A

fetches and follows a set of simple instructions
(also called processor).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Main Memory

A

stores the executing program and its data in RAM
(random access memory). Volatile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Volatile Memory

A

Volatile memory is a type of memory that requires a constant power supply to retain data. When the power is turned off, all data stored in volatile memory is lost. This type of memory is typically used for temporary storage and fast data access.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Secondary Memory

A

stores permanent records (files). Non-volatile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Non-volatile Memory

A

Non-volatile memory (NVM) is a type of computer memory that retains stored information even after power is removed. This makes it ideal for long-term data storage and secondary storage applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Examples of Secondary Memory

A

hard disks, USB-drives,
CD-ROMs, DVDs, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Components of a Computer

A

Input Device, CPU, Main Memory, Secondary Memory, Output Device

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

ALU

A

Part of CPU stands for Arithmetic and Logic Unit performs mathematical operations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Control Unit

A

Control Unit coordinates all of the computer’s operations, performs the
fetch/decode/execute cycle
Fetch: Control Unit fetches next instruction
Decode: Control Unit decodes instruction
Execute: instruction is executed by appropriate
component

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

RAM Main Memory

A

consists of a long list of numbered memory
locations (RAM). Main memory is volatile!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Memory Locations

A

contain zeros and ones, on and off switches,
called binary digits or bits

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Byte

A

8 bits 1 address for the memory stored there

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Storage of Secondary Memory

A

Uses same idea of bits and bytes
Programs/data stored in units called files.
Stores files when they are not in use

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Operating Systems

A

Operating Systems – allocates computer’s
resources and allows communication between
user and computer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Programs/Program

A

a set of instructions to perform
specific tasks. / A set of instructions a computer
follows to perform a task. An algorithm that has
been translated into a programming language so
the computer can “understand” and perform the
steps.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Programming language

A

special language used
to write programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Algorithm

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

High Level Languages

A

designed to be easy for humans to read
and to write programs in, but too complicated for the computerand to write programs in, but too complicated for the computer
to understand

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Low Level Languages

A

consist of simple instructions which can
be understood by the computer after a minor translation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Compiled Languages

A

a separate file is created for the translated binary
code (C++, Java, FORTRAN, etc.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Interpreted Languages
each command is interpreted and executed as program is run (MATLAB, Python, etc.)
26
Machine Language
written in the form of zeros and ones, can be understood directly by the computer
27
High Level to Machine Code Steps
Source Code - Preprocessor - Compiler - Linker - Executable Code
28
Source Code
Source file created by a text editor *.cpp
29
Preprocessor
Modifies source code by instructions (#) A library of already written source code
30
Compiler
Translates to Machine Code *.obj and checks for syntax errors
31
Linker
Combines various object code files to create an executable file *.exe
32
Key Words
reserved words that have a special meaning. (often shown in blue)
33
Programmer Defined Symbols
words or names that have been defined by the programmer. May be variables, constants, or functions/routines.
34
Operators
tell the computer to perform specific operations.
35
Punctuation
begins or ends a statement, or separates items of a list.
36
Syntax
grammar rules for combining elements.
37
Syntax Errors
code does not follow the grammar rules of language. Found by the compiler.
38
Logic Errors
results are not what was expected due to incorrect implementation. (Note different from text!) Use test data for which you know what the results should be.
39
Run-time Errors
program causes the computer to perform an illegal operation. (Note different from text!) Divide by 0 or square root of negative number.
40
Input
data the user of the program will need to enter into the program
41
Output
information the user expects to receive from the program.
42
Processing
what the program does to the input to produce the output. Examples: Calculate weekly pay Calculate the area of a rectangle
43
#include
Preprocessor Directive; comes before everything else in the program except the explanatory comment at the top
44
using namespace std;
Follows #include
45
Algorithm vs Program
All Algorithms are programs, but not all programs are algorithms
46
Fetch
CPU gets, from main memory, the next instruction in the sequence of a program's instructions
47
Decode
The instruction is encoded in the form of a number, The control unit decodes the instruction and generates an electric signal
48
Execute
After decoding the signal is sent to the correct part of the computer and causes that component to perform an operation
49
System Software
Controls and manages the basic operations of a computer
50
Utility Programs
enhance the computer's operations and safeguards data
51
Application Software
makes the computer useful for everyday tasks. Games, browsers, word, etc.
52
Constant Declarations
happen before the main function but after "using namespace std;" for global usage Format: const data type identifier = value;
53
int main()
The main function that holds all of the code be sure to use BRACES
54
variable declarations
happen first within the int main function and set variables for your program
55
return 0;
Marks the end of the program and lets the computer know to stop
56
Test Data
input for which the programmer knows the result
57
4 Types of Control Structures
Branch, Loop, Sequence, Functions
58
Branch Control Structure (decision)
some statements may be executed only when a specific condition is met.
59
Loop Control Structure (repetition)
statements are repeated
60
Functions Control Structure
a group of statements are executed at various times in the program
61
Sequence Control Structure
statements are executed in order they are written
62
Comments
describe what the program is supposed to do and what various portions do. Often used as documentation. Not executed.
63
Preprocessor Directives
directions to perform before program starts.
64
Functions (Not the control structure)
group of statements to perform a specific task.
65
Statements
actions executed by the computer.
66
// double slash
beginning of a single line comment
67
/* */ slash asterisk
Go around a multiline comment
68
octothorp (hashtag)
beginning of a preprocessor directive
69
< > brackets
enclose filenames or data types
70
(_) parentheses
contains parameters for functions or changes order of operations.
71
{_} braces
enclose a group of statements.
72
; semicolon
ends a C++ statement
73
include Directive
Preprocessor directive Causes contents of another file to be inserted into the program. Often the files are library files that contain specific definitions. Not C++ statements
74
Case Sensitive Languages
C++ is one so Include is not the same as INCLUDE or include.
75
Main function
All C++ programs must have a function main int main ()
76
C++ Output Statement
cout "c" + "out"
77
What is needed for cout?
cout object, the insertion operator(s) (<<), and variables or constants to be displayed. cout <<“Hello”;
78
What is needed for multiple items to be output using the same cout statement?
<< insertion operator Ex: cout<<“The volume is ” <
79
Escape Sequences
Performs specific output tasks when enclosed in quotes. (cout is still needed)
80
\n
Causes cursor to go to next line
81
\t
Causes cursor to go to next tab stop
82
\a
Causes computer to beep
83
\\\ (Escape Sequence)
Causes backslash to be printed
84
\\'
Causes single quote to be printed
85
\\"
Cause double quote to be printed
86
endl manipulator
Inserts blank lines in output just like the escape sequence. cout << radius << endl << volume; radius volume
87
Blanks in cout
Blanks may be inserted by enclosing the spaces in quotes. cout << radius << “ ” << volume; radius volume
88
Identifiers
names (or symbols) used by the programmer to refer to items such as variables, named constants, functions, classes, etc. should be descriptive of what they stand for.
89
Identifier Rules
Cannot be a reserved word (keyword) only can contains letters, numbers, or the underscore. first character must be a letter or underscore (better to be a letter).
90
Variables and symbolic constants
names for memory locations in RAM.
91
Variables
refer to memory locations in which the value stored may change throughout the execution of the program.
92
Named or symbolic constants
refer to memory locations in which the values do not change.
93
definition/declaration
statements that tell the computer to allocate memory space and what identifier will be used to refer to that space. you must define or declare a variable or constant before you may use it.
94
Variable Declarations Format
data type variable name; where the variable name must follow the identifier rules.
95
Data Types definition
determines how the data will be stored and what types of operations can be performed on this data.
96
Data Type Examples
Integers (whole numbers), Real Numbers (may have fractional parts), Characters (letters or numbers that you do not want for arithmetic operations), and Boolean (true or false)
97
Integer variables
memory spaces that will store whole numbers
98
Integer Data Types and size
short 2 bytes unsigned short 2 bytes int 4 bytes unsigned int 4 bytes long int 4 bytes unsigned long 4 bytes long long int 8 bytes
99
Floating Point Data
Used to store real numbers, numbers with fractional parts
100
Floating Point Data Types
float 4 bytes single precision numbers double 8 bytes double precision numbers long double 10 bytes
101
Precision
refers to the number of digits that are stored before the values are rounded.
102
Boolean Data
data that is either true or false False is represented as 0 in the computer. True is represented as 1. Anything other than 0 (zero) is considered to be true. Written: bool
103
Character Data
Written: char holds a single character value two methods to store multiple characters: C-strings or string objects.
104
C-Strings
arrays (collections) of characters. The number in brackets should include space for the null character. Ex: char variablename[n]; Can be assigned a value at time of declaration however the assignment operator does not work later.
105
String Objects
# include variables that have be declared of the string class. To use the string class, you must employ the preprocessor directive. string variable name; You do not need to know how many characters need to be stored. Can use assignment operator name = “Tom”;
106
Default Data Type for whole numbers
int
107
Default Data Type for floating point numbers
double
108
Global Scope
Occur before main function and will be the same value to all functions (for constant declarations)
109
Local Scope
Declaration only applies to that variable or constant within the function it is defined You should usually define, declare, the variables at the beginning of the function (for now main) in which they occur.
110
Multi Variable Declaration Format
int alpha, beta, gamma, delta; double weight, feet;
111
Assignment Statements
store values in the memory locations.
112
Assignment Operator
= (Not the same as equals)
113
Assignment Rules
Named constants must be assigned at the time they are declared. Assignments to variables can occur at the same time as declaration or after. EX: int numberincase = 12; The left and right side cannot be interchanged! X = 5; (valid) is not the same as 5 = X; (Not Valid) The left-hand side must be a single variable.
114
What happens when a floating-point number is stored in an int?
It gets truncated 4.57 => 4
115
Assigning char Values
Reminder a variable declared as char can only store 1 character (letter, digit, special character)! To store more than character you must use a string (character array). ‘w’ is a single character whereas “w” is two characters (w and the null character). char var1 = ‘w’; char var1 = “w” // invalid var1 = ‘r’; var1 = “r”; //invalid char str1[2]=“q” ; char str1=“t”; //invalid
116
Strings
a collection of characters. two methods of creating strings in C++. C-strings, String objects (requires the string class)
117
Arithmetic Operators
manipulate numeric values and perform arithmetic operations. Classified as unary, binary, or ternary based on the number of operands needed.
118
Unary
one operand -a
119
binary
requires two operands. X + Y c / b
120
ternary
three operands
121
Operand
+, -, *, /, % things like that
122
Binary Arithmetic Operators
+ Addition sum = y + x - Subtraction diff = x - y * Multiplication numb = c * b / Division rate = part / total % Modulus remainder = d % 4
123
Data Type and Operator Changes
Integers operated on by integers result in an integer Floating points operated on by integers or floats result in floating points
124
Precedence
Defines the order in which operations are performed.
125
Arithmetic Operator Precedence
Operations in parentheses are performed first Unary negation * / % multiplication, division, modulus + - addition and subtraction Operations of equal precedence are performed in order they are written from left to right.
126
Number Representation of int vs. floating point number
int ==> 4 float ==> 4.0
127
Multiple Assignments
A single assignment statement may be used to store the same value in multiple variables at one time. x = y = h = d = k = 4.0; Could be used to replace the statements x = 4.0; y = 4.0; d = 4.0; h = 4.0; k = 4.0;
128
C++ Input Object
cin object and extraction operator to read data from keyboard and store in memory locations. cin>> variablename;
129
When does input stop?
when white space (space, tab, newline) is encountered.
130
Multiple Input Values
separated by extraction operators. cin>>x>>y; //data is stored in order given
131
Cin and Data Types
cin does not confirm data type. A char variable only stores one character (letter, digit, or special character). Using cin will allow the extraction of 1 character from the input stream. If more than one character are entered, the first is stored in the variable and the rest remain in the input stream. White spaces are skipped.
132
Cin with C-strings
Remember a C-string is an array of characters and may be declared as char varname[n]; char last[12]; You can use cin to store characters in this C- string. cin>>last; Input will stop is a white space is encountered. There is no check for number of characters.
133
Data Overflow/Underflow
C++ does not check for data being within range of data type. How the data is stored may be compiler dependent. In many compilers, the number will “wrap”. For example, given the following statements short x = 32767; x = x + 5; cout<< x<
134
Data Type Coercion
Automatic conversion of a data type for mathematical operations or assignment. int alpha = 10.5; // 10.5 is coerced to 10 double beta = 4; // 4 is coerced to 4.0 alpha = alpha/beta; //two coercions occur //10 is coerced to 10.0 for the division //the value 2.5 is truncated to 2 for assignment. beta = alpha * 4.4;
135
Type Casting
Code specifies the conversion of the data type for the purposes of an operation. Type casting a variable will not change what is stored in a variable
136
Three Methods of Type Casting
static_cast(variable or expression) data type (variable or expression) (data type) variable or expression Last two methods considered out of date
137
What are 2 ways to change what is stored in a variable?
Assignment statement Input new value
138
Define
Utilizes a preprocessor directive to associate a value with a word. The data type is not needed because no memory space is allocated. No memory space is used. The preprocessor will replace the word with the value. (Similar to find and replace in word processing) Because no memory is used, the data type of the value is not needed.
139
Define Format
#define identifier value EX: #define tax_rate 4.5
140
Compound Operator
Provide a shortcut for assignment statements. Combines the = operator with another arithmetic operator
141
a+ = 5.67;
is equivalent to a = a + 5.67; a %= 3; is equivalent to a = a % 3; Reminder---the % operator only works for integer data types.
142
a -= 6.0;
is equivalent to a = a – 6.0;
143
a *= 3.4;
is equivalent to a = a * 3.4;
144
a /= 2.1;
is equivalent to a = a /2.1;
145
a %= 3;
is equivalent to a = a % 3; Reminder---the % operator only works for integer data types.
146
Built-In Functions
a library file, like cmath, with a function defined that has the format of Ex: pow(base, exponent) pow(x,y) is equivalent to x^y... Use the include preprocessor directive to tell the program to incorporate the library file #include
147
Trig Functions Assumption
that the angle is in radians not in degrees
148
Random Numbers
The rand( ) function is used to generated random numbers, how the numbers are generated in the same order each time the program is run. cout<
149
Seed
Used with random values to skip the first “seed” values. Can use another built-in function time( ) to generate a value for the seed. unsigned seed = time(0); //generate a value srand(seed); // skip seed values cout<
150
What library file does the rand() function need?
cstdlib library file
151
How to limit the range of rand() function?
The random number can be limited to a range using arithmetic principles. y = rand( ) % value + 1; // numbers from 1 to value will be generated For example, to generate numbers from 1 – 15 y = rand( ) % 15 + 1;
152
Random Numbers Other than rand() function
include Random number engine random_device // one engine type random_device Myrandgen; //defines an engine
153
Distribution Object
uniform_int_distribution randInts(0,100); Object Type states how numbers will be distributed, Object name (Number range (min value, max value))
154
Other random number use
Use the object to store a generated number int number number = randInts(Myrandgen);
155
setw() Manipulator
controls the number of spaces that will be used to output an item cout<
156
setprecision() Manipulator
used to control the number of significant digits or, if used with the fixed manipulator, the number of decimal places that will be displayed for a floating-point number. cout<
157
showpoint Manipulator
set to show the decimal point and zeroes for numbers like 45.0
158
Other Manipulators
left - sends output left justified right - sends output right justified Can use more than one manipulator at a time, just separate with the << operator. The programmer can also change manipulators within the same cout statement. Ex: cout<
159
Formatting Input/Output alternative
cout.width(5) instead of cout<
160
How to specify how many characters you want to store in a string?
can use cin.width(n) or cin>>setw(n) However, input still stops when a space or tab is encountered.
161
cin.get()
To store “white spaces”, spaces, tabs, and/or returns, in char variables use cin.get( ). It has the format cin.get(varname) Often can be used to stop the program until the user enters a return If storing in a character array (C-string) the format may be expanded to cin.get(varname, n, ‘char’)
162
getline
To store multiple characters, including spaces, in string objects. getline(cin, strname); Input stops when a newline character, ‘\n’ is encountered. Will store leading spaces as well.
163
cin.ignore()
Used to skip over characters that you do not want to be stored anywhere. Has the format cin.ignore(n, ‘char’) where n is the number of characters to be skipped and char specifies where skipping should stop. Skipping stops whenever the one of criteria is met. If char stops input, the char remains in the input stream so it may input.
164
Hand Tracing
Given test data the programmer should be able to predict what is stored in each variable at each line of code.
165
Relational (Boolean) Expressions
expressions that evaluate to true or false. They may be comprised of a bool variable or constant; or a combination of variables and constants using relational and/or logical operators. Relational expressions are used for both selection and repetition control structures.
166
Relational Operators
Used to compare, or relate, two values (variables or constants) May be used with string objects, but not with C-strings (character arrays)
167
equal to relational operator
==
168
not equal to relational operator
!=
169
greater than relational operator
>
170
less than relational operator
<
171
greater than or equal to relational operator
>=
172
less than or equal to relational operator
<=
173
Which has higher precedence Relational or Arithmetic Operators?
Arithmetic Operators
174
Decision with One Branch
Statement(s) are executed when a condition is true. “Simple If ” or “single branched if” if (condition) { statement(s) }
175
What are statements inside of braces called?
Block
176
Simple If statement formatting
If more than one statement is to be executed, braces must be used. Otherwise only the first statement is part of the if. Statements that belong to the if should be indented.
177
Decision with Two Branches
Sometimes we would like to take one action if a condition is true and another if the condition is false. Use If/Else structure if (condition) { statement(s) //to be executed if true } else { statement(s)//to be executed if false }
178
What is the opposite of > and
<= and >= respectively
179
Can relational expressions be combined like 5
No, in C++ relational operators only evaluate 2 operands
180
Logical Operators
Combine or negate relational expressions Rewrite the expression 5 < x < 10 using the logical operator and (&&) as 5 < x && x < 10 (note that both relational operators must have 2 operands) Logical operators have lower precedence than relational operators.
181
AND operator
&&
182
OR operator
||
183
NOT operator
!
184
Truth Tables
List possible combinations plus the resultant true/false values from logical operators
185
Local Operator Precedence
&& higher than || Can always be overridden by parentheses
186
Short Circuit Evaluation
When the result of a combination of relational expressions can be determined from the evaluation of the sub-expression to the left of the logical operator, the sub-expression to the right is not evaluated. (x < y) || (x > z) x > z will not be evaluated if x 5) && (c < j) c < j will not be evaluated if y>5 is false
187
Multi-branched Structures
One method to allow for multiple branches is the if/else if structure. if (condition 1) { statement(s) } else if (condition 2) { statement(s) } *** MORE AS NEEDED******** MORE AS NEEDED***** else // default or trailing else, no if! { }
188
Evaluating Multi-way Branches
Go down the ifs one by one As soon as the statements associated with a true condition are executed, the branch structure is exited. When none of the ifs evaluated to true, the statements associated with the trailing else (when there is one) are executed.
189
Nesting Ifs
if (condition 1) { statement(s) if (condition 2) { statement(s) } else { statement(s) } } else { statement(s) } if inside an if statement Proper indentation is very important for the person reviewing the program.
190
Comparing Floats
Because of how floating-point numbers are stored in memory, unpredictable results may occur when trying to determine equality. Stick to using greater than or less than operators and use logical operator to determine a range. Example suppose you thought the round off error to cause a 0.0000003 difference in the value (x == 4.5673675) (x > 4.5673671) && (x < 4.5672679)
191
Comparing C-Strings
C-strings cannot be compared using relational operators, but instead the strcmp( ) function (requires cstring library file). Has the general format strcmp(str1, str2) Compares each character by subtracting the ASCII value of str2 character from str1 character from the beginning of the strings until a difference is found. Returns a zero if strings are the same, a negative number is str1 is less than str2, or a positive number if str1 >str2.
192
Scope
refers to where an identifier (often a variable name) association is known.
193
Global Scope Variables are
NOT PERMITTED in this course
194
Variables with the Same Name
If blocks are nested, the inner block can define (declare) a new variable with the same name as a variable in the outer block. Each variable will have its own memory space. (Don't do this though it makes it hard to debug)
195
Switches
The switch has a controlling expression that is evaluated and matched to a series of cases. The controlling expression if evaluated to an integer or single character. Switch is an alternative method to treat multi-branched decisions. A variable or expression will determine which branch will be executed. switch (integer expression) { case const1: statement(s) case const2: statements(s) case const3: statement(s) case constn: statement(s) default : statement(s) }
196
General Switch Format
switch (expression) { case answer1: statement(s) break; case answer2: statement(s) break; case answer3: statement(s) break; default: statement(s) } The answers will be constants
197
Break in switch
ends the execution of statements for each case. If the break statement is omitted for a case, execution will continue using the statements for the next case until a break is encountered.
198
Default in switch
Acts as a trailing else The default case does not have to be included. If the default is not included and no cases match the expression, no statements will be executed.
199
Advantages of switches
The “look” of the switch may be easier to understand because it looks more like a menu.
200
Disadvantages of switches
Cannot easily do irregular ranges. Cannot match strings.
201
Incrementing
adding one to a variable A = A + 1 This statement can be replaced by the incrementing operator ++. A++; (post incrementing) or ++A; (pre incrementing)
202
Decrementing
Subtracting one from a variable A = A -1 This statement can be replaced by the decrementing operator --. A--; (post decrementing) or --A; (pre decrementing)
203
Pre vs Post Incrementing/Decrementing
Determines when the incrementing (or decrementing occurs), before or after the value is used. Effects the results when the variable is combined with other values.
204
Loops
Loops allow a group of statements to be executed over and over again. All loops must have: loop-control variable(s)loop-control variable(s) body - block of statements to be executed repeatedly a way for the loop to be terminated. Three basic loop mechanisms: while, for, and do-while. Loops may be classified as pre-test or post-test.
205
While Loop
while (relational expression) { statement(s) // body of loop } The statements comprising the body of the loop will be executed until the relational expression evaluates to false. Therefore one of the statements should modify the loop-control variable(s) so the loop terminates.
206
Common Loop Errors
Not reaching the termination condition - loop never ends. It is an infinite loop. Missing braces - only first statement is executed as body of the loop. A semicolon at the end of while line while (condition); No statement is executed - it is an empty loop and an infinite loop if the condition is true.
207
Do-While Loops
do { statement(s) // body of loop } while (condition); //test The do-while loop is a post-test loop. The condition is tested after the loop is executed once. May be sentinel or count-controlled.
208
Sentinel controlled loops
indefinite/ the number of repetitions of the loop are not known
209
Count-Controlled
number of repetitions of the loop is already known when starting the loop
210
For-Loops
for(initialization; test; update) //header { statement(s) // body } Pretest loops Count-controlled (usually)
211
For loop expression variation
One, two, or all of the expressions may be omitted from the for loop. for( ; x < 10 ; x = x+2) the initial value of x is taken from earlier part of code. for( ; x < 10 ; ) the loop control variable must be updated in the body of the loop to avoid an infinite loop. for( ; ; ) // do NOT use in this course! loop is terminated in some other manner.
212
Other For-Loop quality in the header
The program may initialize or update a number of variables in the for header. for(initialization(s); test; update(s)) { statement(s) } for(x = 0, sum=0; x <= 20 && sum <150; x++, sum += x) { statement(s) } Be careful! Update occurs after body of loop has been executed.
213
When do you use these loops?
Should the loop always execute at least once? Yes => do-while No => while or for Should the loop be count controlled or sentinel controlled. Count => any of the loops Sentinel => while or do-while (usually).
214
How do you find a max using loops?
a repeated comparison of the number to the current maximum value. If the number is greater than the maximum value, then the maximum value is reset to that number. There are two common ways to initialize the value of maximum: set it equal to the first value, or set it equal to an extremely low value.
215
File Input/Output used when?
You want to input/output data faster than by hand and/or don't want to just output the data to the stream.
216
ifstream
abstract data type for file input
217
ofstream
abstract data type for file output
218
fstream
abstract data type for both input or output (Not allowed in the course!)
219
library file for using file input or output
#include
220
How to declare an object that refers to the file?
datatype object name; ifstream infile; // infile is just an identifier ofstream outfile; // outfile is just an identifier Can declare multiple objects: ifstream infile, datain, filein; ofstream outfile, dataout, fileout;
221
How to open a file?
infile.open(“filename”); outfile.open(“filename”); may specify a directory path by placing it in quotes as well infile.open(“C:\\somename.ext”); Template: ObjectType.open("filename")
222
How to close a file?
infile.close( ); outfile.close ( ) ;
223
How to hard code file names?
Put actual name in quotes. infile.open(“filename”); // in same directory infile.open(“cse103/myfile.txt”); /* other directory */ The filename may also be stored in C-string (char array) or string object. infile.open(stringname); /* stringname is character array or string object that contains the file name information */
224
How to access or write into the file?
like cin infile >>alpha; and cout outfile << beta; All the formatting for cout and cin will work with your file objects as well.
225
Steps using a file?
Declare File Object Associate File with Object Use File Object
226
Test File Error with...
if(!file) (lol your lab)
227
Fail Function?
The fail function returns a 0 or false if the file has been opened correctly and a 1 or true if there was a problem. if (indata.fail( ) ) { cout<<“There is an error\n”; }
228
Use loops for input files when?
There is more data than you want to process by hand in a repetitive manner.
229
How to determine end of a file?
State of the Extraction Operator and eof function of the input object
230
How State of Extraction Operator works?
The extraction operator (>>) returns a true or false based on whether the value was read correctly. When the end of find is reached the extraction operator will return a false. Therefore the successful input can be used as a status to complete the loop. while(infile >>number)
231
How End Of File works?
infile.eof( ) which evaluates to false as long as the end of the file was not detected and to true when it was detected. while (infile.eof( ) == 0) { statement(s) more input from file }
232
Why use functions in a program?
helps organize code, make it easier to port from program to program – modular programming; and can call the same function from many places in the program.
233
What is needed to employ functions?
Function Definition - Function Call - Function Declaration (Prototype)
234
Function Declaration?
code for the specific task. (In this course function definitions should occur after main)
235
Function Call
statement that directs control of the program to that function
236
Function Declaration (Prototype)?
identifies the function name and requirements. Usually occurs before main so the name is globally defined. Required for this course!
237
How to write Function Definitions?
return type function name (data type parameter(s)) { statement(s) //function body return 0; (Not needed when return type == void) }
238
Function Declaration placement rules
Cannot be nested inside on another. Therefore, because main is a function itself, they may be placed before main or after main (requires a function prototype). For this course you are required to put the functions after main and to use function prototypes (declarations).
239
Function Prototype Declarations rules?
Occur before main. Look similar to function heading except that it ends in a semicolon and it does not require the parameter name(s), just the data type(s). void print2lines ( ); int sum2int (int , int ); If the parameter name is included, it is ignored. Function prototypes are required for this course.
240
Code Format with Functions
//comments # include library files function prototype(s) int main ( ) { statement(s) return 0; } function definition(s) { statement(s) // body }
241
Function Call?
is the statement that tells the function to execute. When execution of the function has been completed, flow of the program returns to immediately after the call. It has the format of function name (parameter(s)) The parameters (arguments) from the call are transferred to the function heading in the order in which they appear.
242
Function Call Rules?
A function can call another function or even itself. y = sum2ints(5,sum2ints(pow(x,3), j)); A single C++ statement may call more than one function. xyz = cos(theta) + sum2ints(a,b); Function calls can be part of a condition. if (sum2ints(alpha, beta) > 10)if (sum2ints(alpha, beta) > 10) if (boolfunction) //function with return type bool
243
Parameters (Arguments) in a Functions?
The parameters in the function heading are referred to as “formal parameters”. The parameters in the function call are referred to as “actual parameters” or arguments. When the function call is executed, the values in the actual parameters are transferred to the formal parameters.
244
Things to think about when making Functions.
What is this function supposed to do? Is the function going to send information back to where it was called? If so, what is the data type of this information What parameters does this function need to operate and what are the data types of these parameters? What variables need to be declared within the function itself?