Homework

Here

The structure of a simple C++ program

The example below shows the structure of a very simple C++ program along the lines of our "Hello World" example from the lab. It's annotated to describe the different parts of the program.

#include <iostream>

using namespace std;

int main() {
  cout << "The answer is ";
  cout << 7*6;
  cout << endl;


  return 0;
}
← this "includes" code needed to use the "standard library" iostream.  Libraries are repositories of 
  compiled C++ code that we can make use of in our own programs. iostream provides input/output functionality.
← This allows us to use shorter names for standard library  objects.  For  example, without this line we 
  have to  write "std::cout" rather than simply "cout".  The line is saying "just assume the 'std::' part".
← The "main" function.  For now, all our C++ code goes in between these { }'s.

← "cout << x" is how we write output.
  The left-hand side can be almost any expression.  "std::cout" is the full name of the output stream
  associated with the terminal. "cout << endl" sends a newline  to the output stream.

← A program actually returns a number to the command shell that launched it.  Returning 0 is like saying "this program exited normally".

In the early part of the course, the C++ statements that comprise your program are listed between the { }'s in the body of the "main function". Just as with Javascript, these statements are executed one after the other from top to bottom. Objects, whether numbers or strings (sequences of characters) can be printed to "standard out" using the syntax "cout << x". For short, you can print several things out in a single "cout" statement by separating them with "<<", like this:

cout << "I am " << 44*12 + 3 << " months old!" << endl

... and the "endl", as mentioned above, produces a newline.

Variables

Suppose I want to compute something like (3.55 - 17.017)^3. I can do this with C++, but "^" doesn't mean exponentiation in C++, so instead I need to write:

cout << (3.55 - 17.017)*(3.55 - 17.017)*(3.55 - 17.017) << endl;

This is a bit of a hassle. Normally we would think of first computing (3.55 - 17.017), then taking the resulting value and cubing it. Hopefully we think something like: "let x be (3.55 - 17.017) and compute x*x*x." We need a variable in which to store the value (3.55 - 17.017)!

So we try creating the following program:
#include <iostream>
using namespace std;

int main() {
  x = 3.55 - 17.017;
  cout <<  x*x*x << endl;
  return 0;
}

When we compile this, we get an error message like

  error line 4: 'x' is an undeclared identifier
    

What the compiler is saying is this: "x??? you never told me there was going to be an x!" If you want to use x to store the value (3.55 - 17.017), you need to first tell the compiler that the name x is going to stand for a number - this is called declaring the variable x.

The statement double x; declares that x is a variable of type double, which means that it's a variable that can stand for numbers with decimal points. The type of a variable tells you what kind of data objects, such as an integer or real number or something else ..., can be stored in the variable. There are many different types in C++, and in fact understanding types is one of the most important skills you'll learn in this course.

The = operator assigns a value to the variable x.

To make the program work, we write:
#include <iostream>
using namespace std;

int main() {
  double x;                         //declare x as a variable to store doubles
  x = 3.55 - 17.017;                //assign x the value 3.55 - 17.017
  cout <<  x*x*x << endl; //print out x^3
  return 0;
}

Once x has been declared as a variable of type double, it can be used in the program just like a normal number, either to print or to use in arithmetic expressions, like cout << x*x*x << endl, which does both.

What really goes on here is that space in your computer's memory is allocated for one object of type double, and given the name x. When you ask for the value of x (by involving it in an arithmetic expression or by trying to print it) the computer fetches a copy of the value from memory. When you use the = operator, the computer takes the value on the right hand side, and copies it into the space reserved for x.

Thus, strange sequences like:

double x;
x = 3.5;
x = 2.4;
    

... make perfect sense. After the statement double x;, space is reserved for x, though we have no idea what actual value is in there - at this point x is uninitialized. The statement x = 3.5; copies the value 3.5 into the space reserved for x. Finally, the statement x = 2.4; copies the value 2.4 into the space reserved for x, thus overwriting the 3.5 that had been there previously. Think of x as being the name of a box into which double values can be written.

ISSUE: Good variable names!

User Input

We've already seen how to output information from a program using cout. In C++ (and in many other places) we refer to an output stream, the idea being that each thing we write goes out sequentially in the order we write it. In exactly the same way, we read from an input stream. Not surprisingly (given that our output stream is cout) our input stream object is called cin. [Note: Really it's called std::cin, but if we use using namespace std; we may drop the std:: part. (We usually put the line using namespace std; after the #include's.) It's defined in the iostream library, just like cout.]

Code
double x, y;
cin >> x >> y;
User Types
12.0 
25.0 
Effect x gets the value 12.0, y gets the value 25.0.

You may only read into variables, so cin >> 1.5 will cause a compiler error. (And what would it mean????) When reading into double x, cin skips any spaces, tab's, or newlines until it comes across a number. So, for example:

Code
double x, y, z;
cin >> x >> y >> z;
User Types
12.0  25.0 
7.1 
Effect x gets the value 12.0, y gets the value 25.0, and z gets the value 7.1

Putting this together, we can construct a very simple program Addition Calculator, which reads in two numbers from the user and adds them together. Notice that the variable that contains the sum of the two numbers input by the user is actually called sum. This is just to enhance the readability of my code. I could've called the variable "George" and it would've worked just the same.

What can we do with doubles?

Very few of the mathematical operations we typically use with real numbers are part of the core C++ language. In fact, the only operations you'd recognize from math class are +, -, *, and /. Operations like exponentiation, square roots, logs, and so on are not part of the core language, but they are available to you in libraries. Libraries extend the functionality of C++. There is a set of standard libraries that are an official part of the language (Here is some online documentation on the standard libraries.), and the iostream library we've been using is one example. There is a library called cmath that allows you to perform other operations on doubles, like square roots and sines and logarithms. (Here is some online documentation on cmath.)

Legal Variable Names

Can you use any word or letter to represent a variable name? The answer is NO. A variable name must begin with a letter (lowercase or uppercase) or an underscore ( _ ). It may be any length you want (although anything after the first 32 characters will be ignored) but it can only contain letters, digits, and the underscore. Except in special situations, the use of the underscore to begin a variable name should be avoided. There are a special class of names called keywords, which are reserved for use by C++, and you may not use one of them to name a variable. Examples of keywords are double, int, and return. (A complete list can be found here.) There are also names that you could choose for variables, but which are already used for important things. Examples of this are main, cin and cout. The problem with using such a name, is that it creates ambiguity. For example, what would happen with the following:

double cin;
cin >> cin;

As it turns out, the compiler will assume that both cin's refer to your new double and you won't be able to use cin for reading. As we proceed, it will (hopefully!) become obvious what cannot be used as variable names.

C++ distinguished between uppercase and lowercase. As a result, Answer and answer will be considered different variable names. A very common mistake that beginning programmers make is to be sloppy in writing variable names, sometimes using capitals and sometimes not. It is not good programming practice to use two variables names that are spelled the same except for capitalization because it leads to errors. Your source code will be easier for mere mortals to understand (interpret this to mean the instructor grading your programs) if you use meaningful variables names.

Now we'll look at several other types, and as the course progresses we'll look at more and more, culminating with us defining new types of our own. I cannot stress this enough the idea of type is key to programming, regardless of the language. As we discuss these types, we'll also go over some of the operations defined for those types. This list is not exhaustive.

double (and float)

We've seen doubles quite a bit already. We use double to simulate computing with real numbers (i.e. anything that can be represented on a number line). I say "simulate", because most numbers can only be approximated by a double, analogous to the way we approximate 1/3 as the 6-digit decimal 0.333333. We'd need an infinite number of digits to get 1/3 exactly, and, well, we don't have an infinite number of bits in our computer. So, double gives us a bunch, and we make do. The issue of how to get good and reliable answers when we can only approximate such numbers is the concern of numerical analysis, which is an important field on the border between mathematics and computer science. The float type is a less accurate (fewer bytes) version of double.

operation(s)Comments
+,-,*,/all more or less work as you'd expect
cmathUse cmath for other typical mathematical operations. Remember #include <cmath>, and remember that all these operations are in the std namespace (meaning they need to be preceded by std:: or you need to have the line using namespace std; at the top). Here is some online documentation on cmath.

int

The int stands for integers. This type is the real workhorse of computing. As with integers, there are no fractions, but unlike integers there are limits on both the positive and negative ends (in the billions on a typical PC today). If you use a number like 65 in your program, it is interpreted as an int. If you used 65.0, on the other hand, it would be a double. (Numbers hard-coded into a program like this are called literals.)

operation(s)Comments
+,-,*all more or less work as you'd expect
/Division is tricky, since fractions aren't involved. Any fractional part leftover after division is simply chopped off (truncated). This leads to some odd "identities". For example, if x is the int 5, and y is the int 2, then x/y is 2! The most infamous version of this is that cout << 1/2 prints out 0. This will trick you at some point or another, I promise.
% This is the "modulus" operator. a % b returns the remainder when a is divided by b. So, for example, 5 % 3 is 2. The signs of numbers simply change the sign of the result, according to the same rules as we have for multiplication. The % operator is surprisingly important. Please look at the Minutes and Seconds program to see an example of why!

char

The char stands for character. These are letters or numbers, or stranger things ... for example there is a "bell character". Writing it causes your computer to beep! char literals are written inside single quotes, so for example the char a is written inside a program as 'a'. Unusual "characters", like tabs or newlines, use "escape codes". They are identified by a backslash. Tab is '\t', and newline is '\n'. Operations on chars will be more important later on.

bool

Characters and integers and (approximations of) real numbers are objects that you probably expect to want to compute with. Boolean values are perhaps not as obvious to you. A boolean value is either true or false, yes or no, one or zero. These are critical to computing because, as we'll soon discuss, much of programming comes down to decision making, and true/false - yes/no - 1/0 boolean values are our decisions. We'll discuss Boolean Logic in more detail later, but here are the basic operations.

operation(s)Comments
&&The AND operator. For bool's a and b, a && b is true if both are true and false otherwise.
||The OR operator. For bool's a and b, a || b is false if both are false and true otherwise.
!The NOT operator. For bool a, !a is false if a is true and true if a is false.
The words true and false can be used in your programs for boolean literal values.

Problems

Here is a list of problems and solutions. With even the very basic construction of input, output, variables, and expressions, we can write some useful programs.