Reading: Deitel & Deitel, Chapters 1, 2
Thiw worksheet reviews some basic concepts
and describes how to use the compiler. There is no quiz associated with it.
The C++ Programming Language
The language to be used in this course is C++. C++ is currently the most widely used programming language for developing ``real world'' applications. It is an object-oriented superset of C, that is, it contains all of the features of C, and has additional features, many of which pertain to object oriented programming. This worksheet is written for a student who has either completed Computer Science I or has had a similar course which introduces elementary programming concepts. It is not assumed that you know C or C++, but it is assumed that you can learn the basic syntax of C++ quickly.
Two of the most widely used compilers for C++ are VC++ (Microsoft Visual C++) and g++ (GNU C++). Both compilers are available on Windows 95/98/NT platforms such as the NT workstations in our classroom, and g++ is also available on most Unix platforms. We will use the VC++ 6.0 in this course. It should be installed on your laptop and on workstations in the classroom.
Basic instructions for using VC++ and Developer Studio are included in Exercise 1 below.
A C or C++ program consist of one or more functions. One and only one of these functions must be called main. Here is a short C++ program.
// A program to compute the average of five grades
#include <iostream>
using namespace std;
int main()
{
int grade, sum, n, average;
n = 0;
sum = 0;
while (n < 5) {
cout << "Enter a grade" << endl;
cin >> grade;
sum = sum + grade;
n++;
}
average = sum / 5;
cout << "The average is " << average << endl;
return 0;
}
Let's go through it line by line to understand it.
// A program to compute the average of five grades
This is a comment. Anything after the double slashes (//) on the same
line is a comment and is ignored by the compiler. C++ programs
can also use C style comments, enclosed between /* and
*/. Here is an example:
/* This is a comment which
extends over two lines*/
#include <iostream>
This is an include statement. Include statements copy additional
material into your program. These can either be standard files
such as iostream, which includes code for reading data into
your program from the keyboard and writing data to your terminal, or
files that you write yourself. In the former case, the name of the
include file is enclosed between < and > as is the
case in this example. Include files that you write yourself and which
are in the same directory are included in double quotes. For example
#include "myfile.h"
You should include iostream in all C++ programs.
using namespace std;
This statement tells the compiler to use the standard namespace.
Include this statement in all of your programs. Note that the
text uses the following statements instead of this.
using std::cout;
using std::cin;
using std::endl;
You may use the text syntax if you prefer.
int main()
This is a function declaration statement. It declares a function called main which returns a value of type int. The function name is followed by the argument list in parentheses. Since main takes no arguments in this example, the parentheses are empty. Some programmers use the keyword void when there are no arguments, i.e., int main(void).
{
The curly brace signifies the beginning of a block, which
contains a sequence of statements. Each open curly
brace must be matched by a close curly brace }, which
ends the block. A function always
contains a block delimited by { and }.
int grade, sum, n, average;
This is a variable declaration statement. As in other languages, C and C++ support a number of standard data types including integers, declared with the keyword int, real numbers, declared with the keyword double, and characters, declared with the keyword char. This statement declares four integer variables, called grade, sum, n, and average. All statements in C and C++, including variable declarations, must end with a semicolon.
In C, all variables to be used in a block must be declared prior to any executable statements, as is done here. In C++, new variables can be declared at any point in the block prior to or at their first use.
n = 0;
sum = 0;
These are assignment statements; they assign values to variables.
The format of the assignment statement is a variable name followed by
the = followed by an arithmetic expression.
Alert: In C and C++, you cannot assume that a variable has
any particular value until it has been assigned a value. A common error
is using a variable before it has been initialized. This can
result in bugs in your program that are hard to detect.
while (n < 5) {
The while statement is used for repetition of a group of
statements (the computer science term for this is iteration).
This is followed by an expression in parentheses which can evaluate to
either zero (false) or non-zero (true). This is then followed by
either a single statement or a block delimited by curly braces.
During execution, the program will continue to execute the block or
statement until the expression evaluates to false. Note that if
the expression is initially false, the statement or block will not
be executed. Thus this statement will continue to loop through
the block as long as the value of the variable n is less than
5. The computer science term for the process of repeatedly
looping through a statement or block of statements is iteration.
The { at the end of the line
signifies the start of the block controlled by the while
statement.
cout << "Enter a grade" << endl;
This is an output statement, sometimes called a cout statement.
cout is actually the name of an output stream (of
characters) that normally appears on your workstation screen as it is
generated. The << operator causes data to be sent that stream,
so that you see it on the screen. In this case, what is displayed is
the character string Enter a grade contained within the double
quotes. The second << operator causes the endl value,
which is a ``newline'' character (sometimes called a carriage return)
to be output; in other words, it moves the output cursor to the start
of a new line.
cin >> grade;
Similarly, this is an input statement, sometimes called a cin
statement. cin is actually the name of an input stream
(of characters) of that normally is generated by typing on your
workstation's keyboard. The >> operator takes data from the
stream and interprets as a value to assign to the following
variable, in this case grades. Since grades is of type
int, the user is expected to type digits which are interpreted
as a decimal number and assigned to grade. This statement halts
the running of the program until the user enters something, and then
hits the Enter key.
sum = sum + grade;
This statement adds the value of grade to the value of sum and stores the value in sum.
n++;
The ++ operator in C and C++ is the increment operator; it
increments its operand by 1.
}
This ends the block controlled by the while statement. The statements in this block will be executed repeatedly until the condition after the word while evaluates to false.
average = sum / 5;
This statement divides the value of sum by 5 and stores the result in average. Since integers cannot have fractional values, the result must be a whole number. Integer division truncates. For example, if the value of sum was 29, the value of the division operation would be 5.
cout << "The average is " << average << endl;
This statement displays the character string The average is on the screen, followed by the value of average.
return 0;
The return statement in a function causes control to return to the calling function, and if the function returns an argument, this will specify the value to be returned. A return statement in the function main() causes the program to terminate. The value returned from main ordinarily does not matter, but typically 0 signifies successful completion.
}
This terminates the function main.
Compiling a C++ program with VC++
VC++, the Microsoft Visual C++ compiler, has an Integrated Development Environment (IDE) called Microsoft Developer Studio, which allows you to edit, compile, link, execute, and debug programs in an integrated fashion. In the following exercises we go through the basics of using the Visual C++ IDE. The first exercise is to type in, compile, and run the grades program.
Exercise 1: Compile and run the program grades.cpp.
To do this, go through the following steps:
From the File Menu choose New. (You should get used to
using the shortcut keys instead of the menus. You can get to the same
place by hitting Cntl-n.) A Window entitled New will pop
up. Choose the Projects Tab. Select Win32 Console
Application. Enter a name for your project, where it says Project Name (grades for example). In the Location window,
enter c:\temp. Then hit the OK button. A window will
pop up asking what kind of Console Application you want to create.
Choose An empty project and push the Finish button.
Compiling... grades.cpp Linking... grades.exe - 0 error(s), 0 warning(s)It is likely that you will have made some errors in typing in the program and so you will not get a clean compile. A list of error or warning messages will appear in the output window. Here is a typical error message.
Compiling...
grades.cpp
C:\cs2\grades\grades.cpp(15) : error C2146: syntax error :
missing ';' before identifier 'cin'
Error executing cl.exe.
grades.exe - 1 error(s), 0 warning(s)
The message refers to line 15, but you don't have to count lines in
the source file to find that position. If you place the mouse pointer
on any error message and double-click the left mouse button, Developer
Studio will point out the line in the edit window the message refers
to by placing a cursor on it and an arrow beside it in the margin.
(Or, use the shortcut key F4, which takes you source line
where the first error was found. Each time you hit the F4 key,
the next error message will be displayed and that line will be
pointed out in the source file.)
Using the Editor
There are a large number of editing commands, but you can do most of what you need to do using only a handful. You can perform most of these by selecting from the Edit menu, but you can work faster if you use the following shortcut keys.
| Action | Key Binding |
| Delete the current line | Cntl-Shift-L |
| Undo the previous action | Cntl-z |
| Insert a file as text | Alt-i, f |
| Copy selected text to the clipboard* | Cntl-c |
| Delete selected text, putting it in the clipboard | Cntl-x |
| Paste contents of the clipboard to the file | Cntl-v |
| Find a word in the file | Cntl-f |
| To look for the next instance of the same word | F3 |
| To match a curly brace or paren. | Cntr-] |
| To indent your code properly | Cntl-A (select all) then Alt-F8 |
*The clipboard is a temporary storage area in the operating system. It allows you to copy text easily from one application to another or from one place to another within an application. You select text by placing the pointer over the start of the text that you want to select, pressing the left mouse button, and then dragging the pointer over the text that you want to select. The selected text will be highlighted.
Other C++ Control Statements
Normally the statements in a program are executed sequentially, but this can be modified with a control structure. The sample program used one type of control structure, the while statement. The structure of the while statement is as follows:
while (expression)
statement or block
The expression is evaluated, and if it evaluates to anything other than zero or to true, the statement or block is executed. This continues until the expression evaluates to zero or false, in which case the program skips the block or statement and goes on the the following statement.
Alert: A common mistake is to put a semicolon after the
close parenthesis. This is syntactically correct, but it means
that there are no statements to execute so the result is usually
an infinite loop. The following statement would run forever because
of the extra semicolon at the end of the while line.
n = 0;
while (n < 5);
{
cin >> x ;
sum = sum + x;
n++;
}
If you think your program is in an infinite loop, you can stop execution by hitting Cntl-c.
Any expression can be enclosed in the parentheses following the
while, but typically
the expression is one involving one of the comparison operators.
Here are the comparison operators in C and C++.
> |
greater than |
< |
less than |
== |
equal to |
>= |
greater than or equal to |
<= |
less than or equal to |
!= |
not equal to |
You can test multiple conditions using the logical and operator
&& or the logical or operator ||. Here are two examples:
while (x < 17 || y == 3) {
while (a > 3 && b != 0) {
The first statement means while x is less than 17 or y is equal to 3 .... The second statement means while a is greater than 3 and b is not equal to zero ....
Alert: Notice that the is equal to operator is ==.
If you use the = (the assignment operator) instead, your
program will probably compile without errors, and will run, but will
not do what you expect it to do. (Some compilers will produce a
warning message, but VC++ is unfortunately not one of them.)
There are two forms of the if statement.
Form 1:
if ( expression )
statement or block
Form 2:
if ( expression )
statement or block
else
statement or block
The third control structure is a for statement. The for
statement initializes one or more variables, sets a condition as in
the while statement, and has an automatic updating expression. These
three expressions are separated by semicolons within the parentheses
after the keyword for. Here is the syntax:
for (expression1;expression2;expression3)
statement or block
expression1 is the initializing expression; it is executed once, before anything else. expression2 is the test expression; the loop continues as long as this condition is true; expression3 is the updating expression; it is executed after each pass through the loop.
This is exactly equivalent to:
expression1;
while (expression2) {
statement or block
expression3;
}
Here is an example
for (i = 0; i < 5; ++i)
cout << i << " squared is " << i * i << endl;
Exercise 2: Modify the grades.cpp program so that instead of being limited to five grades, it first prompts the user to enter the number of grades, and then it asks the user to enter that many grades. Compile and run your new program.
Exercise 3: Write a complete C++ program that computes various
powers of an integer. Your program should first prompt the user for
the integer to be raised to various powers, and then it should prompt
the user to enter the maximum power. You should not use the
pow function; you should use a loop that does multiplication.
Here is a sample run, in which the user enters 2 at the first prompt
and 6 at the second prompt, and then displays the powers from 2
ranging from
through
.
Please enter an integer: 2 Please enter the maximum power: 6 2 to the 1 is 2 2 to the 2 is 4 2 to the 3 is 8 2 to the 4 is 16 2 to the 5 is 32 2 to the 6 is 64