CMPSC 201 Exam 1 Flashcards
What is a computer?
A programmable electronic device that can
store, retrieve and process data.
Advantages of computers
Reliable, Fast, Does not tire,
Follows instructions (programs) precisely
Disadvantages of computers
Not “smart”– cannot analyze problems
Follows instructions (programs) precisely
What can a computer do?
Arithmetic, Comparisons/decision making, Communication-input, output, transfer of data.
CPU
fetches and follows a set of simple instructions
(also called processor).
Main Memory
stores the executing program and its data in RAM
(random access memory). Volatile
Volatile Memory
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.
Secondary Memory
stores permanent records (files). Non-volatile
Non-volatile Memory
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.
Examples of Secondary Memory
hard disks, USB-drives,
CD-ROMs, DVDs, etc.
Components of a Computer
Input Device, CPU, Main Memory, Secondary Memory, Output Device
ALU
Part of CPU stands for Arithmetic and Logic Unit performs mathematical operations
Control Unit
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
RAM Main Memory
consists of a long list of numbered memory
locations (RAM). Main memory is volatile!
Memory Locations
contain zeros and ones, on and off switches,
called binary digits or bits
Byte
8 bits 1 address for the memory stored there
Storage of Secondary Memory
Uses same idea of bits and bytes
Programs/data stored in units called files.
Stores files when they are not in use
Operating Systems
Operating Systems – allocates computer’s
resources and allows communication between
user and computer.
Programs/Program
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.
Programming language
special language used
to write programs.
Algorithm
set of well-defined steps for
performing a task or solving a problem
High Level Languages
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
Low Level Languages
consist of simple instructions which can
be understood by the computer after a minor translation
Compiled Languages
a separate file is created for the translated binary
code (C++, Java, FORTRAN, etc.)
Interpreted Languages
each command is interpreted and executed as
program is run (MATLAB, Python, etc.)
Machine Language
written in the form of zeros and ones, can
be understood directly by the computer
High Level to Machine Code Steps
Source Code - Preprocessor - Compiler - Linker - Executable Code
Source Code
Source file created by a
text editor *.cpp
Preprocessor
Modifies source code by instructions (#)
A library of already written source code
Compiler
Translates to Machine Code *.obj and
checks for syntax errors
Linker
Combines various object code files to create
an executable file *.exe
Key Words
reserved words that have a special
meaning. (often shown in blue)
Programmer Defined Symbols
words or names
that have been defined by the programmer. May
be variables, constants, or functions/routines.
Operators
tell the computer to perform specific
operations.
Punctuation
begins or ends a statement, or
separates items of a list.
Syntax
grammar rules for combining elements.
Syntax Errors
code does not follow the grammar
rules of language.
Found by the compiler.
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.
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.
Input
data the user of the program will need to
enter into the program
Output
information the user expects to receive
from the program.
Processing
what the program does to the input to
produce the output.
Examples:
Calculate weekly pay
Calculate the area of a rectangle
include <iostream></iostream>
Preprocessor Directive; comes before everything else in the program except the explanatory comment at the top
using namespace std;
Follows #include<iostream></iostream>
Algorithm vs Program
All Algorithms are programs, but not all programs are algorithms
Fetch
CPU gets, from main memory, the next instruction in the sequence of a program’s instructions
Decode
The instruction is encoded in the form of a number, The control unit decodes the instruction and generates an electric signal
Execute
After decoding the signal is sent to the correct part of the computer and causes that component to perform an operation
System Software
Controls and manages the basic operations of a computer
Utility Programs
enhance the computer’s operations and safeguards data
Application Software
makes the computer useful for everyday tasks. Games, browsers, word, etc.
Constant Declarations
happen before the main function but after “using namespace std;” for global usage
Format: const data type identifier = value;
int main()
The main function that holds all of the code be sure to use BRACES
variable declarations
happen first within the int main function and set variables for your program
return 0;
Marks the end of the program and lets the computer know to stop
Test Data
input for which the programmer
knows the result
4 Types of Control Structures
Branch, Loop, Sequence, Functions
Branch Control Structure (decision)
some statements may be
executed only when a specific condition is met.
Loop Control Structure (repetition)
statements are repeated
Functions Control Structure
a group of statements are executed at
various times in the program
Sequence Control Structure
statements are executed in order they
are written
Comments
describe what the program is
supposed to do and what various portions do.
Often used as documentation. Not executed.
Preprocessor Directives
directions to perform
before program starts.
Functions (Not the control structure)
group of statements to perform a
specific task.
Statements
actions executed by the computer.
// double slash
beginning of a single line comment
/* */ slash asterisk
Go around a multiline comment
octothorp (hashtag)
beginning of a
preprocessor directive
< > brackets
enclose filenames or data types
(_) parentheses
contains parameters for
functions or changes order of operations.
{_} braces
enclose a group of statements.
; semicolon
ends a C++ statement
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
Case Sensitive Languages
C++ is one so Include is not the same as INCLUDE or include.
Main function
All C++ programs must have a function main
int main ()
C++ Output Statement
cout “c” + “out”
What is needed for cout?
cout
object, the insertion operator(s) («), and
variables or constants to be displayed.
cout «“Hello”;
What is needed for multiple items to be output using the same cout statement?
«_space;insertion operator
Ex: cout«“The volume is ” «volume;
Escape Sequences
Performs specific output tasks when enclosed in
quotes. (cout is still needed)
\n
Causes cursor to go to next line
\t
Causes cursor to go to next tab stop
\a
Causes computer to beep
\\ (Escape Sequence)
Causes backslash to be printed
\’
Causes single quote to be printed
\”
Cause double quote to be printed
endl manipulator
Inserts blank lines in output just like the escape sequence.
cout «_space;radius «_space;endl «_space;volume;
radius
volume
Blanks in cout
Blanks may be inserted by enclosing the spaces in
quotes.
cout «_space;radius «_space;“ ” «_space;volume;
radius volume
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.
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).
Variables and symbolic constants
names for memory locations in RAM.
Variables
refer to memory locations in which the
value stored may change throughout the
execution of the program.
Named or symbolic constants
refer to memory
locations in which the values do not change.
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.
Variable Declarations Format
data type variable name;
where the variable name must follow the identifier
rules.
Data Types definition
determines how the data will be stored and
what types of operations can be performed on this data.
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)
Integer variables
memory spaces that will store
whole numbers
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
Floating Point Data
Used to store real numbers, numbers with
fractional parts
Floating Point Data Types
float 4 bytes single precision numbers
double 8 bytes double precision numbers
long double 10 bytes
Precision
refers to the number of digits that are
stored before the values are rounded.
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
Character Data
Written: char
holds a single character value
two methods to store multiple characters: C-strings or string objects.
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.
String Objects
include <string></string>
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”;
Default Data Type for whole numbers
int
Default Data Type for floating point numbers
double
Global Scope
Occur before main function and will be the same value to all functions (for constant declarations)
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.
Multi Variable Declaration Format
int alpha, beta, gamma, delta;
double weight, feet;
Assignment Statements
store values in the memory locations.
Assignment Operator
= (Not the same as equals)
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.
What happens when a floating-point number is stored in an int?
It gets truncated 4.57 => 4
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
Strings
a collection of characters.
two methods of creating strings in
C++. C-strings, String objects (requires the string class)
Arithmetic Operators
manipulate numeric values and perform
arithmetic operations.
Classified as unary, binary, or ternary based on
the number of operands needed.
Unary
one operand -a
binary
requires two operands.
X + Y c / b
ternary
three operands
Operand
+, -, *, /, % things like that
Binary Arithmetic Operators
+ Addition sum = y + x
- Subtraction diff = x - y
* Multiplication numb = c * b
/ Division rate = part / total
% Modulus remainder = d % 4
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
Precedence
Defines the order in which operations are
performed.
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.
Number Representation of int vs. floating point number
int ==> 4
float ==> 4.0
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;
C++ Input Object
cin object and extraction operator to read data from keyboard and store in memory locations.
cin» variablename;
When does input stop?
when white space (space, tab, newline) is encountered.
Multiple Input Values
separated by extraction operators.
cin»x»y; //data is stored in order given
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.
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.
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«_space;x«endl;
will usually output -32764.
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;
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
Three Methods of Type Casting
static_cast<data>(variable or expression)
data type (variable or expression)
(data type) variable or expression
Last two methods considered out of date</data>
What are 2 ways to change what is stored in a variable?
Assignment statement
Input new value
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.
Define Format
define identifier value
EX: #define tax_rate 4.5
Compound Operator
Provide a shortcut for assignment statements. Combines the = operator with another arithmetic operator
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.
a -= 6.0;
is equivalent to a = a – 6.0;
a *= 3.4;
is equivalent to a = a * 3.4;
a /= 2.1;
is equivalent to a = a /2.1;
a %= 3;
is equivalent to a = a % 3;
Reminder—the % operator only works for integer
data types.
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 <cmath></cmath>
Trig Functions Assumption
that the angle is in radians not in degrees
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«rand( )«endl;
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«rand( )«endl; // output next number
What library file does the rand() function need?
cstdlib library file
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;
Random Numbers Other than rand() function
include<random>
Random number engine
random_device // one engine type
random_device Myrandgen; //defines an engine</random>
Distribution Object
uniform_int_distribution<int> randInts(0,100);
Object Type states how numbers will be distributed,</int>
<Data> Object name (Number range (min value, max value))
</Data>
Other random number use
Use the object to store a generated number
int number
number = randInts(Myrandgen);
setw() Manipulator
controls the number of spaces that will be
used to output an item
cout«manipulator«item;
cout«setw(10)«x; // allows 10 spaces
The n must be an integer and is often called the
field width specification.
By default numbers are right justified within this field.
Must be before each item to be output.
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«setprecision(3)«y;
cout«fixed«setprecision(3)«y;
Both fixed and setprecision() remain in effect until a new manipulator is used. Has no effect on integer values!
showpoint Manipulator
set to show the decimal point and zeroes for numbers like 45.0
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 «_space;operator.
The programmer can also change manipulators within the same cout statement.
Ex: cout«left«somevariable«right«var2;
Formatting Input/Output alternative
cout.width(5) instead of cout«setw(5)
cout.precision(3)
cout.setf(iosflag(s))
cout.unsetf(iosflags(s))
cout is actually an object belonging to a class
and as such has member functions that can be
accessed using the format object.function.
Usually formatting of input is reserved for use
with strings (character arrays).
By default, the cin object will also stop input if a
space, tab, or return is encountered.
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.
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’)
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.
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.
Hand Tracing
Given test data the programmer should be able to predict what is stored in each variable at each line of code.
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.
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)
equal to relational operator
==
not equal to relational operator
!=
greater than relational operator
>
less than relational operator
<
greater than or equal to relational operator
> =
less than or equal to relational operator
<=
Which has higher precedence Relational or Arithmetic Operators?
Arithmetic Operators
Decision with One Branch
Statement(s) are executed when a condition is true.
“Simple If ” or “single branched if”
if (condition)
{
statement(s)
}
What are statements inside of braces called?
Block
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.
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
}
What is the opposite of > and <?
<= and >= respectively
Can relational expressions be combined like 5<x<10
No, in C++ relational operators only evaluate 2 operands
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.
AND operator
&&
OR operator
||
NOT operator
!
Truth Tables
List possible combinations plus the resultant true/false values from logical operators
Local Operator Precedence
&& higher than ||
Can always be overridden by parentheses
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<y is true
(y > 5) && (c < j) c < j will not be evaluated if y>5 is false
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!
{
}
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.
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.
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)
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.
Scope
refers to where an identifier (often a variable name) association is known.
Global Scope Variables are
NOT PERMITTED in this course
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)
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)
}
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
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.
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.
Advantages of switches
The “look” of the switch may be easier to
understand because it looks more like a menu.
Disadvantages of switches
Cannot easily do irregular ranges.
Cannot match strings.
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)
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)
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.
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.
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.
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.
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.
Sentinel controlled loops
indefinite/ the number of repetitions of the loop are not known
Count-Controlled
number of repetitions of the loop is already known when starting the loop
For-Loops
for(initialization; test; update) //header
{
statement(s) // body
}
Pretest loops
Count-controlled (usually)
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.
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.
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).
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.
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.
ifstream
abstract data type for file input
ofstream
abstract data type for file output
fstream
abstract data type for both input or output (Not allowed in the course!)
library file for using file input or output
include<fstream></fstream>
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;
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”)
How to close a file?
infile.close( );
outfile.close ( ) ;
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 */
How to access or write into the file?
like cin
infile»_space;alpha;
and cout
outfile «_space;beta;
All the formatting for cout and cin will work with your file objects as well.
Steps using a file?
Declare File Object
Associate File with Object
Use File Object
Test File Error with…
if(!file)
(lol your lab)
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”;
}
Use loops for input files when?
There is more data than you want to process by hand in a repetitive manner.
How to determine end of a file?
State of the Extraction Operator
and
eof function of the input object
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»_space;number)
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
}
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.
What is needed to employ functions?
Function Definition - Function Call - Function Declaration (Prototype)
Function Declaration?
code for the specific task. (In this course function definitions should occur after main)
Function Call
statement that directs control of the
program to that function
Function Declaration (Prototype)?
identifies the function name and requirements. Usually occurs before main so the name is globally defined. Required for this course!
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)
}
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).
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.
Code Format with Functions
//comments
# include library files
function prototype(s)
int main ( )
{
statement(s)
return 0;
}
function definition(s)
{
statement(s) // body
}
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.
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
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.
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?