// This program calculates the area of a rectangle. // By Frank McCown #include <iostream> using namespace std; int main() { int width; int height; int area; cout << "Width? "; cin >> width; cout << "Height? "; cin >> height; area = width * height; cout << "Area is " << area; return 0; }
//
or surrounded by /* */
// This is a single line comment. /* This is a multi-line comment. */
//
is ignored by the compiler
int x; // This comment is ignored by the compiler
#include <library-name>
iostream
is a library that sends output to
the console (cout
) and reads input from the keyboard via
the console (cin
)
using
statement is necessary, but don't worry about
what it's used for now
int main()
is the beginning of the executable statements
{
and }
to surround statements
return 0;
at the end says the program finished successfully
int
means that the variable may hold integers (no decimal place),
like 2 and -10
width, height, area
are the three variables used in the program
w
,
h
and a
,
but using complete words makes our programs easier to understand and is
preferred by most programmers
using
or int
int test5_0; // OK int test50%; // WRONG (% is not a legal char) int test 50; // WRONG (space is not legal)
int test_2; // OK int _2test; // OK int 2_test; // WRONG (starts with digit)
width
and Width
are not the same variable!
<<
to send
string literals like
"Hello!"
and the value of variables to the console
cout << "height is " << height;
/* Outputs: Hello there! */ cout << "Hello" << endl << "there!";
>>
with a variable to read a
number from the keyboard into the variable
// Read a number into x cin >> x; // Read in three numbers cin >> x >> y >> z;
=
final = 80.0;
=
80.0 = final; // Syntax error!
// Calculate the average of the final and midterm aveGrade = (final + midterm) / 2; // Wrong since since / is done first! aveGrade = final + midterm / 2;