SlideShare a Scribd company logo
1 of 39
INPUT AND OUTPUT PROCESSING
Please note that the material on this website is not intended to
be exhaustive.
This is intended as a summary and supplementary material to
required textbook.
INTRODUCTION
Most computer programs spend very little processing time in
obtaining input and producing output.
Most of the work goes into the processing in between. The
exception to this generalization is non-
browser-based graphical user interfaces (GUIs). In these
programs, often over 50% of the code can be
dedicated to user input and output. In browser-based user
interfaces, the browser does a lot of the work
for you.
Input/output (I/O) comes in two flavors: interactive and non-
interactive. Interactive I/O involves
prompting the user for the input and displaying the output on
the user's monitor. Non-interactive I/O
involves reading and writing files, which for us will be text
files.
INTERACTIVE I/O
The majority of interactive I/O is accomplished in C++ using
cin and cout. For now all interactive I/O
comes from and goes to the console window. Recall that in
order to use cin and cout we have to
#include <iostream>.
The cin input stream views the input the user types as if the
data came from a text file. But, cin ignores
as data all whitespace characters: the newline, the tab, and the
space. As a result cin does some input
formatting for the program, and only assigns non-whitespace
data to the input variables.
If the user is entering several data items on one line (in the
console window), cin will wait for the user to
press the newline (Enter or Return) key before it will process
the line of input data.
The input stream can consist of any array of characters,
representing: integers, decimals, strings, single
characters, .... Each array of characters is delimited by
whitespace characters, and cin will interpret any
of the whitespace characters as a delimiter (with some
exceptions, of course).
When we invoke cin we always have to specify a variable in
which to place the user input; that variable
must have a type. And, cin is very persnickety about types. If
cin is expecting an integer, it will not read
an alphabetic character; it will generate an error condition. In
the following code snippet cin will expect
to see a single character, an integer, a decimal, and a string, in
that order.
char yOrN;
int userID;
double hourlyWage;
string lastName;
...
cin >> yOrN >> userID >> hourlyWage >> lastName;
If the user typed the last name for the userID, cin will flag an
error and not continue to read the input
stream until your program deals with that error (see below).
The cout output stream has a lot more variety to it; cout is
aware of the types of variables passed to it,
and will format them accordingly, unless your program specifies
another format to use. When thinking
about the arrangement of your program's output, consider each
string of output characters as a field, and
the contents of each line of output as an array of fields. The
following output has 4 fields in the one-line
array of fields:
Y 1648942 25.00 Smith
Every field in the array has a width. In the example above you
cannot easily tell by looking exactly what
the width of each field is as each field has a tab character in
front of it (which you cannot see in this
document or on your monitor).
Some output will not have such an orderly appearance; you
might get a two-line output that looks like
(still using a tab in front of each field):
Y 1648942 25.00 Smith
N 179240578352 35.375 Jones
As far as columnar output is concerned we have some generally
accepted principles:
All columnar output fields should be "lined up" in their own
columns, and each column should be
wide enough in width to hold the longest field in that column.
Non-numeric fields, whether strings of characters or single
characters, should be arranged left-
justified in their column – that is, so the first character is left-
most within the field.
Numeric fields, whether integers or decimals, should be
arranged right-justified in their column –
that is, the last character is right-most within the field.
Furthermore, when decimals are used, principle 3 should be
violated so every decimal in the
column has the decimal point vertically in line.
You can probably think of a lot of cases where you might want
to violate one or more of these
principles, but before you do be aware of why they are
principles.
Y 1648942 25.00 Smith
N 179240578352 35.375 Jones
N 15469 30.00 Rimsky-Korsakov
Users will expect to see non-numeric string data left-justified in
their columns – it makes it easier to scan
the column. User will also expect to see numeric integers right-
justified in their columns – it makes it
easier to tell the difference between 1000000 and 10000000
when scanning. And, users (especially
accountants) will want to see all the decimal points lined up
vertically for the same reason. Most
spreadsheets assiduously follow these principles unless you tell
them to do otherwise.
Notice that the second column above violates the 3rd principle,
and it does so with good reason. The ID
number is not really an integer – we do not expect to be doing
arithmetic operations on the ID number.
The ID number really should be declared as a string and treated
just like any other alpha string. Consider
U.S. zip codes – do you ever expect to add or subtract these
numbers?
As programmers, then, we need to know the characteristics and
intended uses of our output data. And,
we need to format that output so that it is orderly, if not
aesthetically, pleasing. Programmers are usually
not good judges of either characteristic, and the users who will
utilize a program's output should always
be consulted about such mundane matters as format.
FORMATTING OUTPUT
Formatting output can be daunting at first, and we will simplify
it considerably here (but see iostream).
In order to use the formatting functions you have to: #include
<iomanip>.
The two most important formatting routines will be setw() and
setprecision(). In addition, we will show
you how to display decimal numbers in either scientific or
fixed-point notation.
The setw() function is used to set a field width. The function is
used directly in the cout line:
cout << setw(10) << numb1 << setw(10) << numb2 << endl;
The setw() function requires an integer parameter (in this case
10), and its effect is to specify the field
width for each of the two numbers following in the cout
statement.
If you wanted the second number in a different field width you
need to use something like:
cout << setw(10) << numb1 << setw(5) << numb2 << endl;
If you try to output a string of characters that is too wide for the
field width setting, C++ will not
truncate the output; it will overfill the field, which will throw
off all the rest of the columnar output.
Lastly, (and this a real gotcha!) by default C++ will NOT left-
justify any output. The default setting is to
always right-justify output. You can set the justification on a
case-by-case basis with:
cout << setiosflags(ios::left) << ...;
cout << setiosflags(ios::right) << ...;
Whenever you insert a setiosgflags() call in a cout statement, it
will apply to ALL subsequent cout
statements, unless you explicitly change the flag setting.
You can set the number of decimal places to be represented in
the output with setprecision() which
takes an integer parameter:
cout << setprecision(2) < ...;
Bear in mind that setprecision() will NOT round off; it will only
truncate. If you want to round money
to the nearest cent use:
float money;
...
cout << setprecision(2) << money + 0.005;
Also bear in mind that once you use setprecision() this setting
will apply to all subsequent calls to cout,
unless you explicitly change the precision setting.
You can choose to display decimals in either fixed-point or
scientific notation. The default is fixed-point.
http://www.cplusplus.com/reference/iostream/
Use the following to toggle between the two formats:
cout << setiosflags(ios::fixed);
cout << setiosflags(ios::scientific);
Once you set a format, it stays in effect until you explicitly
change the setting.
MISCELLANEOUS
The getline() function (you must #include <string>) is
particularly useful for reading a whole line or the
first parts of lines. It has two forms:
getline(infile, dest_string);
getline(infile, dest_string, delim_char);
The first form reads the entire line (up to the newline) from the
input stream (infile) into the dest_string
(not including the newline); dest_string must be of type string.
This form is useful for reading whole
lines at a time. The second form reads the line up the delimiter
character passed (for instance, ',') into the
dest_string (not including the delimiter character). In both cases
the next read will continue with the
character after the newline or delimiter.
You may have noticed that cin reads the input stream and skips
over whitespace characters. If you want
to read the input stream character by character (one character at
a time), including the white space
characters, you use the istream member function get():
cin.get(char_variable);
Unlike cin and getline(), the get() member function does not
strip any characters from the input stream;
instead it delivers all characters from the input stream including
whitespace characters.
HANDLING I/O ERRORS
Once an input stream encounters an error, it sets an error flag,
and it will refuse to read anything more,
until the error flag is cleared. When using cin in situations
where the user may mistype (which is really
all situations), you would need to check the error flag, inform
the user of their error, clear the error flag,
and re-prompt the user.
We will not cover input error handling in detail yet. Just be
aware that your program may just "hang"
because of an I/O error. For now, we will program as if the user
never makes a mistake typing.
NON-INTERACTIVE I/O
Non-interactive I/O involves reading and writing text files. In
order to read and write files we have to be
able to open files for reading and/or writing. When we are done
we have to close the file. In order to use
the file libraries that contain the file manipulation functions you
will have to #include <fstream> and
also often <string>. The four operations on files are, then:
Open (a file for reading or for writing)
Read (an open file)
Write (an open file)
Close (an open file)
Opening a file is straightforward, if you know the name of the
file to open, and the file exists in your
application program's current working directory, that is, the
same directory or folder in which the
application program itself is stored. In this case you just use the
name of the file: "filename.txt".
If the text file is stored in another directory, then you will have
to know the full (or relative) pathname of
the file. This can get tricky for Windows-based systems, as the
pathnames will have a backslash
character () in them, which the C++ compiler uses as an escape
character. In order to have  characters
in the pathname string you have to escape the escape character
(with ). Hence, the string naming a file:
"C:directory1directory2...filename.txt" will often have to be
named as:
"C:directory1directory2...filename.txt."
In non-Windows OSs pathnames use the slash character (/), and
that causes no problems for the C++
compiler. (Note: UNIX OSs have problems with file and
directory names that contain spaces – ASCII
hex 20 or decimal 32 – in them; a good naming practice to
follow is to NEVER use spaces in file or
directory names; if you ever move your programming working
environment to a UNIX system, this
practice will save you a lot of headaches.)
A further complication is caused by C++ and the C++ compiler.
We are used to strings, and it is a string
that we use to name files. However, the file open function
requires that you use C-language string (which
is a NULL-terminated array of characters). The workaround is
fairly straightforward. In order to open a
file named by a string variable, we will have to first convert it
to a C-based character array (using the
c_str() member function; see below).
Any input file stream will have the type: ifstream (used for
reading) and any output file stream will have
the type: ofstream (used for writing). We declare these streams
as follows:
#include <fstream>
...
ifstream input_stream_name;
ofstream output_stream_name;
Most often we will do the declaration and the open in one line,
as in:
ifstream is("filename.txt", ios::in);
ofstream os("filename.txt", ios::out)
Once we have an open file we use the stream variable (either is
or os in the example immediately above)
just like we already use cin and cout:
is >> variable_name;
os << "And the answer is: " << answer << endl;
However, if we name the file by means of a C++ string variable,
we have to use the workaround
mentioned above. The workaround uses the string member
function c_str(). For instance, your programs
will often want to prompt the user for the filename and read the
name into a string variable. In order to
do that and open the file successfully you have to use something
like:
#include <fstream>
#include <string>
...
string filename;
...
// prompt user for input file name
cout << "Enter the name of the input file: "
cin >> filename;
ifstream is(filename.c_str(), ios::in);
As users may mistype the name of the string, you have to be
prepared for errors on open with something
like:
if (is.fail()) {
cout << "Cannot open " << filename << endl;
// either re-prompt the user or exit your program
...
}
Last, but not least, when you are done reading or writing a file
you should close the file. In any case, you
should close the file before exiting, with:
is.close();
os.close();
Nothing bad will happen if you do not close a file before
exiting, as the OS will take care of that for you.
Experienced programmers consider programmers who fail to
close open files to be sloppy programmers.
REVIEW EXERCISES
1. * Write a program that opens a non-existent file for writing
and output some text into the file. Did
the underlying OS create a file for your text?
2. ** Write a program that prompts the user for an integer, then
prompts the user for a string, then
prompts the user for a decimal. Your program should then print
out what the user entered.
Experiment with various error input scenarios. Try entering 5o1
for the integer (instead of 501).
Try entering two separate words for the string (instead of a
single word. Try entering 10% for the
decimal (instead of .10). Take note of your results!
3. *** Write a program that outputs the following tabular data
correctly aligned. Note: you have to
reset the I/O flags BEFORE you set the alignment right or left
with: cout <<
resetiosflags(ios::adjustfield);
ID First Name Last Name Balance
1 Mary Worth 100.00
2 John Kildare 15.10
3 Harvey Jones 65.27
4 Wilbur Murphy 1145.43
5 Sandra Dee 0.00
6 Amy Santucci 231.55
7 Melissa Cox 2.01
8 Morgan Freeman 1789.03
9 Jack Nicholson 123.67
10 John Brown 426.87
© 2011 cad18; rcm27; cpsm
mailto:[email protected]
mailto:[email protected]
mailto:[email protected]
ANALYSIS AND DESIGN
Please note that the material on this website is not intended to
be exhaustive.
This is intended as a summary and supplementary material to
required textbook.
INTRODUCTION
Having a systematic approach two programming means that you
will approach each problem in the same methodological way.
So you will take the same steps to writing programs for each
problem. However, there are some variations. For example, we
will present to general systematic approaches to programming
here. The first approach is constructed for the beginning
programmer. It is relatively simple and basic and helps the
student programmer get a handle on the necessary tools.
The second approach models the kind of approach used by
professional programmers. This approach is sometimes called
the
Software Development Life Cycle (SDLC). With this second
approach, you will see a summary of a different and more
complicated organization of basically the same material.
Our suggestion is that you start with the first approach and then
change over to the second one when you are ready. In the end,
you should choose the approach that best helps you get a handle
on the problem you are programming for.
The simple approach to a systematic approach states that there
are two parts to a systematic approach to programming. These
two parts consist of solving the problem and implementing the
solution. What needs to be emphasized here is that the first
part is done without writing any code. The solution to the
problem is logically constructed and is expressed using specific
tools and templates. After the solution is constructed, we
implement it. This implementation includes using programming
languages that eventually have to be translated into the
computer's machine language – the actual language that the
computer
understands.
THE ANALYSIS
The first part of solving the problem has 3 sub-steps. Those 3
sub-steps consist of writing the analysis, writing the design, and
testing the solution. First, it is important to distinguish analysis
from the design. The analysis expresses the basic
informational requirements of the problem. This information
conveyed in the analysis includes the data inputs of the
program,
the data outputs, data that is calculated but not part of the
output, and formulas. The beginning template we will use for
the
analysis is below. Note that this is only a beginning template
and that you should find your own way to modify this template
as more complex problem solving and programming issues are
introduced.
Analysis:
Input:
Output:
Temporary Variables:
Formulas:
The input part of the analysis will consist of the information
that the person running the program, the user, will enter. This
usually consists of data values only; the user rarely, if ever,
enters a formula. The output part of the analysis will consist of
the
information that the user either wants to see, store, or send to
another location. Like the input, we are usually referring to data
values. The Temporary Variables will consist of all values
calculated in the formulas but are not output. Finally, we will
list
the formulas used. In terms of the sequence of filling out this
analysis template, we need to fill out the Formulas before we
fill
out the Temporary Variables, because the Formulas often
determine what is a Temporary Variable. But in terms of the
order of
appearance, Temporary Variables will be listed before the
Formulas because, like input and output, Temporary Variables
are
data and it is preferable to list like items together.
Below is a sample analysis. The problem that this sample
analysis will address is listed before the analysis.
Problem: You are to find and display the average of 3 test
scores.
Analysis:
Input: Test #1, Test #2, Test #3
Output: Average
Temporary Variables: Total
Formulas:
Total = Test #1 + Test #2 + Test #3
Average = Total/3
We should note few things about the above analysis. For the
Input, Output, and Temporary Variables, we do not fill in
numeric values. It is the job of the user to select the numeric
values for the Input and the job of the computer to calculate the
numeric values for the Temporary Variables and Output. The
next thing we should observe is that once a term is used,
Average in the Output for example, that term is spelled the
same way throughout the rest of the analysis. As a result,
Average
in Formulas is spelled the exact same way as Average in Output.
Finally, Total is a Temporary Variable because its value is
calculated in Formulas, but is not part of the Output.
THE DESIGN
The next part of solving the problem consists of writing the
Design. While the Analysis is concerned with understanding the
problem by listing its requirements, the Design contains the
actual solution to the problem. How that solution is expressed
depends on the kind of problem solving approach we are using.
In an Object-Oriented (OO) programming approach, we
would be identifying the parts or players needed to solve the
problem and then we would determine how and when these parts
would communicate with each other to actually solve the
problem. We will be using a Structured programming approach,
which is much easier to use.
Though there are other parts to it, the Structured programming
approach is primarily concerned with taking the right sequence
of actions to solve the problem. The solution will be expressed
using verb-phrases. One can use a number of tools when
expressing the solution in a Structured programming approach.
At this programming level, we will write the solution to our
problems using an algorithm. There are three important parts to
the definition of an algorithm. The first part says what we
have already said, that there is a correct sequence of actions to
take. The next part says that this sequence of actions will solve
the problem – that is, give us the correct answer every time.
Finally, the solving of the problem occurs in a timely fashion.
If writing a design means listing the actions, we need to know
what actions are available to us. The actions available to
beginning programmers include get input, process information,
and print output. When we say get input, we are telling the
computer to ask the user to enter in specific information and
then tell the computer to use the appropriate input device to
read
that information. When we say process information, we are
telling the computer to apply operations (arithmetic, logic, or
shifting) to data it has. And when we say print output, we are
telling the computer to send the requested information to a
specified output device, usually the monitor. We should note
that during the design time, we are not actually telling the
computer to do anything; telling the computer to act is in our
planned solution, and programming the computer comes later.
Now we know what actions we can take, we need to determine
the order of the actions to write the algorithm. The steps in an
algorithm can be determined in a number of different ways.
Some of these approaches include working backwards, using the
algorithm from a similar problem, means-ends, and trial and
error. But the one we will use here is called the Input-Process-
Output (IPO) algorithm. What this means is that we will list all
of the get input steps first, then we will list all of the process
information steps second, and we will finally list all of the print
output steps last. To determine what get input, process
information, and print output steps we need we will consult the
analysis for that problem. Below is an example of an
algorithm that is written by applying the IPO approach and
using the analysis of that problem.
Problem: Find and display the average of 3 test scores.
Analysis:
Input: Test #1, Test #2, Test #3
Output: Average
Temporary Variables: Total
Formulas:
Total = Test #1 + Test #2 + Test #3
Average = Total /3
Design (using an IPO algorithm):
Get test #1
Get test #2
Get test #3
Calculate Total
Calculate Average
Print Average
Using the IPO approach, we started by listing the get input
steps. How do we know what get input steps are involved? For
each input item, whcih we will call a variable, in the input part
of the analysis, we write a get input step. That is why we have
the steps Get test #1 and so on.
Then for each formula in the analysis, we will write a process
information step. Each step will state what it is calculated. We
do not need to rewrite the formula used. That is why we wrote
Calculate Total and Calculate Average.
Finally, the print output step was determined writing the step
for each variable in the output part of the analysis.
We have arrived at the final part of Solving the Problem. That
part is testing the solution. Note that we are testing the solution
before we write any code. Though we will be testing the
solution by testing the code later on.
THE TEST OF THE SOLUTION
The last part of solving the problem consists of testing our
analysis and design. We can do this by creating a table of
information using a spreadsheet. Using the analysis and design
from the test average problem, our test of the solution of the
analysis and design looks like the following:
Test1 Test2 Test3 Total Average
Get Test1 90 ? ? ? ?
Get Test2 90 80 ? ? ?
Get Test3 90 80 70 ? ?
Calc Total 90 80 70 240 ?
Calc Average 90 80 70 240 80
Print Average 90 80 70 240 80
To construct this test, we simply put each variable from the
analysis into a column and put each design step into a row. The
values entered for Test1, Test2, and Test3 produce a result that
is known without using the formulas from the analysis. The
value for Total is calculated by implementing the formula in the
analysis by adding the cells containing the test scores for that
row. And we implement the formula used to calculate Average
by dividing the contents of the cell holding the Total for that
row by 3.
Returning back to the values we entered for Test1, Test2, and
Test3, we need to repeat that we, those who constructed this
test, must pick values that produce a known result. That is
because if the answer calculated for Average is different from
80,
the answer we expected, we know that there was an error in
either the Analysis and/or the Design.
IMPLEMENTING THE SOLUTION
Implementing the solution means exactly what it says. We have
to tell the computer how to carry out our solution to the
problem. To do that, we must translate the solution into code,
we must eliminate errors, and we must document the code. But
whereas the order in which the steps of solving the problem are
performed are sequential, the steps in which implementing the
solution takes place, for the most part, are concurrent. That is
we will be translating the solution, eliminating error, and
documenting the code seemingly at the same time.
TRANSLATING THE SOLUTION
If we have put the appropriate work into solving the problem,
then writing the code will be like translating a U.N. speech into
the language of a listener. Most of the mental work, for the
beginning programmer, takes place while we try to solve the
problem. Translating the solution should be simple once we
have sufficiently learned the language.
Writing code has 3 prerequisites. You must know what each part
of the code does. We can learn that by reading definitions
and seeing examples. You must also know the syntax of each
C++ construct you have to use. Knowing this syntax is
equivalent to knowing the syntax of the language you speak in.
When writing code, the syntax of the programming language
tells us the order in which each symbol should occur. Finally,
and this is where using the solution to the problem comes into
play, the solution to the problem tells us when to use each C++
construct. That is what we need to know to write code. We
need to understand each construct we use, we need to know the
syntax so that we can write the code properly, and we need to
know when to use each construct. We will not go into the
details here, but as you learn the different C++ constructs,
remember the constructs used by the solution so you can
recognize what C++ construct to write as you translate each part
of
your solution into code.
ELIMINATING ERRORS
The errors that we must correct when writing programs are of 3
kinds: compiler errors, runtime errors, and logical errors. We
should note that we will be oversimplifying things when
describing compiler errors. Before defining what a compiler
error is,
we must first define a compiler. A compiler is one of the tools
that a computer uses to translate code, written in a
programming language, into a language a computer understands.
To help translate what is written in a programming language,
a compiler must perform two tasks. The first task of the
compiler is to check the code for syntax errors. A syntax error
is when
the symbols of a piece of code are in the wrong order. If the
compiler spots a syntax error, it notes it and goes on to look for
the next error so that these errors can be reported to the user. If
the code being compiled does not have any syntax errors, then
the compiler translates the code into machine code, code in a
language the computer understands, and writes it to a file with a
.obj or .o extension. Now even though the contents of the .obj
and .o files are in machine code, it is not quite ready for the
computer to execute the file. In order to execute the code, the
machine language must be loaded into main memory.
The next kind of error that we must know how to correct is a
runtime error. Whereas compiler errors occur when different
parts of the code are not written in the correct order, a runtime
error occurs when there are no syntax errors. A runtime error
occurs when use the correct syntax to tell the computer to do
something it cannot do. A common example of a runtime error
is
when we tell the computer to divide by 0. Because we cannot
divide by 0, we cannot tell the computer how to divide by 0;
thus when the computer is told to divide by 0, it is told to do
something that it is not able to do.
How a computer reacts to a runtime error is unpredictable. That
is because how a computer reacts to such an error depends on
the machine and the software it runs.
Runtime errors are more difficult to solve than compiler errors.
That is because runtime errors are more difficult to locate than
compiler errors.
The final kind of error that we must know how to eliminate is a
logical error. Logical errors contain no syntax errors or
runtime errors. A logical error occurs when the programmer
writes code that tells the computer to do something that does
not
help solve the problem. For example, suppose we are writing a
program that will find and display the average of 3 test scores.
And suppose that we have added the 3 tests together but when
we calculate the average, we divide by 4 rather than 3. We can
tell the computer to divide by 4 legally and the computer is able
to do that. The problem is that dividing the total by 4 does
not tell the computer how to calculate the average of 3 tests.
All of the 3 errors types are corrected by re-editing the code and
retesting, until no errors remain.
DOCUMENTING THE CODE
Documentation is a plain language description of either of what
the whole program does or what a part of the program does.
The first step in documenting the code is to provide
documentation at the top of the file. An example is provided
below:
/*
Program: TestAverage.cpp
Name: Your Name
Date: 07/28/10
Purpose: The purpose of this program is to find and display the
average of 3 test scores
*/
It is recommended that you document your program as you are
writing the code rather than to document after you finish
writing
the code.
Again, when implementing the code, we will be translating the
solution into code, eliminating errors, and documenting the
code concurrently. When discovering a logical error in the code,
if the error is because of a mistake in the analysis or design,
then the analysis and design must be corrected immediately.
Then we correct the code, recompile, and retest.
REVIEW EXERCISES
Using the methods of this module provide a design, analysis,
and test of the algorithms you previously developed in the
Review Exercises at the end of the Introduction to Programming
Environments module.
© 2011 cad18; rcm27; cpsm
mailto:[email protected]
mailto:[email protected]
mailto:[email protected]
C++ BASCIS
Please note that the material on this website is not intended to
be exhaustive.
This is intended as a summary and supplementary material to
required textbook.
INTRODUCTION
As all languages have a grammar, a description of what counts
as a "well-formed" sentence, so does C++. This
module explains some of the basic syntax, or grammar, of C++.
A compiler is a tool that translates C++ code
into instructions the computer hardware understands.
COMMENTS
Comments are entirely ignored by the compiler, so you can put
anything you want in them. One way to add a
comment is to use // which indicates that the rest of the line is a
comment:
EXAMPLE: ... // the rest of this line is a comment
Alternatively, multiple lines can be comments using the /* ... */
notation:
EXAMPLE: /*
.
.
.
all of this text is a comment and is entirely ignored by the
compiler
.
.
.
*/
In addition, the compiler ignores blank lines. For the most part,
the compiler also ignores spaces and indentations
(tabs).
A very simple C++ program will look something like the
following:
EXAMPLE: // The purpose of this program is to illustrate how a
C++ program is constructed
#include <iostream>;
using namespace std;
// the main () routine is where the program begins
// execution
int main ()
{
cout << "Hello World!" << endl;
return 0;
}
This program begins with a comment; indeed, every program
should begin with a comment explaining its basic
purpose. Good software design principles require comments
liberally placed throughout the code. This example
also has a comment before the main routine. The entire main ( )
routine is contained within curly braces, { and },
which delimit the body of the main routine in a block.
INCLUDE DIRECTIVES
The purpose of include directives is to allow the programmer to
take advantage of the many facilities that have
already been coded, compiled, and tested. The definitions of
cout and endl are in the <iostream> include file
(often called a header file). If you leave out the include
<iostream> statement, this simple program will not
compile.
The include files do not contain compiled code; rather, they
contain the C++ definitions of various terms. The
compiled code for the items defined in a header file is in
libraries.
The using namespace std; is also necessary. For now, we will
think of a namespace as akin to a dictionary, with
the definition of various terms listed in the namespace (called
std).
When a program is compiled, before the compiler begins its
work, a preprocessor reads into the file all of the
contents of the files named in the include statements. Most
compilers are two-pass compilers; that is, after the
preprocessor has run the compiler makes two passes through the
code: once to check the syntax, and if the
syntax passes, the second pass produces the object code.
The linker is responsible for combining the object code with the
libraries of routines defined in the include files
to produce a program that is executable. An executable program
still has to be loaded into memory to be run,
and the loader is responsible for this.
MAIN ROUTINE
The main ( ) routine is where the program begins execution,
once the executable is loaded into memory. A
simple main routine may only be responsible for obtaining input
to the program, processing the input, and
producing the output. More complicated main routines are more
like traffic directors, defining the route the
program must traverse in order to accomplish its objective. The
main routine is defined within a block of code
contained within curly braces.
The int main ( ) part is the header of the main routine, and it
merely says that main is a function (i.e., the ( )
part), and it returns an integer value when it exits. The main
routine in the example above returns 0 when it exits
(i.e., the return 0; part).
Within a block of code every line is a statement or a comment.
A statement is a syntactically correct sentence of
C++. All statements are terminated with a semicolon (;).
Normally, only one statement is written on a single
line, but you may put multiple statements on a single line. You
may also have statements that require several
lines in a file. An essential characteristic of a statement is that
it ends with a semicolon. In the example above
there are two statements: one beginning with cout and ending
with a semicolon, and one beginning with return
and ending with a semicolon. Note especially that blocks of
code do not end with a semicolon; they end with a
close curly brace.
INPUT AND OUTPUT>
Most programs require input and most programs produce output.
Sometimes the only output from a program
indicates that an error occurred (this is called error output).
For now all input will be done using the cin facility (see
below), and all output will be done by using the cout
facility. Both of these facilities are defined in the <iostream>
header file.
In the example above, the program outputs the text contained
between the double quotes, i.e., the string Hello
World!. The endl causes the end of the line to be a newline,
which moves the cursor in the output window to a
new line. Both of these items are separated with an operator:
<<.
Thus the cout line in the example first outputs the string Hello
World!, followed by a newline.
A prompt is an output statement that solicits input from the user
of the program. Typically these are strings that
are not followed by an endl.
EXAMPLE: cout << "Enter the name of the file to open => ";
cout << "Enter Y for yes or N for no => ";
WRITING YOUR FIRST C++ PROGRAM
Your first program will be the example shown above.
SYNTAX, SEMANTICS, and METALANGUAGE
In order to fully describe the C++ language, we must explain
how to form syntactically correct statements using
the facilities of the language. Next, we must describe what the
different statements of the language mean, i.e.,
the semantics of the facility. Our description of the facilities of
C++ is carried out in yet another language,
English, which is our metalanguage, i.e., the language we use to
describe another language: C++.
VARIABLES AND CONSTANTS; ASSIGNMENT
Variables and constants are specified in C++ by means of
declarations. Each declaration names a variable or
constant and indicates how it will be used, its type. The name of
a variable or constant is called an identifier.
Identifiers must be formed according to the following rules: all
identifiers consist of the following letters and
only the following letters (note that a space is not included):
A, B, C, D, ..., Z (upper case alphas)
a, b, c, d, ..., z (lower case alphas)
0, 1, 2, 3, ..., 9 (digits)
_ (the underscore)
An identifier may not begin with a digit. Further, no identifier
can be the same as a keyword (a reserved word)
in C++; keywords are listed below.
Thus the following are valid identifiers:
EXAMPLE: isAnAlpha
_myVariable
PI
word1
Word_1
The following are NOT valid identifiers:
EXAMPLE: 1Word a variable may not start with a number
word 1 a variable can't have a space
Word*1 * is an invalid character
word/1 / is an invalid character
continue reserved words are not valid identifiers
while reserved words are not valid identifiers
In addition, your instructor may require you to follow certain
naming conventions, which are not required by the
C++ language. For instance:
All constants will consist of upper case alphas, digits, and _.
All variables will begin with a lower case alpha.
When multiple words are used, subsequent words are
capitalized.
Once a valid name is chosen for a variable or a constant, the
next important task is to declare the type of the
variable or constant. Some of the many simple types are listed
in the table below, along with their usage
(meaning), storage size in memory, and possible values.
(Recall that one byte is eight bits: 8 0s and 1s.)
In C++ all decimal numbers are represented in memory in a
shorthand for scientific notation, which has two
parts as in: 2.14 x 105. The first part (2.14 in the example) is
called the coefficient (sometimes called the
mantissa) and the second part is a power of 10. In C++ the 10 is
assumed, and what is stored is the exponent (5
in the example). C++ displays decimal numbers in the form:
2.14e5. Even though all decimal numbers are
stored in scientific notation, they also can be displayed in fixed
point form: 214000.0.
Variable and Constant Types
Type Meaning StorageSize* Values
char character 1 - 4 bytes The keys on the keyboard (and more)
enclosed in single
quotes: '
short signed integer 2 bytes -32,767 to 32,767
int signed integer 4 bytes -2,146,483,647 to 2,146,483,647
long signed integer 4 bytes same as int (may be 8 bytes)
float signed decimal 4 bytes 10-37 to 1038 with 6 significant
digits
double signed decimal 8 bytes 10-307 to 10308 with 15
significant digits
long signed decimal 16 bytes Used for very large and very small
signed numbers
double 10-4931 to 104932 with 19 significant digits
string set of
characters
varies** Any set of characters, enclosed in double quotes: "
* Different computer architectures may assign different storage
sizes than those shown here.
** The string type is considered a complex type, not a simple
type.
For the numeric types there is also an unsigned type, such as
unsigned int (range of values: 0 to 4,294,967,295)
and unsigned short (range of values: 0 to 65,535).
A declaration of a variable consists of its type, its name, and
optionally an assignment of a value to the variable.
A constant declaration consists of the keyword const followed
by its type, its name, and a required assignment
of a value to the constant. The assignments are made by use of
the = operator. All declarations are statements, so
a semicolon must terminate declarations. Some examples of
valid variable and constant declarations are:
EXAMPLE: char userInput;
int counter;
double rate = 0.10;
char response = 'Y';
string prompt = "Enter Y or N => ";
const float PI = 3.14159;
const string KG = "kilograms";
When initializing constants and variables, you may use the
alternative syntax:
EXAMPLE: int counter (0);
double rate (0.10);
C++ requires that all variables and constants must be declared
before they are used. For now, this means the
declaration must precede the uses of the variable. The most
common use of a variable is make an assignment to
it:
EXAMPLE: int counter;
.
.
.
counter = 1;
.
.
.
Variable declarations and assignments are valid when they
contain commas, as these examples show:
EXAMPLE: int num1, num2, num3; // declares 3 integers
double rate1, rate2, rate3; // declares 3 decimals
char YES = 'Y', NO = 'N'; // declarations with assignments
Other simple types include enum and bool (covered in other
modules). Other complex types, in addition to
string, are: struct, union, and class (also covered in other
modules).
USING THE cin FACILITY
User input is stored in variables, already declared in your
program, usually after the user is prompted for the
input.
EXAMPLE: .
.
.
char userResponse;
cout << "Enter Y to continue or N to quit => ";
cin >> userResponse;
.
.
.
The cin facility uses the operator >>, and never contains a
string or character literal, or an endl.
CHARACTER AND STRING VALUES
A literal string, such as "This is a string.", must be enclosed in
double quotes; literal characters, such as 'a',
must be enclosed in single quotes. Certain characters are special
whitespace characters, such as the newline, the
carriage return, the backspace, and the tab, which you may want
to embed in your strings; you may also want to
represent these special characters as literal characters or embed
them within strings.
C++ provides an escape mechanism to represent these special
characters; all escape characters begin with the
backslash, . A partial list would include:
n the newline (on your keyboard, the Return or Enter key)
r the carriage return (in C++ the newline includes the carriage
return)
b the backspace
t the tab key
 the backslash character
" the double quote
' the single quote
Some examples of output strings and characters constructed
with cout are:
EXAMPLE: cout << "This produces a string with " << ''' <<
"single quotes << ''' << " in it";
cout << "I said, "No more!"" << endl;
cout << 'n'; // produces a blank line
cout << "The path is C:tempmisc" << endl;
KEYWORDS
iThe following keywords, or reserved words, can never be used
as identifiers.
and double not this
and_eq dynamic_cast not_eq throw
asm else operator true
auto enum or try
bitand explicit or_eq typedef
bitor export private typeid
bool extern protected typename
break false public union
case float register unsigned
catch for reinterprete_cast using
char friend return virtual
class goto short void
compl if signed volatile
const inline sizeof wchar_t
const_cast int static while
continue long static_cast xor
default mutable struct xor_eq
delete namespace switch
do new template
REVIEW EXERCISES
1. * The main ( ) routine is set out in a block of code, and is
where the program begins execution. T or F?
2. * All comments must begin with //. T or F?
3. * The library routines cout and endl are declared in the
include file <iostream>. T or F?
4. ** Most simple data types can be signed as well as unsigned.
T or F?
5. ** What do the following code snippets output?
cout << "Enter the name of the file to opent=> ";
cout << "The man said: "Enough is enough!"n";
cout << "The path name of the file is " <<
"C:tempfile.out" << endl;
Note that the last cout statement spans more than one line. How
does the compiler determine that this is a
single statement?
6. * What is wrong with the following code snippet?
int main ( ) {
counter = 0;
int counter;
return 0;
}
7. * Which of the following a valid identifiers? Why or why
not?
0num
speedOfLight
user response
if
E
QUART
8. * What type should the variable userResponse have to be to
make the following code snippet
syntactically correct?
cout << "Enter your full name => ";
cin >> userResponse;
9. ** Determine the size of the primitive data types on your
machine. Write a program that prints out the
sizes using lines like the following:
cout << "The size of an int is " << sizeof(int) << endl;
What is the size (i.e., the number of bits) of a char, a short, a
float, a double, and the like?
© 2011 cad rcm cpsm
mailto:[email protected]
mailto:[email protected]
mailto:[email protected]

More Related Content

Similar to INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx

Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0xppd1961
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docxPinkiVats1
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptxAkash Baruah
 
030 cpp streams
030 cpp streams030 cpp streams
030 cpp streamsHồ Lợi
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit IssuesAndrey Karpov
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticPVS-Studio
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cMd Nazmul Hossain Mir
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdfSergiuMatei7
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteachingeteaching
 

Similar to INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx (20)

Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptx
 
030 cpp streams
030 cpp streams030 cpp streams
030 cpp streams
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmetic
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-c
 
C-PROGRAM
C-PROGRAMC-PROGRAM
C-PROGRAM
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdf
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Ch02
Ch02Ch02
Ch02
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 

More from jaggernaoma

Attached is a joint letter to Capitol Hill to advocate for increased.docx
Attached is a joint letter to Capitol Hill to advocate for increased.docxAttached is a joint letter to Capitol Hill to advocate for increased.docx
Attached is a joint letter to Capitol Hill to advocate for increased.docxjaggernaoma
 
Attached is a copy of an interview done with a Tribal member regardi.docx
Attached is a copy of an interview done with a Tribal member regardi.docxAttached is a copy of an interview done with a Tribal member regardi.docx
Attached is a copy of an interview done with a Tribal member regardi.docxjaggernaoma
 
Attached Files Week 5 - trace IP Physical Location.rtf (38..docx
Attached Files Week 5 - trace IP Physical Location.rtf (38..docxAttached Files Week 5 - trace IP Physical Location.rtf (38..docx
Attached Files Week 5 - trace IP Physical Location.rtf (38..docxjaggernaoma
 
Attached here is a psychology article I need to be summarized. Pleas.docx
Attached here is a psychology article I need to be summarized. Pleas.docxAttached here is a psychology article I need to be summarized. Pleas.docx
Attached here is a psychology article I need to be summarized. Pleas.docxjaggernaoma
 
Attached Files News Analysis Sample.docxNews Analysis Sam.docx
Attached Files News Analysis Sample.docxNews Analysis Sam.docxAttached Files News Analysis Sample.docxNews Analysis Sam.docx
Attached Files News Analysis Sample.docxNews Analysis Sam.docxjaggernaoma
 
Attached Files  SOC-220_SOCIAL PROBLEMS PRESENTATION.docx
Attached Files     SOC-220_SOCIAL PROBLEMS PRESENTATION.docxAttached Files     SOC-220_SOCIAL PROBLEMS PRESENTATION.docx
Attached Files  SOC-220_SOCIAL PROBLEMS PRESENTATION.docxjaggernaoma
 
Attached below you will find the series of 4 questions. This assignm.docx
Attached below you will find the series of 4 questions. This assignm.docxAttached below you will find the series of 4 questions. This assignm.docx
Attached below you will find the series of 4 questions. This assignm.docxjaggernaoma
 
Attached below isWEEK 4 As always, include references. As alwa.docx
Attached below isWEEK 4 As always, include references. As alwa.docxAttached below isWEEK 4 As always, include references. As alwa.docx
Attached below isWEEK 4 As always, include references. As alwa.docxjaggernaoma
 
Attached are two articles in one document. Write thoughtful resp.docx
Attached are two articles in one document. Write thoughtful resp.docxAttached are two articles in one document. Write thoughtful resp.docx
Attached are two articles in one document. Write thoughtful resp.docxjaggernaoma
 
Attached are the instructions to the assignment.Written Assign.docx
Attached are the instructions to the assignment.Written Assign.docxAttached are the instructions to the assignment.Written Assign.docx
Attached are the instructions to the assignment.Written Assign.docxjaggernaoma
 
Attached are the instructions and rubric! Research Paper #2.docx
Attached are the instructions and rubric! Research Paper #2.docxAttached are the instructions and rubric! Research Paper #2.docx
Attached are the instructions and rubric! Research Paper #2.docxjaggernaoma
 
Attached are the guidelines for the Expertise Sharing Project. M.docx
Attached are the guidelines for the Expertise Sharing Project. M.docxAttached are the guidelines for the Expertise Sharing Project. M.docx
Attached are the guidelines for the Expertise Sharing Project. M.docxjaggernaoma
 
Attached are the documents needed to complete the assignment. The in.docx
Attached are the documents needed to complete the assignment. The in.docxAttached are the documents needed to complete the assignment. The in.docx
Attached are the documents needed to complete the assignment. The in.docxjaggernaoma
 
Attached are the 3 documents1. Draft copy submitted2. Sam.docx
Attached are the 3 documents1. Draft copy submitted2. Sam.docxAttached are the 3 documents1. Draft copy submitted2. Sam.docx
Attached are the 3 documents1. Draft copy submitted2. Sam.docxjaggernaoma
 
attached are directions needed to complete this essay! Please make s.docx
attached are directions needed to complete this essay! Please make s.docxattached are directions needed to complete this essay! Please make s.docx
attached are directions needed to complete this essay! Please make s.docxjaggernaoma
 
Attach is the checklist For this Assignment, write a 3 and half pa.docx
Attach is the checklist For this Assignment, write a 3 and half pa.docxAttach is the checklist For this Assignment, write a 3 and half pa.docx
Attach is the checklist For this Assignment, write a 3 and half pa.docxjaggernaoma
 
Attach and submit the final draft of your Narrative Essay. Remember .docx
Attach and submit the final draft of your Narrative Essay. Remember .docxAttach and submit the final draft of your Narrative Essay. Remember .docx
Attach and submit the final draft of your Narrative Essay. Remember .docxjaggernaoma
 
Atomic Theory Scientists and Their ContributionsScientist .docx
Atomic Theory Scientists and Their ContributionsScientist .docxAtomic Theory Scientists and Their ContributionsScientist .docx
Atomic Theory Scientists and Their ContributionsScientist .docxjaggernaoma
 
Atomic models are useful because they allow us to picture what is in.docx
Atomic models are useful because they allow us to picture what is in.docxAtomic models are useful because they allow us to picture what is in.docx
Atomic models are useful because they allow us to picture what is in.docxjaggernaoma
 
Atoms and Electrons AssignmentLook at these websites to he.docx
Atoms and Electrons AssignmentLook at these websites to he.docxAtoms and Electrons AssignmentLook at these websites to he.docx
Atoms and Electrons AssignmentLook at these websites to he.docxjaggernaoma
 

More from jaggernaoma (20)

Attached is a joint letter to Capitol Hill to advocate for increased.docx
Attached is a joint letter to Capitol Hill to advocate for increased.docxAttached is a joint letter to Capitol Hill to advocate for increased.docx
Attached is a joint letter to Capitol Hill to advocate for increased.docx
 
Attached is a copy of an interview done with a Tribal member regardi.docx
Attached is a copy of an interview done with a Tribal member regardi.docxAttached is a copy of an interview done with a Tribal member regardi.docx
Attached is a copy of an interview done with a Tribal member regardi.docx
 
Attached Files Week 5 - trace IP Physical Location.rtf (38..docx
Attached Files Week 5 - trace IP Physical Location.rtf (38..docxAttached Files Week 5 - trace IP Physical Location.rtf (38..docx
Attached Files Week 5 - trace IP Physical Location.rtf (38..docx
 
Attached here is a psychology article I need to be summarized. Pleas.docx
Attached here is a psychology article I need to be summarized. Pleas.docxAttached here is a psychology article I need to be summarized. Pleas.docx
Attached here is a psychology article I need to be summarized. Pleas.docx
 
Attached Files News Analysis Sample.docxNews Analysis Sam.docx
Attached Files News Analysis Sample.docxNews Analysis Sam.docxAttached Files News Analysis Sample.docxNews Analysis Sam.docx
Attached Files News Analysis Sample.docxNews Analysis Sam.docx
 
Attached Files  SOC-220_SOCIAL PROBLEMS PRESENTATION.docx
Attached Files     SOC-220_SOCIAL PROBLEMS PRESENTATION.docxAttached Files     SOC-220_SOCIAL PROBLEMS PRESENTATION.docx
Attached Files  SOC-220_SOCIAL PROBLEMS PRESENTATION.docx
 
Attached below you will find the series of 4 questions. This assignm.docx
Attached below you will find the series of 4 questions. This assignm.docxAttached below you will find the series of 4 questions. This assignm.docx
Attached below you will find the series of 4 questions. This assignm.docx
 
Attached below isWEEK 4 As always, include references. As alwa.docx
Attached below isWEEK 4 As always, include references. As alwa.docxAttached below isWEEK 4 As always, include references. As alwa.docx
Attached below isWEEK 4 As always, include references. As alwa.docx
 
Attached are two articles in one document. Write thoughtful resp.docx
Attached are two articles in one document. Write thoughtful resp.docxAttached are two articles in one document. Write thoughtful resp.docx
Attached are two articles in one document. Write thoughtful resp.docx
 
Attached are the instructions to the assignment.Written Assign.docx
Attached are the instructions to the assignment.Written Assign.docxAttached are the instructions to the assignment.Written Assign.docx
Attached are the instructions to the assignment.Written Assign.docx
 
Attached are the instructions and rubric! Research Paper #2.docx
Attached are the instructions and rubric! Research Paper #2.docxAttached are the instructions and rubric! Research Paper #2.docx
Attached are the instructions and rubric! Research Paper #2.docx
 
Attached are the guidelines for the Expertise Sharing Project. M.docx
Attached are the guidelines for the Expertise Sharing Project. M.docxAttached are the guidelines for the Expertise Sharing Project. M.docx
Attached are the guidelines for the Expertise Sharing Project. M.docx
 
Attached are the documents needed to complete the assignment. The in.docx
Attached are the documents needed to complete the assignment. The in.docxAttached are the documents needed to complete the assignment. The in.docx
Attached are the documents needed to complete the assignment. The in.docx
 
Attached are the 3 documents1. Draft copy submitted2. Sam.docx
Attached are the 3 documents1. Draft copy submitted2. Sam.docxAttached are the 3 documents1. Draft copy submitted2. Sam.docx
Attached are the 3 documents1. Draft copy submitted2. Sam.docx
 
attached are directions needed to complete this essay! Please make s.docx
attached are directions needed to complete this essay! Please make s.docxattached are directions needed to complete this essay! Please make s.docx
attached are directions needed to complete this essay! Please make s.docx
 
Attach is the checklist For this Assignment, write a 3 and half pa.docx
Attach is the checklist For this Assignment, write a 3 and half pa.docxAttach is the checklist For this Assignment, write a 3 and half pa.docx
Attach is the checklist For this Assignment, write a 3 and half pa.docx
 
Attach and submit the final draft of your Narrative Essay. Remember .docx
Attach and submit the final draft of your Narrative Essay. Remember .docxAttach and submit the final draft of your Narrative Essay. Remember .docx
Attach and submit the final draft of your Narrative Essay. Remember .docx
 
Atomic Theory Scientists and Their ContributionsScientist .docx
Atomic Theory Scientists and Their ContributionsScientist .docxAtomic Theory Scientists and Their ContributionsScientist .docx
Atomic Theory Scientists and Their ContributionsScientist .docx
 
Atomic models are useful because they allow us to picture what is in.docx
Atomic models are useful because they allow us to picture what is in.docxAtomic models are useful because they allow us to picture what is in.docx
Atomic models are useful because they allow us to picture what is in.docx
 
Atoms and Electrons AssignmentLook at these websites to he.docx
Atoms and Electrons AssignmentLook at these websites to he.docxAtoms and Electrons AssignmentLook at these websites to he.docx
Atoms and Electrons AssignmentLook at these websites to he.docx
 

Recently uploaded

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 

Recently uploaded (20)

Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 

INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx

  • 1. INPUT AND OUTPUT PROCESSING Please note that the material on this website is not intended to be exhaustive. This is intended as a summary and supplementary material to required textbook. INTRODUCTION Most computer programs spend very little processing time in obtaining input and producing output. Most of the work goes into the processing in between. The exception to this generalization is non- browser-based graphical user interfaces (GUIs). In these programs, often over 50% of the code can be dedicated to user input and output. In browser-based user interfaces, the browser does a lot of the work for you. Input/output (I/O) comes in two flavors: interactive and non- interactive. Interactive I/O involves prompting the user for the input and displaying the output on the user's monitor. Non-interactive I/O involves reading and writing files, which for us will be text files. INTERACTIVE I/O The majority of interactive I/O is accomplished in C++ using cin and cout. For now all interactive I/O comes from and goes to the console window. Recall that in order to use cin and cout we have to
  • 2. #include <iostream>. The cin input stream views the input the user types as if the data came from a text file. But, cin ignores as data all whitespace characters: the newline, the tab, and the space. As a result cin does some input formatting for the program, and only assigns non-whitespace data to the input variables. If the user is entering several data items on one line (in the console window), cin will wait for the user to press the newline (Enter or Return) key before it will process the line of input data. The input stream can consist of any array of characters, representing: integers, decimals, strings, single characters, .... Each array of characters is delimited by whitespace characters, and cin will interpret any of the whitespace characters as a delimiter (with some exceptions, of course). When we invoke cin we always have to specify a variable in which to place the user input; that variable must have a type. And, cin is very persnickety about types. If cin is expecting an integer, it will not read an alphabetic character; it will generate an error condition. In the following code snippet cin will expect to see a single character, an integer, a decimal, and a string, in that order. char yOrN; int userID; double hourlyWage; string lastName; ... cin >> yOrN >> userID >> hourlyWage >> lastName;
  • 3. If the user typed the last name for the userID, cin will flag an error and not continue to read the input stream until your program deals with that error (see below). The cout output stream has a lot more variety to it; cout is aware of the types of variables passed to it, and will format them accordingly, unless your program specifies another format to use. When thinking about the arrangement of your program's output, consider each string of output characters as a field, and the contents of each line of output as an array of fields. The following output has 4 fields in the one-line array of fields: Y 1648942 25.00 Smith Every field in the array has a width. In the example above you cannot easily tell by looking exactly what the width of each field is as each field has a tab character in front of it (which you cannot see in this document or on your monitor). Some output will not have such an orderly appearance; you might get a two-line output that looks like (still using a tab in front of each field): Y 1648942 25.00 Smith N 179240578352 35.375 Jones As far as columnar output is concerned we have some generally
  • 4. accepted principles: All columnar output fields should be "lined up" in their own columns, and each column should be wide enough in width to hold the longest field in that column. Non-numeric fields, whether strings of characters or single characters, should be arranged left- justified in their column – that is, so the first character is left- most within the field. Numeric fields, whether integers or decimals, should be arranged right-justified in their column – that is, the last character is right-most within the field. Furthermore, when decimals are used, principle 3 should be violated so every decimal in the column has the decimal point vertically in line. You can probably think of a lot of cases where you might want to violate one or more of these principles, but before you do be aware of why they are principles. Y 1648942 25.00 Smith N 179240578352 35.375 Jones N 15469 30.00 Rimsky-Korsakov Users will expect to see non-numeric string data left-justified in their columns – it makes it easier to scan the column. User will also expect to see numeric integers right- justified in their columns – it makes it easier to tell the difference between 1000000 and 10000000 when scanning. And, users (especially accountants) will want to see all the decimal points lined up vertically for the same reason. Most spreadsheets assiduously follow these principles unless you tell them to do otherwise.
  • 5. Notice that the second column above violates the 3rd principle, and it does so with good reason. The ID number is not really an integer – we do not expect to be doing arithmetic operations on the ID number. The ID number really should be declared as a string and treated just like any other alpha string. Consider U.S. zip codes – do you ever expect to add or subtract these numbers? As programmers, then, we need to know the characteristics and intended uses of our output data. And, we need to format that output so that it is orderly, if not aesthetically, pleasing. Programmers are usually not good judges of either characteristic, and the users who will utilize a program's output should always be consulted about such mundane matters as format. FORMATTING OUTPUT Formatting output can be daunting at first, and we will simplify it considerably here (but see iostream). In order to use the formatting functions you have to: #include <iomanip>. The two most important formatting routines will be setw() and setprecision(). In addition, we will show you how to display decimal numbers in either scientific or fixed-point notation. The setw() function is used to set a field width. The function is used directly in the cout line:
  • 6. cout << setw(10) << numb1 << setw(10) << numb2 << endl; The setw() function requires an integer parameter (in this case 10), and its effect is to specify the field width for each of the two numbers following in the cout statement. If you wanted the second number in a different field width you need to use something like: cout << setw(10) << numb1 << setw(5) << numb2 << endl; If you try to output a string of characters that is too wide for the field width setting, C++ will not truncate the output; it will overfill the field, which will throw off all the rest of the columnar output. Lastly, (and this a real gotcha!) by default C++ will NOT left- justify any output. The default setting is to always right-justify output. You can set the justification on a case-by-case basis with: cout << setiosflags(ios::left) << ...; cout << setiosflags(ios::right) << ...; Whenever you insert a setiosgflags() call in a cout statement, it will apply to ALL subsequent cout statements, unless you explicitly change the flag setting. You can set the number of decimal places to be represented in the output with setprecision() which takes an integer parameter: cout << setprecision(2) < ...;
  • 7. Bear in mind that setprecision() will NOT round off; it will only truncate. If you want to round money to the nearest cent use: float money; ... cout << setprecision(2) << money + 0.005; Also bear in mind that once you use setprecision() this setting will apply to all subsequent calls to cout, unless you explicitly change the precision setting. You can choose to display decimals in either fixed-point or scientific notation. The default is fixed-point. http://www.cplusplus.com/reference/iostream/ Use the following to toggle between the two formats: cout << setiosflags(ios::fixed); cout << setiosflags(ios::scientific); Once you set a format, it stays in effect until you explicitly change the setting. MISCELLANEOUS The getline() function (you must #include <string>) is particularly useful for reading a whole line or the first parts of lines. It has two forms:
  • 8. getline(infile, dest_string); getline(infile, dest_string, delim_char); The first form reads the entire line (up to the newline) from the input stream (infile) into the dest_string (not including the newline); dest_string must be of type string. This form is useful for reading whole lines at a time. The second form reads the line up the delimiter character passed (for instance, ',') into the dest_string (not including the delimiter character). In both cases the next read will continue with the character after the newline or delimiter. You may have noticed that cin reads the input stream and skips over whitespace characters. If you want to read the input stream character by character (one character at a time), including the white space characters, you use the istream member function get(): cin.get(char_variable); Unlike cin and getline(), the get() member function does not strip any characters from the input stream; instead it delivers all characters from the input stream including whitespace characters. HANDLING I/O ERRORS Once an input stream encounters an error, it sets an error flag, and it will refuse to read anything more, until the error flag is cleared. When using cin in situations where the user may mistype (which is really all situations), you would need to check the error flag, inform the user of their error, clear the error flag,
  • 9. and re-prompt the user. We will not cover input error handling in detail yet. Just be aware that your program may just "hang" because of an I/O error. For now, we will program as if the user never makes a mistake typing. NON-INTERACTIVE I/O Non-interactive I/O involves reading and writing text files. In order to read and write files we have to be able to open files for reading and/or writing. When we are done we have to close the file. In order to use the file libraries that contain the file manipulation functions you will have to #include <fstream> and also often <string>. The four operations on files are, then: Open (a file for reading or for writing) Read (an open file) Write (an open file) Close (an open file) Opening a file is straightforward, if you know the name of the file to open, and the file exists in your application program's current working directory, that is, the same directory or folder in which the application program itself is stored. In this case you just use the name of the file: "filename.txt". If the text file is stored in another directory, then you will have to know the full (or relative) pathname of the file. This can get tricky for Windows-based systems, as the pathnames will have a backslash
  • 10. character () in them, which the C++ compiler uses as an escape character. In order to have characters in the pathname string you have to escape the escape character (with ). Hence, the string naming a file: "C:directory1directory2...filename.txt" will often have to be named as: "C:directory1directory2...filename.txt." In non-Windows OSs pathnames use the slash character (/), and that causes no problems for the C++ compiler. (Note: UNIX OSs have problems with file and directory names that contain spaces – ASCII hex 20 or decimal 32 – in them; a good naming practice to follow is to NEVER use spaces in file or directory names; if you ever move your programming working environment to a UNIX system, this practice will save you a lot of headaches.) A further complication is caused by C++ and the C++ compiler. We are used to strings, and it is a string that we use to name files. However, the file open function requires that you use C-language string (which is a NULL-terminated array of characters). The workaround is fairly straightforward. In order to open a file named by a string variable, we will have to first convert it to a C-based character array (using the c_str() member function; see below). Any input file stream will have the type: ifstream (used for reading) and any output file stream will have the type: ofstream (used for writing). We declare these streams as follows: #include <fstream> ... ifstream input_stream_name;
  • 11. ofstream output_stream_name; Most often we will do the declaration and the open in one line, as in: ifstream is("filename.txt", ios::in); ofstream os("filename.txt", ios::out) Once we have an open file we use the stream variable (either is or os in the example immediately above) just like we already use cin and cout: is >> variable_name; os << "And the answer is: " << answer << endl; However, if we name the file by means of a C++ string variable, we have to use the workaround mentioned above. The workaround uses the string member function c_str(). For instance, your programs will often want to prompt the user for the filename and read the name into a string variable. In order to do that and open the file successfully you have to use something like: #include <fstream> #include <string> ... string filename; ... // prompt user for input file name
  • 12. cout << "Enter the name of the input file: " cin >> filename; ifstream is(filename.c_str(), ios::in); As users may mistype the name of the string, you have to be prepared for errors on open with something like: if (is.fail()) { cout << "Cannot open " << filename << endl; // either re-prompt the user or exit your program ... } Last, but not least, when you are done reading or writing a file you should close the file. In any case, you should close the file before exiting, with: is.close(); os.close(); Nothing bad will happen if you do not close a file before exiting, as the OS will take care of that for you. Experienced programmers consider programmers who fail to close open files to be sloppy programmers. REVIEW EXERCISES 1. * Write a program that opens a non-existent file for writing and output some text into the file. Did the underlying OS create a file for your text? 2. ** Write a program that prompts the user for an integer, then
  • 13. prompts the user for a string, then prompts the user for a decimal. Your program should then print out what the user entered. Experiment with various error input scenarios. Try entering 5o1 for the integer (instead of 501). Try entering two separate words for the string (instead of a single word. Try entering 10% for the decimal (instead of .10). Take note of your results! 3. *** Write a program that outputs the following tabular data correctly aligned. Note: you have to reset the I/O flags BEFORE you set the alignment right or left with: cout << resetiosflags(ios::adjustfield); ID First Name Last Name Balance 1 Mary Worth 100.00 2 John Kildare 15.10 3 Harvey Jones 65.27 4 Wilbur Murphy 1145.43 5 Sandra Dee 0.00 6 Amy Santucci 231.55 7 Melissa Cox 2.01 8 Morgan Freeman 1789.03 9 Jack Nicholson 123.67 10 John Brown 426.87 © 2011 cad18; rcm27; cpsm mailto:[email protected] mailto:[email protected] mailto:[email protected]
  • 14. ANALYSIS AND DESIGN Please note that the material on this website is not intended to be exhaustive. This is intended as a summary and supplementary material to required textbook. INTRODUCTION Having a systematic approach two programming means that you will approach each problem in the same methodological way. So you will take the same steps to writing programs for each problem. However, there are some variations. For example, we will present to general systematic approaches to programming here. The first approach is constructed for the beginning programmer. It is relatively simple and basic and helps the student programmer get a handle on the necessary tools. The second approach models the kind of approach used by professional programmers. This approach is sometimes called the Software Development Life Cycle (SDLC). With this second approach, you will see a summary of a different and more complicated organization of basically the same material. Our suggestion is that you start with the first approach and then change over to the second one when you are ready. In the end, you should choose the approach that best helps you get a handle on the problem you are programming for. The simple approach to a systematic approach states that there are two parts to a systematic approach to programming. These two parts consist of solving the problem and implementing the
  • 15. solution. What needs to be emphasized here is that the first part is done without writing any code. The solution to the problem is logically constructed and is expressed using specific tools and templates. After the solution is constructed, we implement it. This implementation includes using programming languages that eventually have to be translated into the computer's machine language – the actual language that the computer understands. THE ANALYSIS The first part of solving the problem has 3 sub-steps. Those 3 sub-steps consist of writing the analysis, writing the design, and testing the solution. First, it is important to distinguish analysis from the design. The analysis expresses the basic informational requirements of the problem. This information conveyed in the analysis includes the data inputs of the program, the data outputs, data that is calculated but not part of the output, and formulas. The beginning template we will use for the analysis is below. Note that this is only a beginning template and that you should find your own way to modify this template as more complex problem solving and programming issues are introduced. Analysis: Input: Output: Temporary Variables: Formulas: The input part of the analysis will consist of the information that the person running the program, the user, will enter. This
  • 16. usually consists of data values only; the user rarely, if ever, enters a formula. The output part of the analysis will consist of the information that the user either wants to see, store, or send to another location. Like the input, we are usually referring to data values. The Temporary Variables will consist of all values calculated in the formulas but are not output. Finally, we will list the formulas used. In terms of the sequence of filling out this analysis template, we need to fill out the Formulas before we fill out the Temporary Variables, because the Formulas often determine what is a Temporary Variable. But in terms of the order of appearance, Temporary Variables will be listed before the Formulas because, like input and output, Temporary Variables are data and it is preferable to list like items together. Below is a sample analysis. The problem that this sample analysis will address is listed before the analysis. Problem: You are to find and display the average of 3 test scores. Analysis: Input: Test #1, Test #2, Test #3 Output: Average Temporary Variables: Total Formulas: Total = Test #1 + Test #2 + Test #3 Average = Total/3
  • 17. We should note few things about the above analysis. For the Input, Output, and Temporary Variables, we do not fill in numeric values. It is the job of the user to select the numeric values for the Input and the job of the computer to calculate the numeric values for the Temporary Variables and Output. The next thing we should observe is that once a term is used, Average in the Output for example, that term is spelled the same way throughout the rest of the analysis. As a result, Average in Formulas is spelled the exact same way as Average in Output. Finally, Total is a Temporary Variable because its value is calculated in Formulas, but is not part of the Output. THE DESIGN The next part of solving the problem consists of writing the Design. While the Analysis is concerned with understanding the problem by listing its requirements, the Design contains the actual solution to the problem. How that solution is expressed depends on the kind of problem solving approach we are using. In an Object-Oriented (OO) programming approach, we would be identifying the parts or players needed to solve the problem and then we would determine how and when these parts would communicate with each other to actually solve the problem. We will be using a Structured programming approach, which is much easier to use. Though there are other parts to it, the Structured programming approach is primarily concerned with taking the right sequence of actions to solve the problem. The solution will be expressed using verb-phrases. One can use a number of tools when expressing the solution in a Structured programming approach. At this programming level, we will write the solution to our problems using an algorithm. There are three important parts to the definition of an algorithm. The first part says what we
  • 18. have already said, that there is a correct sequence of actions to take. The next part says that this sequence of actions will solve the problem – that is, give us the correct answer every time. Finally, the solving of the problem occurs in a timely fashion. If writing a design means listing the actions, we need to know what actions are available to us. The actions available to beginning programmers include get input, process information, and print output. When we say get input, we are telling the computer to ask the user to enter in specific information and then tell the computer to use the appropriate input device to read that information. When we say process information, we are telling the computer to apply operations (arithmetic, logic, or shifting) to data it has. And when we say print output, we are telling the computer to send the requested information to a specified output device, usually the monitor. We should note that during the design time, we are not actually telling the computer to do anything; telling the computer to act is in our planned solution, and programming the computer comes later. Now we know what actions we can take, we need to determine the order of the actions to write the algorithm. The steps in an algorithm can be determined in a number of different ways. Some of these approaches include working backwards, using the algorithm from a similar problem, means-ends, and trial and error. But the one we will use here is called the Input-Process- Output (IPO) algorithm. What this means is that we will list all of the get input steps first, then we will list all of the process information steps second, and we will finally list all of the print output steps last. To determine what get input, process information, and print output steps we need we will consult the analysis for that problem. Below is an example of an algorithm that is written by applying the IPO approach and using the analysis of that problem.
  • 19. Problem: Find and display the average of 3 test scores. Analysis: Input: Test #1, Test #2, Test #3 Output: Average Temporary Variables: Total Formulas: Total = Test #1 + Test #2 + Test #3 Average = Total /3 Design (using an IPO algorithm): Get test #1 Get test #2 Get test #3 Calculate Total Calculate Average Print Average Using the IPO approach, we started by listing the get input steps. How do we know what get input steps are involved? For each input item, whcih we will call a variable, in the input part of the analysis, we write a get input step. That is why we have the steps Get test #1 and so on. Then for each formula in the analysis, we will write a process information step. Each step will state what it is calculated. We do not need to rewrite the formula used. That is why we wrote Calculate Total and Calculate Average. Finally, the print output step was determined writing the step for each variable in the output part of the analysis.
  • 20. We have arrived at the final part of Solving the Problem. That part is testing the solution. Note that we are testing the solution before we write any code. Though we will be testing the solution by testing the code later on. THE TEST OF THE SOLUTION The last part of solving the problem consists of testing our analysis and design. We can do this by creating a table of information using a spreadsheet. Using the analysis and design from the test average problem, our test of the solution of the analysis and design looks like the following: Test1 Test2 Test3 Total Average Get Test1 90 ? ? ? ? Get Test2 90 80 ? ? ? Get Test3 90 80 70 ? ? Calc Total 90 80 70 240 ? Calc Average 90 80 70 240 80 Print Average 90 80 70 240 80 To construct this test, we simply put each variable from the analysis into a column and put each design step into a row. The values entered for Test1, Test2, and Test3 produce a result that is known without using the formulas from the analysis. The value for Total is calculated by implementing the formula in the analysis by adding the cells containing the test scores for that row. And we implement the formula used to calculate Average by dividing the contents of the cell holding the Total for that row by 3. Returning back to the values we entered for Test1, Test2, and Test3, we need to repeat that we, those who constructed this test, must pick values that produce a known result. That is because if the answer calculated for Average is different from 80,
  • 21. the answer we expected, we know that there was an error in either the Analysis and/or the Design. IMPLEMENTING THE SOLUTION Implementing the solution means exactly what it says. We have to tell the computer how to carry out our solution to the problem. To do that, we must translate the solution into code, we must eliminate errors, and we must document the code. But whereas the order in which the steps of solving the problem are performed are sequential, the steps in which implementing the solution takes place, for the most part, are concurrent. That is we will be translating the solution, eliminating error, and documenting the code seemingly at the same time. TRANSLATING THE SOLUTION If we have put the appropriate work into solving the problem, then writing the code will be like translating a U.N. speech into the language of a listener. Most of the mental work, for the beginning programmer, takes place while we try to solve the problem. Translating the solution should be simple once we have sufficiently learned the language. Writing code has 3 prerequisites. You must know what each part of the code does. We can learn that by reading definitions and seeing examples. You must also know the syntax of each C++ construct you have to use. Knowing this syntax is equivalent to knowing the syntax of the language you speak in. When writing code, the syntax of the programming language tells us the order in which each symbol should occur. Finally, and this is where using the solution to the problem comes into play, the solution to the problem tells us when to use each C++
  • 22. construct. That is what we need to know to write code. We need to understand each construct we use, we need to know the syntax so that we can write the code properly, and we need to know when to use each construct. We will not go into the details here, but as you learn the different C++ constructs, remember the constructs used by the solution so you can recognize what C++ construct to write as you translate each part of your solution into code. ELIMINATING ERRORS The errors that we must correct when writing programs are of 3 kinds: compiler errors, runtime errors, and logical errors. We should note that we will be oversimplifying things when describing compiler errors. Before defining what a compiler error is, we must first define a compiler. A compiler is one of the tools that a computer uses to translate code, written in a programming language, into a language a computer understands. To help translate what is written in a programming language, a compiler must perform two tasks. The first task of the compiler is to check the code for syntax errors. A syntax error is when the symbols of a piece of code are in the wrong order. If the compiler spots a syntax error, it notes it and goes on to look for the next error so that these errors can be reported to the user. If the code being compiled does not have any syntax errors, then the compiler translates the code into machine code, code in a language the computer understands, and writes it to a file with a .obj or .o extension. Now even though the contents of the .obj and .o files are in machine code, it is not quite ready for the computer to execute the file. In order to execute the code, the machine language must be loaded into main memory. The next kind of error that we must know how to correct is a
  • 23. runtime error. Whereas compiler errors occur when different parts of the code are not written in the correct order, a runtime error occurs when there are no syntax errors. A runtime error occurs when use the correct syntax to tell the computer to do something it cannot do. A common example of a runtime error is when we tell the computer to divide by 0. Because we cannot divide by 0, we cannot tell the computer how to divide by 0; thus when the computer is told to divide by 0, it is told to do something that it is not able to do. How a computer reacts to a runtime error is unpredictable. That is because how a computer reacts to such an error depends on the machine and the software it runs. Runtime errors are more difficult to solve than compiler errors. That is because runtime errors are more difficult to locate than compiler errors. The final kind of error that we must know how to eliminate is a logical error. Logical errors contain no syntax errors or runtime errors. A logical error occurs when the programmer writes code that tells the computer to do something that does not help solve the problem. For example, suppose we are writing a program that will find and display the average of 3 test scores. And suppose that we have added the 3 tests together but when we calculate the average, we divide by 4 rather than 3. We can tell the computer to divide by 4 legally and the computer is able to do that. The problem is that dividing the total by 4 does not tell the computer how to calculate the average of 3 tests. All of the 3 errors types are corrected by re-editing the code and retesting, until no errors remain. DOCUMENTING THE CODE
  • 24. Documentation is a plain language description of either of what the whole program does or what a part of the program does. The first step in documenting the code is to provide documentation at the top of the file. An example is provided below: /* Program: TestAverage.cpp Name: Your Name Date: 07/28/10 Purpose: The purpose of this program is to find and display the average of 3 test scores */ It is recommended that you document your program as you are writing the code rather than to document after you finish writing the code. Again, when implementing the code, we will be translating the solution into code, eliminating errors, and documenting the code concurrently. When discovering a logical error in the code, if the error is because of a mistake in the analysis or design, then the analysis and design must be corrected immediately. Then we correct the code, recompile, and retest. REVIEW EXERCISES Using the methods of this module provide a design, analysis, and test of the algorithms you previously developed in the Review Exercises at the end of the Introduction to Programming Environments module.
  • 25. © 2011 cad18; rcm27; cpsm mailto:[email protected] mailto:[email protected] mailto:[email protected] C++ BASCIS Please note that the material on this website is not intended to be exhaustive. This is intended as a summary and supplementary material to required textbook. INTRODUCTION As all languages have a grammar, a description of what counts as a "well-formed" sentence, so does C++. This module explains some of the basic syntax, or grammar, of C++. A compiler is a tool that translates C++ code into instructions the computer hardware understands. COMMENTS Comments are entirely ignored by the compiler, so you can put anything you want in them. One way to add a comment is to use // which indicates that the rest of the line is a comment: EXAMPLE: ... // the rest of this line is a comment Alternatively, multiple lines can be comments using the /* ... */ notation:
  • 26. EXAMPLE: /* . . . all of this text is a comment and is entirely ignored by the compiler . . . */ In addition, the compiler ignores blank lines. For the most part, the compiler also ignores spaces and indentations (tabs). A very simple C++ program will look something like the following: EXAMPLE: // The purpose of this program is to illustrate how a C++ program is constructed #include <iostream>; using namespace std; // the main () routine is where the program begins // execution int main () { cout << "Hello World!" << endl; return 0; } This program begins with a comment; indeed, every program should begin with a comment explaining its basic
  • 27. purpose. Good software design principles require comments liberally placed throughout the code. This example also has a comment before the main routine. The entire main ( ) routine is contained within curly braces, { and }, which delimit the body of the main routine in a block. INCLUDE DIRECTIVES The purpose of include directives is to allow the programmer to take advantage of the many facilities that have already been coded, compiled, and tested. The definitions of cout and endl are in the <iostream> include file (often called a header file). If you leave out the include <iostream> statement, this simple program will not compile. The include files do not contain compiled code; rather, they contain the C++ definitions of various terms. The compiled code for the items defined in a header file is in libraries. The using namespace std; is also necessary. For now, we will think of a namespace as akin to a dictionary, with the definition of various terms listed in the namespace (called std). When a program is compiled, before the compiler begins its work, a preprocessor reads into the file all of the contents of the files named in the include statements. Most compilers are two-pass compilers; that is, after the preprocessor has run the compiler makes two passes through the code: once to check the syntax, and if the syntax passes, the second pass produces the object code.
  • 28. The linker is responsible for combining the object code with the libraries of routines defined in the include files to produce a program that is executable. An executable program still has to be loaded into memory to be run, and the loader is responsible for this. MAIN ROUTINE The main ( ) routine is where the program begins execution, once the executable is loaded into memory. A simple main routine may only be responsible for obtaining input to the program, processing the input, and producing the output. More complicated main routines are more like traffic directors, defining the route the program must traverse in order to accomplish its objective. The main routine is defined within a block of code contained within curly braces. The int main ( ) part is the header of the main routine, and it merely says that main is a function (i.e., the ( ) part), and it returns an integer value when it exits. The main routine in the example above returns 0 when it exits (i.e., the return 0; part). Within a block of code every line is a statement or a comment. A statement is a syntactically correct sentence of C++. All statements are terminated with a semicolon (;). Normally, only one statement is written on a single line, but you may put multiple statements on a single line. You may also have statements that require several lines in a file. An essential characteristic of a statement is that it ends with a semicolon. In the example above there are two statements: one beginning with cout and ending with a semicolon, and one beginning with return and ending with a semicolon. Note especially that blocks of
  • 29. code do not end with a semicolon; they end with a close curly brace. INPUT AND OUTPUT> Most programs require input and most programs produce output. Sometimes the only output from a program indicates that an error occurred (this is called error output). For now all input will be done using the cin facility (see below), and all output will be done by using the cout facility. Both of these facilities are defined in the <iostream> header file. In the example above, the program outputs the text contained between the double quotes, i.e., the string Hello World!. The endl causes the end of the line to be a newline, which moves the cursor in the output window to a new line. Both of these items are separated with an operator: <<. Thus the cout line in the example first outputs the string Hello World!, followed by a newline. A prompt is an output statement that solicits input from the user of the program. Typically these are strings that are not followed by an endl. EXAMPLE: cout << "Enter the name of the file to open => "; cout << "Enter Y for yes or N for no => "; WRITING YOUR FIRST C++ PROGRAM
  • 30. Your first program will be the example shown above. SYNTAX, SEMANTICS, and METALANGUAGE In order to fully describe the C++ language, we must explain how to form syntactically correct statements using the facilities of the language. Next, we must describe what the different statements of the language mean, i.e., the semantics of the facility. Our description of the facilities of C++ is carried out in yet another language, English, which is our metalanguage, i.e., the language we use to describe another language: C++. VARIABLES AND CONSTANTS; ASSIGNMENT Variables and constants are specified in C++ by means of declarations. Each declaration names a variable or constant and indicates how it will be used, its type. The name of a variable or constant is called an identifier. Identifiers must be formed according to the following rules: all identifiers consist of the following letters and only the following letters (note that a space is not included): A, B, C, D, ..., Z (upper case alphas) a, b, c, d, ..., z (lower case alphas) 0, 1, 2, 3, ..., 9 (digits) _ (the underscore) An identifier may not begin with a digit. Further, no identifier can be the same as a keyword (a reserved word) in C++; keywords are listed below. Thus the following are valid identifiers:
  • 31. EXAMPLE: isAnAlpha _myVariable PI word1 Word_1 The following are NOT valid identifiers: EXAMPLE: 1Word a variable may not start with a number word 1 a variable can't have a space Word*1 * is an invalid character word/1 / is an invalid character continue reserved words are not valid identifiers while reserved words are not valid identifiers In addition, your instructor may require you to follow certain naming conventions, which are not required by the C++ language. For instance: All constants will consist of upper case alphas, digits, and _. All variables will begin with a lower case alpha. When multiple words are used, subsequent words are capitalized. Once a valid name is chosen for a variable or a constant, the next important task is to declare the type of the variable or constant. Some of the many simple types are listed
  • 32. in the table below, along with their usage (meaning), storage size in memory, and possible values. (Recall that one byte is eight bits: 8 0s and 1s.) In C++ all decimal numbers are represented in memory in a shorthand for scientific notation, which has two parts as in: 2.14 x 105. The first part (2.14 in the example) is called the coefficient (sometimes called the mantissa) and the second part is a power of 10. In C++ the 10 is assumed, and what is stored is the exponent (5 in the example). C++ displays decimal numbers in the form: 2.14e5. Even though all decimal numbers are stored in scientific notation, they also can be displayed in fixed point form: 214000.0. Variable and Constant Types Type Meaning StorageSize* Values char character 1 - 4 bytes The keys on the keyboard (and more) enclosed in single quotes: ' short signed integer 2 bytes -32,767 to 32,767 int signed integer 4 bytes -2,146,483,647 to 2,146,483,647 long signed integer 4 bytes same as int (may be 8 bytes) float signed decimal 4 bytes 10-37 to 1038 with 6 significant digits double signed decimal 8 bytes 10-307 to 10308 with 15 significant digits
  • 33. long signed decimal 16 bytes Used for very large and very small signed numbers double 10-4931 to 104932 with 19 significant digits string set of characters varies** Any set of characters, enclosed in double quotes: " * Different computer architectures may assign different storage sizes than those shown here. ** The string type is considered a complex type, not a simple type. For the numeric types there is also an unsigned type, such as unsigned int (range of values: 0 to 4,294,967,295) and unsigned short (range of values: 0 to 65,535). A declaration of a variable consists of its type, its name, and optionally an assignment of a value to the variable. A constant declaration consists of the keyword const followed by its type, its name, and a required assignment of a value to the constant. The assignments are made by use of the = operator. All declarations are statements, so a semicolon must terminate declarations. Some examples of valid variable and constant declarations are: EXAMPLE: char userInput; int counter; double rate = 0.10; char response = 'Y'; string prompt = "Enter Y or N => "; const float PI = 3.14159;
  • 34. const string KG = "kilograms"; When initializing constants and variables, you may use the alternative syntax: EXAMPLE: int counter (0); double rate (0.10); C++ requires that all variables and constants must be declared before they are used. For now, this means the declaration must precede the uses of the variable. The most common use of a variable is make an assignment to it: EXAMPLE: int counter; . . . counter = 1; . . . Variable declarations and assignments are valid when they contain commas, as these examples show: EXAMPLE: int num1, num2, num3; // declares 3 integers double rate1, rate2, rate3; // declares 3 decimals char YES = 'Y', NO = 'N'; // declarations with assignments Other simple types include enum and bool (covered in other modules). Other complex types, in addition to string, are: struct, union, and class (also covered in other modules).
  • 35. USING THE cin FACILITY User input is stored in variables, already declared in your program, usually after the user is prompted for the input. EXAMPLE: . . . char userResponse; cout << "Enter Y to continue or N to quit => "; cin >> userResponse; . . . The cin facility uses the operator >>, and never contains a string or character literal, or an endl. CHARACTER AND STRING VALUES A literal string, such as "This is a string.", must be enclosed in double quotes; literal characters, such as 'a', must be enclosed in single quotes. Certain characters are special whitespace characters, such as the newline, the carriage return, the backspace, and the tab, which you may want to embed in your strings; you may also want to represent these special characters as literal characters or embed them within strings. C++ provides an escape mechanism to represent these special characters; all escape characters begin with the backslash, . A partial list would include: n the newline (on your keyboard, the Return or Enter key)
  • 36. r the carriage return (in C++ the newline includes the carriage return) b the backspace t the tab key the backslash character " the double quote ' the single quote Some examples of output strings and characters constructed with cout are: EXAMPLE: cout << "This produces a string with " << ''' << "single quotes << ''' << " in it"; cout << "I said, "No more!"" << endl; cout << 'n'; // produces a blank line cout << "The path is C:tempmisc" << endl; KEYWORDS iThe following keywords, or reserved words, can never be used as identifiers. and double not this and_eq dynamic_cast not_eq throw asm else operator true
  • 37. auto enum or try bitand explicit or_eq typedef bitor export private typeid bool extern protected typename break false public union case float register unsigned catch for reinterprete_cast using char friend return virtual class goto short void compl if signed volatile const inline sizeof wchar_t const_cast int static while continue long static_cast xor default mutable struct xor_eq delete namespace switch do new template REVIEW EXERCISES 1. * The main ( ) routine is set out in a block of code, and is where the program begins execution. T or F?
  • 38. 2. * All comments must begin with //. T or F? 3. * The library routines cout and endl are declared in the include file <iostream>. T or F? 4. ** Most simple data types can be signed as well as unsigned. T or F? 5. ** What do the following code snippets output? cout << "Enter the name of the file to opent=> "; cout << "The man said: "Enough is enough!"n"; cout << "The path name of the file is " << "C:tempfile.out" << endl; Note that the last cout statement spans more than one line. How does the compiler determine that this is a single statement? 6. * What is wrong with the following code snippet? int main ( ) { counter = 0; int counter; return 0; } 7. * Which of the following a valid identifiers? Why or why not? 0num speedOfLight user response if E QUART
  • 39. 8. * What type should the variable userResponse have to be to make the following code snippet syntactically correct? cout << "Enter your full name => "; cin >> userResponse; 9. ** Determine the size of the primitive data types on your machine. Write a program that prints out the sizes using lines like the following: cout << "The size of an int is " << sizeof(int) << endl; What is the size (i.e., the number of bits) of a char, a short, a float, a double, and the like? © 2011 cad rcm cpsm mailto:[email protected] mailto:[email protected] mailto:[email protected]