1 Intro to Programming

advertisement
1 Introduction to Programming
Lesson 1 - Building Your First Program
Step 1: Launching C++
We will be using Microsoft’s Visual C++ 2008 Express. You can install the same
version on your computer at home if you wish since the software is free. Upon launching
VC++ you will see the following screen. (The first time you launch VC++ you may get a
message “VC++ is configuring the environment for first time use. This may take a few
minutes.”)
When you open VC++, you will find window with multiple areas. In addition, you will
have a lot of toolbar items, most of which are inactive. Through this course, I strongly
encourage you to casually move your mouse across the various toolbar items to see the
ToolTips highlights which will indicate their name.
At times you may wonder where certain toolbar items have gone. Some toolbars are only
active when you are in a certain state of program development. If you are missing a
needed toolbar, simply perform the following steps:
1 Intro to Computer Science
1
· Select Tools/Customize..
· Select the Toolbars tab.
· Check the toolbars which you want activated. The ones you will normally make use
of, particularly in this course are:
Menu Bar
Standard
Build
Debug
· After selection, click the Close button.
Step 2: Setting Project Parameters
Choose File/New/Project... (or click the New Project button). The New Project dialog
box will appear. Be sure the Win32 project type is selected and the Win32 Console
Application template, as shown below.
1 Intro to Computer Science
2
If the following path is not specified, type it in, replacing “userid” with your actual user
id.
\\12WDC1\userid$\My Documents\Visual Studio 2008\Projects
Finally, supply the name for your first project: 01 My First Project
You will want to supply a meaningful name for this (and every) project. You will always
be told what to name your projects. DO NOT choose names other that those suggested by
your teacher. The location should be your student directory on the server. Upon clicking
the OK button you will be taken to the “Win32 Application Wizard” window. Click on
the Application Settings text. Be sure the Console application and Empty project
options are selected as shown below:
Click Finish. You should now have a blank project with which you are ready to work.
1 Intro to Computer Science
3
Step 3: Adding a file to the project
Your screen should now have the following displayed in the Solution Explorer window:
We now need to add a file to the project so we can work. Select Project/Add New
Item… (or click the Add New Item button). In the window displayed, be sure the Code
category is selected and the C++ File template is selected as shown in the following
image.
1 Intro to Computer Science
4
Varify that the Code category is chosen and the C++ File (.cpp) template is selected.
Finally, you must supply a name before continuing. We will always use “main”. Note
this is not the name of the project, which is why it can always be the same. You don’t
have to type the .cpp extension – this is supplied automatically by VC++.
You should now be staring at a screen similar to the following:
1 Intro to Computer Science
5
And you are now ready to begin writing the code for your first program.
Step 4: Adding code to the file
At the very least every project should have the following code:
#include <iostream>
using namespace std;
void main()
{
system("pause");
}
Step 5: Building your program
You are now in a position to “build” (compile) your program. The compiler is itself a
program which translates the text you see in the code window into lower level code that
is understood by the computer. Select Build/Build Solution (or press the F7 key). In a
moment you will see some text appear in the Output window at the bottom of the screen.
Hopefully the last line will say the following:
1 succeeded, 0 failed, 0 skipped
This means the compiler was able to understand everything you typed in the code
window and was able to successfully translate it into machine language. You are now
ready to “run” your program. If all did not go well you may have one or more errors that
have to be fixed. We will talk more about those in the following lesson.
Step 6: Running your program
Press the Start Debugging button on the menu bar ( ) (or select Debug/Start
Debugging, or press the F5 function key). You may see the following window appear:
1 Intro to Computer Science
6
Since it’s annoying to get this window each time you want to run a program it’s advisable
to check the Do not show this dialog again checkbox and then click the Yes button.
You should be presented with a window similar to the following:
If all didn’t go well you may have one or more errors reported by the compiler (like an
internal translator). We will learn about some of the different types of errors in the next
lesson. For now the only error you’re likely to have is a syntax error – a misspelled
word.
Step 7: Experimenting with your program.
Try to adding the following lines to your program (these added piecemeal during class by
the teacher to avoid confusion):
1 Intro to Computer Science
7
#include <iostream>
using namespace std;
void main()
{
cout << endl << "Hello world!";
cout << endl << endl << "Welcome to CS20S";
cout << endl << endl;
system("pause");
}
Read the code that you wrote in this program carefully and try to answer the following
questions:
1. What do you think the cout <<... line does?
2. What is the effect of using more (or less) endl’s on the cout lines?
3. Experiment with this program by changing the message that is printed to the user!
Step 8: Submitting a program to your teacher
As we continue working together, you will be required to write many programs on your
own. You will be assisted in class. You will be your own best helper. Learning
programming is a combination of trial and error, practice, and plenty of patience.
Being that you outnumber your teacher, you will be frustrated if you are waiting for me
with each and every problem. Do yourself a favor and spend some time doing your best
to figure out your own bugs (mistakes). Of course early on this will be hard, but with
practice you will become more adept at fixing incorrect code.
You can certainly work on code at home, but since your programming is done at school
your files will reside here. Programs will be printed in class and handed in in class.
You are responsible for your own success in this class. If you do not know the material
for yourself you will not perform well on tests. From the beginning you must force
yourself to figure things out as much as possible on your own. Also, be warned that
cheating will not be tolerated. Programs submitted as yours that do not reside in your
network directory will be assumed to be someone else’s work and will not be accepted.
1 Intro to Computer Science
8
1 Introduction to Programming
Lesson 2 – Introduction to Debugging
The art of programming is complicated by one particularly serious problem - the
computer doesn't know when we make programming mistakes.
In the early days of computing, there was a moth in a computer causing the computer to
malfunction. From that early experience, the task of removing errors from programs is
called “debugging”.
Programming errors are divided into two categories:
1. Compile-time Errors. These are errors which prohibit the compiler from actually
creating an executable file.
2. Run-time Errors. These are errors which occur during the execution of your
program (where the output you get is incorrect).
In this first lesson on debugging, you will:
1. Explore the effects of various seemingly small programming errors.
2. Learn how to find and correct the errors.
The errors we will explore in this first debugging lesson are limited to compile-time
errors.
Begin the debugging lesson by performing the following tasks:
1. Create a new project called 02 Debug
You may wish to review the lesson on creating new projects.
2. Create a new source file in the 02 Debug project called main.
3. Enter the following code into the source file.
a comment
(“green stuff”)
1 Intro to Computer Science
9
4. Make sure the code works by building the exe file and executing it.
Next we will introduce some programming errors and explore their effects.
To explore our first error, modify the code as shown below.
When you compile (hit F7) this code (with only the one error), your resulting compiler
message pane (at the bottom of the VC++ window) will look like:
error C2013: missing '>'
is certainly very discriptive – we know exactly what to
fix.
What you need to do is try to eliminate errors, frequently one at a time, always starting
with the first one.
The process of removing compile-time errors is illustrated below.
1 Intro to Computer Science
10
To demonstrate another programming error, follow the steps below:
1. Start by ensuring the code in your debug1 project is correct and working.
2. Modify the code with the errors shown in red. Make one error at a time to see the
effect each one has.
Correct the code by following the debugging process illustrated on the previous
page. This time, try this process by only correcting the first error in the error message
window before recompiling.
To summarize, when you debug
1. Always start by correcting the first error in the compiler message window.
2. Continue the compiler/correct cycle until all compile-time errors are eliminated.
1 Intro to Computer Science
11
Sometimes, you will get compile-time errors which make no sense to you. If that
happens, I want you to
1. If you want to do a fresh build (compile), select Build/Rebuild. Sometimes, with
large projects, the compiler may need to perform all of its tasks from the
beginning.
2. Only after you have made a sincere effort to find and correct your errors should
you call over your instructor for assistance.
1 Intro to Computer Science
12
1 Introduction to Programming
Lesson 3 - Parts of a Program
For you, the programmer, to instruct the computer on the various tasks it is to perform,
you must write your code in a form which the compiler will understand. This will require
you to perform flawlessly in order for the program to work to your expectations. The
compiler has very specific expectations as to what it will process. As a result, you will
need to understand all the various parts which make up a computer program. Initially, the
parts of the "Hello World" program which we will explore are:
Comments - explanations to yourself and other programmers as to what the actual code is
trying to accomplish
#include
files - instructs the compiler to include certain pre-coded files provided with
the C++ environment
The main() function - this is where every executable program starts execution
Code blocks - help to define sections of code which perform specific tasks
The cout statement - used to display information to the user output screen
New Line command - used to move output down to the next line on the screen
After we have completed this initial study, you will demonstrate your knowledge with a
series of programming assignments.
Comments
Languages like C++ use English words, but they often are very cryptic (though not as bad
as machine language in terms of readability). Comments are useful for a variety of
reasons.
1. Because code can be difficult to follow, comments can serve as reminders to the
author of the code just what is happening in line or chunk of code.
2. Comments document what we are doing in our programs. Creation and modification
details are important especially when many programmers are involved in a project.
Comments are ignored by the compiler when it is converting your program to machine
code. For this reason, “commenting out” suspicious code can be a useful debugging
strategy.
1 Intro to Computer Science
13
Comments in C++ are available in two styles.
Any text which follows two consecutive forward slashes (//) is ignored by the compiler..
// the computer ignores everything after the double slash
Any text between a /* and a */ is ignored by the compiler.
cout << "Hello /*Comments can also be placed inside the code*/ World";
Though the above is doable, it’s not recommended and would be an example of poor
programming practices.
Here’s an example:
/*
Project Name:
Programmed By:
Date:
--
Envelope Labeling
Joe Cool
6 Oct 2009
program description here --
*/
#include <iostream>
comments
using namespace std;
void main()
{
// put a comment above possibly confusing code
cout << "Hello" << endl << endl;
cout << "Welcome to Computer Science 20S";
cout << endl << endl;
system("pause");
} // end main
#include
// hold the output window on screen
files
is a request for a header file – a file that has already been written and is part of
the library of files that are packaged with C++.
#include
#include <iostream>
The “iostream” file contains instructions to handle simple input and output (literally
input/output stream). The preprocessor takes care of attaching this file to your code. If
you would have to write the instructions for simple input and output, your simple hello
world program would be several thousand lines long. We will use the appropriate header
files as they become necessary.
1 Intro to Computer Science
14
void main()
C++ programs are made up of different parts called functions. main is the only function
which must appear. Most often the main function will be of type void. We will learn
about other function types in the second half of this course. Functions allow us to break
our programs up into logical pieces, each one dedicated to a specific task. After the task
is complete, the function may or may not send results back to the process which “called”
the function. In our case void main doesn’t return anything (hence “void”). It is not
unusual for a program to be made up of dozens of functions.
Code Blocks
Blocks of code are delimited by braces ({..}). Braces always come in pairs - an
“opening” brace ({), and a “closing” brace (}). In the following code segment the braces
indicate the beginning and end of the main function, but braces are also used in other
situations we will learn about.
braces
void main()
{
cout << "Hello" << endl << endl;
cout << "Welcome to Computer Science 20S";
cout << endl << endl;
system("pause");
} // end main
Visual C++’s editor has a nice feature of highlighting the pair when the closing brace is
typed. This will come in handy when our programs have increasing numbers of code
blocks, some nested inside of others.
cout
(pronounced “see out”) is a special variable, defined in the iostream header file.
refers to the default output device which in our case will be the console output
window (literally console out). cout tells the compiler that what comes after it is to be
displayed in the console window.
cout
cout
Immediately after cout we find a pair of less than signs (<<). These are actually
considered as one character, even though we type two. This symbol pair is called the
insertion operator and it tells the compiler to insert the content which follows into the
output stream. In the above program, the insertion operator inserts the character string
“Hello”. You might have noticed we can insert more than one item at a time into the
output stream…
1 Intro to Computer Science
15
cout << "Hello" << endl << endl;
Of the three items to be inserted into the output stream above, the first one is called a
character string. The other two are discussed in the next section.
All C++ executable statements (or just “statements” for short) end with a semicolon (;).
This indicates the end of the statement to the compiler. Please note that this feature can
be abused by programmers wanting to claim shortest possible programs. To wit, the
following program works just fine..
#include <iostream>
using namespace std;void main(){cout<<"Hello"<<endl<<endl;cout<<"Welcom
e to Computer Science 20S";cout<<endl<<endl;system("pause");}
..but it is hardly readable.
The New Line Command
endl
endl
(end line) causes the output device to move to the next line. Note that each time
is used, it must be preceeded by an insertion operator (<<). There is another way of
moving to a new line in the output window – the “escape sequence” \n. \n, like other
escape sequences in C++, are considered single entities, even though we type them with
two keyboard characters. Escape sequences are always part of character strings. So, the
following snippets of code achieve the same result.
cout << "Hello" << endl << endl;
cout << "Welcome to Computer Science 20S";
cout << endl << endl;
cout << "Hello\n\n";
cout << "Welcome to Computer Science 20S\n\n";
both produce..
1 Intro to Computer Science
16
Displaying Special Characters
You may be wondering how you display certain characters, like a double quote (") or a
single backslash (\) – try that one; since the backslash is part of all escape sequences, you
can understand why the compiler might complain.
The following is a table which tells you what to type in order to get the desired output.
Symbol
Effect
\n
\"
\'
\a
\\
\t
go to new line
"
'
alert (make a beep sound)
\
tab (move to the next tab position)
Hand’s On Programming Example
Let’s see if we can write a program to using nothing but escape sequences (ie, no endls)
to generate the following output. Call the program 03 House.
/\
/
\
/
\
/
\
|
|
| -- |
|__||__|
Don’t forget to add all necessary comments to your program as indicated earlier in the
notes.
1 Intro to Computer Science
17
For sure there is a certain amount of trial and error. A solution, similar to the one
developed in class, is presented here.
/*
Project Name:
Programmed By:
Date:
03 House
Super Teach
7 Oct 2009
This program prints a house design
using nothing but escape sequences.
*/
#include <iostream>
using namespace std;
void main()
{
cout << "\n";
cout
cout
cout
cout
cout
cout
cout
<<
<<
<<
<<
<<
<<
<<
"
"
"
"
"
"
"
/\\\n";
\\\n";
/
\\\n";
/
\\\n";
|
|\n";
| -- |\n";
|__||__|\n";
/
cout << "\n\n";
system("pause");
}
You may now proceed to Assignment Set 1. This includes the following assignments:
04 Sailboat
05 Giant Letters
06 Shapes
1 Intro to Computer Science
18
1 Introduction to Programming
Lesson 4 – Math, too!
Of course we are not restricted to printing simple keyboard characters with C++. You
could predict that math is a big part of programming. Previously cout was used to
display the result of a calculation and control the location of output. The following line
prints a number.
cout << "10";
Now try the following:
cout << 10;
They seem to do the same thing. Is there any difference? Try the following:
cout << "10 + 10";
And now this:
cout << 10 + 10;
There obviously is a difference between "10" and 10. It seems the second is treated as a
number and in fact it is. The last line also illustrates you can print the results of a
calculation. This could come in handy. Let’s see if we can use this fact to do something a
little more useful. How about calculating the area of a circle with a radius of 10.
#include <iostream>
using namespace std;
void main()
{
cout << "\n
cout << "\n\n
cout <<
"\n
Call this program
07 Area of a Circle
Calculate the area of a circle";
Radius: " << 10;
Area: " << 3.14159 * 10 * 10;
cout << "\n\n\n ";
system("pause");
}
Modify the program to print the area of a circle with radius 50.
1 Intro to Computer Science
19
As you might expect C++ has operators for the common math functions (multiplication,
division, addition, subtraction) and a few more we’ll save for later.
1 Intro to Computer Science
20
1 Introduction to Programming
Lesson 5 – Variables
Variables and Basic Data Types
All computers manipulate data of different data types. Check out the following program:
#include <iostream>
Start this project as
08 Range of Values
We’ll modify it as we go..
using namespace std;
void main()
{
int
num;
double hours;
char
letter;
bool
doneYet;
//
//
//
//
an integer
a number that may have a decimal portion
a single alphanumeric character
a boolean - "true" or "false"
// code..
cout << "\n\n ";
system("pause");
}
These statements (which should always appear first in a function), are “declaring”
variables. Variables are exactly the same things you’re used to using in math class – you
know x, y, z. They represent an unknown or changing value. Same thing here. Just a few
differences. The identifier (name) can be multiple characters and hence can be more
meaningful (if chosen properly). We’ll talk about identifiers in a bit.
There are many data types available in C++ (and other high-level languages). These four
(int, double, char, and bool) will be sufficient for our purposes in CS20S. All will be
examined on an as needed basis.
Variable declarations tell the compiler to set aside a named memory location for use in
the body of the function in which they are declared. Note that although the variable is
declared, it has no value, so the following program..
continued..
1 Intro to Computer Science
21
#include <iostream>
using namespace std;
void main()
{
int num;
// an integer
cout << num;
cout << "\n\n ";
system("pause");
}
..will generate a run time error:
[Note that most, but not all high-level languages behave like this. Visual Basic is a
notable exception. In Visual Basic, declared variables all get a default value; numeric
types get the value zero by default, for example.]
Sometime before the variable is accessed it must acquire an appropriate value. This
would do..
int num;
num = 6;
// ..called an "assignment" statement
cout << num;
// now this will work
C++ also lets us assign a value in the variable declaration:
int num = 6;
cout << num;
// this works too
1 Intro to Computer Science
22
You might have noticed the use of the word “appropriate” above. It would be nonsense to
attempt the following:
int num = a;
// can you predict what might happen here?
Note that the statement
num = 6;
has nothing to do with equality. It’s called an assignment statement, as in “num is
assigned the value 6.” You could read it as “num equals 6”, but since we will be talking
about equality later, it might be better to say this in a different way, such as “num gets 6”.
We’ll talk much more about assignment statements in a few lessons.
Ranges of Values
Computers have limits on their abilities (yes, it’s true). As far as data types go, there is a
limit on the range of values that can be represented for each data type. Let’s see if we can
find the limit for an integer, for example (done experimentally in class).
#include <iostream>
#include <limits>
// required for DBL_MIN, DBL_MAX
using namespace std;
Modify 08 Range of Values
to now be this program.
void main()
{
int
num;
double hours;
char
letter;
bool
doneYet;
cout <<
cout <<
//
//
//
//
..an integer
a real number
a single alphanumeric character
a boolean - "true" or "false"
"\n
"\n
minimum integer:
maximum integer:
cout << "\n\n
unsigned integer max:
"
<< INT_MIN;
" << INT_MAX;
" << UINT_MAX;
cout << "\n\n minimum positive double:
cout <<
"\n maximum positive double:
cout << "\n\n minimum negative double:
cout <<
"\n maximum negative double:
// -2^31
// 2^31 - 1
" << DBL_MIN;
" << DBL_MAX;
"
"
<< -DBL_MIN;
<< -DBL_MAX;
cout << "\n\n ";
system("pause");
}
1 Intro to Computer Science
23
Identifiers
Identifiers are strings of alphanumeric characters used to identify variables in C++.
Variable names are identifiers, as are function names. Later on we will see many more
types of identifiers.
Identifiers are made up of letters (A-Z, a-z), numbers (0-9), and the underscore character
( _ ). They must begin with a letter or underscore character. Anything else will give you a
syntax error.
It is very important to remember that C++ is case sensitive. Therefore, the following two
identifiers would be considered different by the compiler.
int totalcount, TotalCount;
// this would not confuse the compiler
In order to make programs easier to read, for ourselves as well as for others, we will
adopt a naming convention for all identifiers. All variable names will be in lower case
letters, except for the first letter of all words after the leading word. This labeling scheme
is called interCaps.
Using this convention, some acceptable identifiers are:
quantity
stockNumber
maximumAge
timeOnTask
middleInitial
So, besides the identifiers above, see if you can identify which of the following identifiers
are legal and follow our naming convention, which are legal but don’t follow the naming
convention, and which are illegal (ie, the compiler would complain).
Identifier
_cheeseFood
not enough
dayNumber
x15y
hopelessName
%overDue
4by4
howMuch$
1 Intro to Computer Science
legal and
follows naming
convention
legal but doesn’t
follow naming
convention
X
illegal
X
X
X
X
X
X
X
24
A word of caution: We can’t declare a variable with the same identifier twice in the same
function. As well, some identifiers are illegal because they have special meaning in C++.
These include int, if, while, double, and many others.
Other names are legal though silly to use. For example, you could use cout, main, or
cin. However, these names have other meanings and if we redefine their meaning we
can’t use them in our program as they were originally intended. Finally,
thisIsaLoopCounter would be considered less desirable than loopCounter.
Literals and Constants
The following statement
cout << "I have " << 3 << "eggs.";
..contains three “literals” – fixed quantities. Two are strings, one is an integer. Here is a
program that contains some more literals:
#include <iostream>
Save as 09 Literals
using namespace std;
void main()
{
char ch1, ch2, ch3, ch4;
int num1 = 5, num2 = 2, num3;
ch1
ch2
ch3
ch4
=
=
=
=
'F';
'r';
'e';
'd';
// notice how chars are enclosed
num3 = num1 - num2 * 2;
cout << "\n
didn’t analyze output
until a few pages from
now..
// what do you notice this does?
" << ch1 << ch2 << ch3 << ch4 << " is #" << num3;
cout << "\n\n\n ";
system("pause");
}
There’s a new type of literal here – a char literal. Note they are enclosed in single
quotes and must be or an error will result.
Literals, as their description implies, cannot be modified:
'a' = 'c';
// ..does not make sense
1 Intro to Computer Science
25
We can make named constants..
const double TAX_RATE = .07,
PI = 3.14159265;
You should notice that we’ve extended our naming convention. Named constants will be
made with all capital lettters and and underscore between words: ALL_CAPS.
Once declared, named constants cannot be changed – kinda defeats the purpose of a
constant, so it would be logically silly to try anyway.
Can you think of any reasons why named constants would be a good idea? One good
reason is using number constants everywhere can be confusing. So while 3.14 might be
recognizeable, 9.8, 1.618, and 2.718 probably aren’t and shouldn’t be used as such in a
program. What might be better is
const double GRAVITY = 9.8,
GOLDEN_RATIO = 1.618,
E = 2.718;
// you'd be excused for using e here
These are scientific numbers that are fixed and so by definition should be constants.
Bottom line, GRAVITY will be more meaningful to the program reader than 9.8.
Numbers like
const double TAX_RATE = .07;
certainly might change at some point in the future and that brings us to the second reason
for using named constants. Imagine the number .07 were used in multiple occurrences in
a program and the tax rate changed (like the GST for example). Now you have to change
all those occurrences. And how can you be sure you got every occurrence? If you use a
named constant at the top of the program, you only have to change one number and
you’ll be sure everything works.
One final note, you cannot have an expression as a constant. A constant can not change in
the program. The following example:
const double SALARY = wage * hours;
is incorrect since a constant can not be dependent on anything.
Use of Variables
So what do variables do for us anyway? As we add to our knowledge of programming,
we extend our ability to solve more involved and interesting problems. There problems
we simply cannot solve without variables. This will become more apparent in coming
1 Intro to Computer Science
26
lessons. For now accept that variables form the foundation of every practical program
you write from now on. With them we can do all of our data processing. A few examples:
We can..
1. Assign values to them:
count = 4;
middleInitial = 'Q';
density = 3.46;
2. Use them in expressions:
simpleInterest = principal * rate * time;
celcius = 5/9 * (farenheit - 32);
voltage = current * resitance;
3. Print their values:
cout << "The calculated area is:
" << area;
So, can you now predict the output of the following program?
#include <iostream>
using namespace std;
void main()
{
char ch1, ch2, ch3, ch4;
int num1 = 5, num2 = 2, num3;
ch1
ch2
ch3
ch4
=
=
=
=
'F';
'r';
'e';
'd';
// notice how chars are enclosed
num3 = num1 - num2 * 2;
cout << "\n
// what do you notice this does?
" << ch1 << ch2 << ch3 << ch4 << " is #" << num3;
cout << "\n\n\n ";
system("pause");
}
1 Intro to Computer Science
27
Data Types and Coercion
C++ is a strongly typed language. This means that every variable is of a specific type,
int, double etc. Certain types can be converted to other types. These simple type
conversions are provided by the compiler. For example..
void main()
{
int
num1;
double num2;
num1 = 24.92;
num2 = x;
// num1 will be assigned 24
// num2 will be assigned 24.
cout << "\n\n\n ";
system("pause");
}
Although C++ will make an effort to coerce anything, it doesn’t always make sense and
is discouraged. Check out the following (on the next page):
1 Intro to Computer Science
28
#include <iostream>
Save as 10 Coercion
using namespace std;
void main()
{
int
num1;
double num2;
char
letter1, letter2;
bool
works1, works2, works3;
num1 = 'A';
num2 = 'a';
cout << num1 << "
" << num2;
// 65
" << num2;
// 1
97
..ascii at work
num1 = true;
num2 = false;
cout << num1 << "
0
internal rep of true & false
letter1 = 4;
letter2 = 14.5;
cout << letter1 << "
works1 = 4;
works2 = 5.67;
works3 = 't';
" << letter2;
// ♦
//
♫
goofy stuff;
not recommended
// all receive 1;
// apparently everything
// that isn't 0 is true
cout << works1 << "
" << works2 << "
" << works3;
cout << "\n\n\n ";
system("pause");
}
Obviously the compiler doesn’t warn you about potentially goofy coercions. Utlimately
you, the programmer, are responsible for your code. You are responsible for knowing
what value num1 receives in the following code:
int
num1;
double num2;
num1 = 24.92;
num2 = x;
We can convert (promote) a literal integer to a double by just adding a decimal..
cout << 4/3;
cout << 4/3.;
// 1
// 1.33333
Let’s see if this works with variables. Try the following..
1 Intro to Computer Science
29
int num1 = 4,
num2 = 3;
cout << num1/num2.;
The compiler doesn’t like that much, does it? Makes sense, really. Try the following:
int num1 = 4,
num2 = 3;
cout << double(num1)/num2;
// ..called "casting"
What we’ve done here is “cast” num1 to a double. In effect num1 has been changed to
a double, before the division is performed. Note num1 itself has not been permanently
changed into a double. To see this you can run the following program:
#include <iostream>
using namespace std;
void main()
{
int
num1 = 4;
double num2 = 3;
Save as 11 Casting
cout << "\n\n
" << double(num1) / num2;
cout << "\n\n
" << num1 / num2;
// proof casting is temporary
cout << "\n\n ";
system("pause");
}
Be carefull what you cast. The following output statements don’t produce the same
output. Do you see why?
int num1 = 4,
num2 = 3;
cout <<
double(num1/num2);
cout << endl << double(num1)/num2;
(end of Lesson 5 – no assignment yet)
1 Intro to Computer Science
30
1 Introduction to Programming
Lesson 6 – Data Storage
A variable in C++ is actually a named memory location for a variable of a specific data
type. When we declare a variable we are asking for a piece of memory from the operating
system. For integer (int) variables we ask for 32 bits (or 4 bytes or 1 word) of memory
space. Characters (char) are stored in 8 bits (1 byte) in ASCII. double represent real
numbers with 15 digits of accuracy. They require 8 bytes of storage.
It may be helpful for you to understand that the computer does not work with numbers
like we do. We work in base 10 (“decimal”) but the computer works in base 2
(“binary”). To illustrate this, study the following illustrations carefully.
We can represent numbers as powers of ten. Consider the number 45369. We could
represent it the following way:
4 x 104 +
40000 +
5 x 103 +
5000 +
3 x 102
300
+
+
6 x 101
60
+ 9 x 100
+
9
Binary (base 2) works the same way but instead of using 10 digits (0-9), binary only uses
2 digits (0 and 1). The following are some examples of binary numbers:
1001101
111010100
1101001001
And, to express the numbers as sums of powers, as we’ve done above with the decimal
number 45369, we would use 2 as the base rather that 10. So, let’s express the binary
number 1001101 as sums of powers and find out it’s decimal equivalent:
1 x 26
64
77
+
+
0 x 25 + 0 x 24
0
+
0
+
+
1 x 23
8
+
+
1 x 22
4
+
+
0 x 21
0
+
+
1 x 20
1
Try another one. See if you can convert the binary number 111111 to it’s decimal
equivalent. You should get 127.
Ok, so you’re good converting binary to decimal. How about decimal to binary? Here’s
the deal (next page)..
1 Intro to Computer Science
31
Suppose we want to convert the decimal number 81 to binary. Find the largest power of
two that fits into 81. This would be 64 (which happens to be 26). Place a 1 down to mark
this 6th position:
Then subtract 64 from 81: 81 – 64 = 17
1
Into the remainder the next power of 2 (25 or 32) doesn’t fit, so mark a 0 in the 5th
position:
10
The next power of 2 (24 or 16) does fit, so mark a 1 in the 4th position and subtract..
17 – 16 = 1
101
The next three powers of 2 (23, 22 and 21) all don’t fit, so mark a zero for their postions..
101000
20 does fit, so mark a 1 for it’s position
1010001
Subtracting now gives zero and we’re done.
So the decimal number 81 corresponds to the binary number 1010001.
At this point you may begin the Numbers Conversion Worksheet.
1 Intro to Computer Science
32
1 Introduction to Programming
Lesson 7 – Basic C++ Statements
C++ programs are made up of a series of statements. The statements are executed one
after another in sequence ..unless otherwise instructed – we’ll discover that later.
We have seen two types of statements so far: Assignment statements and output
statements.
Let’s quickly summarize the different types of assignment statements we’ve encountered
by looking at the following program:
#include <iostream>
#include <cmath>
// necessary for cout
// necessary for pow
using namespace std;
void main()
{
double radius,
square,
squareRoot,
num,
finalResult;
Save as 12 Basic Statements
num = 256;
radius = 6.258;
// assignment from a literal
// and again
square = num;
// ..from a variable
squareRoot = sqrt(square);
// ..from a function
finalResult = pow(radius, 2) * squareRoot - num;
cout
cout
cout
cout
<< "\n\n
radius:
<<
"\n
square:
<<
"\n square root:
<<
"\n
answer:
"
"
"
"
<<
<<
<<
<<
// ..from an
// expression
radius;
square;
squareRoot;
finalResult;
cout << "\n\n\n ";
system("pause");
}
and the output..
1 Intro to Computer Science
33
More Expressions in C++
C++ expressions are made up of constants, operators, and variables. The operators
allowed in an expression depend on the data types being used in the expression.
Arithmetic operations are performed on integers and doubles and the results are int
or double. Here’s a table of the numerical operators in C++:
Operator
+
*
/
%
++
--
Name
Example
unary minus
addition
subtraction
multiplication
division
modulus (“mod”)
increment
decrement
-num
num1 +
num1 –
num1 *
num1 /
num1 %
c++ or
c-- or
num2
num2
num2
num2
num2
++c
--c
We created a simple project
called “13 Math Operators”
to test some of the operators.
We have already seen how integer division works and we know to be mindful of the data
types of the operands and to cast them if necessary. There are a few operators on the list
you may not have encountered before. The first is the modulus (or just “mod”) operator.
It returns the remainder of the integer division of it’s operands. A few examples..
Operation
12 % 5
12 % 11
12. % 5
11 % 12
12 % 12
12 % 2
12 % 4
Result
2
1
error C2296: '%' : illegal, left operand has type 'double'
11
0
0
0
After studying the results you might recognize the usefulness of the mod operator. No? It
can be used to determine whether an integer divides evenly into another. We could get
the equivalent results by doing the following:
int quotient,
remainder;
quotient = 12 / 5;
remainder = 12 - quotient * 5;
1 Intro to Computer Science
34
Really, though no programmer in his or her right mind would go through the trouble if
mod (%) was available. Virtually all high-level programming languages have a mod
operator.
Two other new operators are the increment (++) and decrement (--) operators. They also
happen to have a part in the name of the programming language: C++.
Both increment operators (ie, the postincrement c++ version and the preincrement ++c
version) do the same thing, and that is to increment (“add to”, “bump up”, etc) the value
of the variable. They have the same effect as
c = c + 1;
Being seasoned programmers we know this is an assignment statement and not a
mathematically impossible equation. It’s effect is to increase the value of the variable c.
(Yes, we have used a single character name for a variable here. There’s a reason for that
we’ll get to in a bit.) In C++ the following two statements are functionally identical:
c++;
++c;
// used tons
// never used alone like this
So if they do the same thing what’s the difference between them?! They are the same, but
can’t be appreciated in the above situation (ie on their own). The difference is in the
timing. The c++ version increments c after the statement is executed, the ++c version
increments c before the statement is executed. Here’s an example:
int c = 4;
cout << endl << c++;
cout << endl << c;
cout << endl << endl << ++c;
cout << endl << c;
So why would we bother? Suffice it to say that you can’t appreciate the value of this just
yet. Just trust that it’s important and you definitely have to know what it means.
If you followed the above example,
you should be able to predict the output of the following program..
1 Intro to Computer Science
35
int c = 4;
cout << endl << c--;
cout << endl << c;
cout << endl << endl << --c;
cout << endl << c;
And here it is..
Mathematical Precedence in Expressions
As with expressions you’re used to in math class, C++ expressions are evaluated based
on BEDMAS (Brackets, Exponents, Division/Multiplication, Addition/Subtraction). If
we just make a few additions, we get a complete list of precedence. From highest to
lowest, then:
highest precedence →
↓
lowest precedence →
()
pow
* / %
+ -s
You may now proceed to the Expressions Worksheet.
1 Intro to Computer Science
36
1 Introduction to Programming
Lesson 8 – Basic Input
Computers often need input from a user (interactivity) or from a file while the program is
running. The way we do this is very much like the way we output data to the screen.
#include <iostream>
// necessary for cout ..and now cin
using namespace std;
void main()
{
int num1;
Save as 14 Basic Input
cout << "\n Enter an integer ->
cin >> num1;
cout << "\n\n
You entered:
";
// a "prompt"
// note the extraction operator (>>)
" << num1;
cout << "\n\n\n ";
system("pause");
}
When we get data, we are extracting it from the input stream and placing it in memory. It
may be helpful to think of the operators as pointing in the direction we want the data to
travel, the extraction operator >> points to the variables in which the data is to be stored,
while the insertion operator << points to cout – the output stream.
Note the prompt to the user. Every cin statement should be preceded by a cout
statement prompting the user exactly what should be entered, both type of data, and
quantity. We may want to enter more than one value.
int num1, num2, num3;
cout << "\n Enter three integers ->
cin >> num1 >> num2 >> num3;
";
Note that extraction operators precede input identifiers, not commas!
1 Intro to Computer Science
37
Upon running the program,
the user must separate input values with a space:
Input gives us much more power as programmers. Our programs become much more
flexible. So, instead of changing the code in our Area of a Circle program (from Lesson
4)..
#include <iostream>
using namespace std;
void main()
{
cout << "\n
cout << "\n\n
cout <<
"\n
Calculate the area of a circle";
must change these
quantities for every
new calculation
Radius: " << 10;
Area: " << 3.14159 * 10 * 10;
cout << "\n\n\n ";
system("pause");
}
..we can now ask the user exactly what they want without having to modify our program
(next page)..
1 Intro to Computer Science
38
#include <iostream>
using namespace std;
void main()
{
const double PI = 3.14159;
double radius;
cout << "\n
cout << "\n
This program determines the";
area of a circle.";
cout << "\n\n Enter the radius of the circle ->
cin >> radius;
cout << "\n
Area is:
";
" << PI * radius * radius;
cout << "\n\n\n ";
system("pause");
}
You may now procede to the second set of programming assignments. These include..
15 Temperature Conversion
16 Cutting the Grass
17 The Jogger
18 Seconds Conversion
1 Intro to Computer Science
39
Download