HerbSchildt.com

 

Getting Started With

C++

By

Herbert Schildt

 

C++ is the language of choice for the development of high-performance software. Invented by Bjarne Stroustrup in 1979, at Bell Laboratories in Murray Hill, New Jersey, the language was originally called "C with Classes." In 1983 the name was changed to C++. Stroustrup built C++ on the foundation of the C language, adding features that supported object-oriented programming (OOP). The creation of C++ had a profound effect on modern programming. Its syntax became the standard for professional programming languages, and its design philosophy still reverberates throughout computing. For example, both Java and C# are derived from C++. If the development of high-performance, system-level code is in your future, then C++ is the right language to learn.

The purpose of this article is to help you take your first steps toward becoming a C++ programmer. Here you will learn how to

create, compile, and run a C++ program
use a variable
input from the keyboard
employ the if statement
apply the for loop
create a block of code.

Keep in mind that C++ is a large, powerful, professional programming language. The information presented here is only a starting point.

Note: Before you can compile and run C++ programs, you must have a C++ compiler installed on your computer. There are several to choose from, including Visual C++ and Borland C++. In general, any modern C++ compiler will work. Just make sure that it complies with the ANSI/ISO standard for C++.

 

Create, Compile, and Run Your First C++ Program

The first step to learning to program in C++ is to understand how to compile and run a C++ program. The one we will begin with is shown here.

/*
  This is a simple C++ program.

  Call this file Example.cpp.
*/

#include <iostream>
using namespace std;

// A C++ program begins at main().
int main()
{
  cout << "C++ is power programming.";

  return 0;
}

Here is the sequence you will follow.

  1. Enter the program.
  2. Compile the program.
  3. Run the program.

 

Enter the Program

When you write a program, you create a file that contains the program's source code. Source code is the human-readable form of a program. Thus, you must begin by creating a file that holds the source code to the program just shown.

To enter the program, you must use a text editor, not a word processor. Word processors typically store format information along with text. This format information will confuse the C++ compiler. If you are using Windows you can use WordPad to enter the program. Just be sure to save it as a text file.

The name of the file that holds the source code for a C++ program is technically arbitrary. However, C++ programs are normally contained in files that use the extension .cpp. Thus, you can call a C++ program file by any name, but it should use the .cpp extension. For this first example, name the source file Example.cpp so that you can follow along with the instructions for compiling and running the program.

 

Compile the Program

How you will compile Example.cpp depends upon your compiler and what options you are using. Therefore, it is not possible to give generalized instructions that will work for all environments. Instead, instructions for compiling when using Microsoft's Visual C++ are shown. Visual C++ was chosen because it is one of the most widely used compilers. If you are using a different compiler, you must consult the documentation supplied with your compiler.

Visual C++ provides two different ways of compiling a program: the command-line compiler and the Integrated Development Environment (IDE). Although the IDE is excellent for developing real world applications, the command-line compiler is much easier to use when compiling short, sample programs such as those shown in this article. Therefore, it is the method described here.

To use the Visual C++ command-line compiler, you must first execute the batch file VCVARS32.BAT, which is provided by Visual C++. When using Visual C++ .NET, you can start a command-prompt session already configured for Visual C++ by choosing Visual Studio .NET Command Prompt from the list of tools shown under the Visual Studio .NET entry in the Start | Programs menu of the task bar.

If you are using Visual C++ 2005 (or later) to compile Example.cpp, then use this command line:

cl -EHsc Example.cpp

The –EHsc option is required for modern-style C++ code.

If you are using an earlier version of Visual C++, then use the –GX option instead, as shown here.

cl -GX Example.cpp

The output from a C++ compiler is executable object code. For a Windows environment, the executable file will use the same name as the source file, but have the .exe extension. Thus, the executable version of Example.cpp will be in Example.exe.

 

Run the Program

After a C++ program has been compiled, it is ready to be run. Simply enter its name at the command prompt. For example, to run Example.exe, use this command line:

Example

When run, the program displays the following output:

C++ is power programming.

One other point: The programs in this article are console based. This means that they are not windowed applications that use a graphical user interface (GUI). Thus, they run in a Command Prompt session. C++ is fully capable of creating GUI-based applications, such as Windows programs. Indeed, it is one of the most commonly used languages for Windows development. However, console-based programs are much shorter and are the type of programs normally used to teach programming. Once you have mastered C++, you will be able to apply your knowledge to GUI-based programming with no trouble.

 

The First Sample Program Line-by-Line

Although Example.cpp is quite short, it includes several key features that are common to all C++ programs. Let’s closely examine each part of the program.

The program begins with the lines

/*
  This is a simple C++ program.

  Call this file Example.cpp.
*/

This is a comment. Like most other programming languages, C++ lets you enter a remark into a program’s source code. The contents of a comment are ignored by the compiler. The purpose of a comment is to describe or explain the operation of a program to anyone reading its source code. In this case, the comment describes the program and suggests that you call the source file Example.cpp. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does.

In C++, there are two types of comments: multiline and single-line. The one you’ve just seen is a multiline comment. This type of comment begins with a /* (a slash followed by an asterisk). It ends only when a */ is encountered. Anything between these two comment symbols is completely ignored by the compiler. Multiline comments can be one or more lines long. The single-line comment is found a little further on in the program and will be discussed shortly.

The next line of code is:

#include <iostream>

The C++ language defines several headers that contain information that is either necessary or useful to your program. This program requires the header <iostream>, which supports the C++ I/O system. This header is provided with your compiler. A header is included in your program using the #include directive.

The next line in the program is

using namespace std;

This tells the compiler to use the std namespace. A namespace creates a declarative region in which various program elements can be placed. Elements declared in one namespace are separate from elements declared in another. Namespaces help in the organization of large programs. The using statement informs the compiler that you want to use the std namespace. This is the namespace in which the entire C++ library is declared. By using the std namespace, you simplify access to the standard library.

The next line of code is

// A C++ program begins at main().

This line shows the second type of comment available in C++: the single-line comment. Single-line comments begin with // and stop at the end of the line. Typically, C++ programmers use multiline comments when writing larger, more detailed commentaries, and single-line comments when short remarks are needed. This is, of course, a matter of personal style.

The next line is where program execution begins.

int main()

All C++ programs are composed of one or more functions. A function is a subroutine. Every C++ function must have a name, and the only function that any C++ program must include is called main( ). The main( ) function is where program execution begins. The opening curly brace { on the line that follows main( ) marks the start of the main( ) function code. The int that precedes main( ) specifies the type of data returned by main( ). C++ supports several built-in data types, and int is one of them. It stands for integer.

The next line in the program is

cout << "C++ is power programming.";

This is a console output statement. It causes the message C++ is power programming. to be displayed on the screen. It accomplishes this by using the output operator <<. The << operator causes whatever expression is on its right side to be output to the stream specified on its left side. (A stream is a source or target for I/O.) In this case, the stream is specified by cout, which is a predefined identifier that stands for console output. It is linked to a stream that (by default) refers to the computer’s screen. Thus, this statement causes the message to be output to the screen. Notice that this statement ends with a semicolon. In general, all C++ statements end with a semicolon.

The message "C++ is power programming." is a string. In C++, a string is a sequence of characters enclosed between double quotes.

The next line in the program is

return 0;

This line terminates main( ) and causes it to return the value 0 to the calling process (which is typically the operating system). For most operating systems, a return value of 0 signifies that the program is terminating normally. Other values indicate that the program is terminating because of some error. return is one of C++’s keywords, and it is used to return a value from a function. All of your programs should return 0 when they terminate successfully (that is, without error).

The closing curly brace } at the end of the program formally concludes the program.

One last point: C++ is case sensitive. Forgetting this can cause you problems. For example, if you accidentally type Main instead of main, or couT instead of cout, the preceding program will be incorrect. Furthermore, if you misspell main, the compiler will still compile your program. However, you will see an error message when you try to run it.

 

Using a Variable

Perhaps no other construct is as fundamental to programming as the variable. A variable is a named memory location that can be assigned a value. Further, the value of a variable can be changed during the execution of a program. That is, the content of a variable is changeable, not fixed.

The following program uses two variables called x and y.

// This program demonstrates variables.

#include <iostream>
using namespace std;

int main()
{
  int x; // this declares a variable called x
  int y; // this declares a variable called y

  x = 10; // this assigns 10 to x

  cout << "x contains " << x;

  cout << "\n"; // advance to next line

  y = x + 2; // this assigns to y the value of x + 2

  cout << "y contains " << y << "\n";

  return 0;
}

As mentioned earlier, the names of C++ programs are arbitrary. Thus, when you enter this program, select a filename to your liking. For example, you could give this program the name VarDemo.cpp. When you run this program, you will see the following output:

x contains 10
y contains 12

This program introduces several new concepts. First, the statement

int x; // this declares a variable called x

declares a variable called x of type integer. In C++, all variables must be declared before they are used. Further, the kind of values that the variable can hold must also be specified. This is called the type of the variable. In this case, x can hold integer values. These are whole number values. In C++, to declare a variable to be of type integer, precede its name with the keyword int. Thus, the preceding statement declares a variable called x of type int.

The next line declares a second variable called y.

int y; // this declares a variable called y

Notice that its uses the same format as the first except that the name of the variable is different.

In general, to declare a variable you will use a statement like this:

type var-name;

Here, type specifies the type of variable being declared, and var-name is the name of the variable. In addition to int, C++ supports several other data types, such as double, float, long, short, and char.

In C++, variable names (and other programmer-defined names) are called identifiers. Identifiers may start with any letter of the alphabet or an underscore. Next may be either a letter, a digit, or an underscore. The underscore can be used to enhance the readability of a variable name, as in line_count. Uppercase and lowercase are different; that is, myvar and MyVar are separate names. Here are some examples of acceptable identifiers:

Test

x

y2

MaxLoad

simpleInterest

_top

my_var

sample23

Remember, you can't start an identifier with a digit. Thus, 12x is invalid, for example.

The next line in the program, shown here, assigns x the value 10.

x = 10; // this assigns 10 to x

In C++, the assignment operator is the single equal sign. It copies the value on its right side into the variable on its left.

The next line of code outputs the value of x preceded by the string "x contains ".

cout << "x contains " << x;

Notice that this line uses two output operators within the same cout statement. It outputs the string "x contains " followed by the value of x. This concept can be generalized. Using the << output operator, you can chain together as many output operations as you like within one cout statement. Just use a separate << for each item.

The next line advances the output to the next line.

cout << "\n"; // advance to next line

The \n is an escape sequence that stands for a newline (that is, a carriage-return/linefeed sequence). When a string is output, each \n embedded in the string causes output to advance one line. Thus, this string "\n\n" advances output by two lines.

The next line of code assigns y the value of x plus 2.

y = x + 2;

After the line executes, y will contain the value 12. The value of x is unchanged and is still 10. As you would expect, C++ supports a full range of arithmetic operators, including those shown here.

 

Operator

Meaning

+

Addition

Subtraction

*

Multiplication

/

Division

%

Modulus

Here is the last line in the program:

cout << "y contains " << y << "\n";

It displays the string "y contains " followed by the value of y, which is 12, followed by a newline. Thus, it uses three output operators in a single statement.

 

Read Input from the Keyboard

In C++, it is easy to obtain data from the keyboard: simply read from cin using the >> input operator. Here is the general form

cin >> var;

Similar to cout, cin is another predefined identifier. It stands for console input and is automatically supplied by C++. By default, cin is linked to the keyboard, although it can be redirected to other devices. The variable that receives input is specified by var.

Here is a program that demonstrates console input. It computes the area of a rectangle, the dimensions of which are entered by the user.

/*
  An interactive program that computes
  the area of a rectangle.
*/

#include <iostream>
using namespace std;

int main()
{
  int length;
  int width;

  cout << "Enter the length: ";
  cin >> length; // input the length

  cout << "Enter the width: ";
  cin >> width; // input the width

  // Compute and display the area.
  cout << "The area is " << length * width;

  cout << "\n";

  return 0;
}

Here is a sample run:

Enter the length: 8
Enter the width: 3
The area is 24

Pay special attention to these lines:

cout << "Enter the length: ";
cin >> length; // input the length

The cout statement prompts the user. The cin statement reads the user’s response, storing the value in length. The value entered by the user (which must be an integer in this case) is put into the variable that is on the right side of the >> (in this case, length). Thus, after the cin statement executes, length will contain the rectangle’s length. (If the user enters a nonnumeric response, length will be zero.) The statements that prompt for and read the width work in the same way.

 

Two Control Statements

Inside a function, execution proceeds sequentially from one statement to the next, top to bottom. It is possible, however, to alter this flow through the use of the various program control statements. C++ supports a rich set of such statements. We will examine two here: the if and for.

 

The if Statement

You can selectively execute part of a program through the use of C++’s conditional statement: the if. Its simplest form is shown here:

if(condition) statement;

Here, condition is an expression that evaluates to either true or false. In C++, true is nonzero and false is zero. If the condition is true, then the statement will execute. If it is false, then the statement will not execute. For example, the following fragment displays the phrase "10 is less than 11" on the screen because 10 is less than 11.

if(10 < 11) cout << "10 is less than 11";

However, consider the following:

if(10 > 11) cout << "this does not display";

In this case, 10 is not greater than 11, so the cout statement is not executed. Of course, the operands inside a conditional expression need not be constants. They can also involve variables.

C++ defines a full complement of relational operators that can be used in a conditional expression. They are shown here:

Operator

Meaning

<

Less than

<=

Less than or equal

>

Greater than

>=

Greater than or equal

==

Equal to

!=

Not equal

Notice that the test for equality is the double equal sign.

Here is a program that illustrates the if statement:

// Demonstrate the if.

#include <iostream>
using namespace std;

int main() {
  int a;
  int b;

  a = 10;
  b = 20;

  // Demonstrate the if.
  if(a != b) cout << "a is not equal to b\n";
  if(a < b) cout << "a is less than b\n";
  if(a == 10) cout << "a equals 10\n";
  if(a == 1000) cout << "This won't be displayed\n";

  return 0;
}

The output generated by this program is shown here:

a is not equal to b
a is less than b
a equals 10

 

The for Loop

You can repeatedly execute a sequence of code by creating a loop. C++ supplies a powerful assortment of loop constructs. The one we will look at here is the for loop. The simplest form of the for loop is shown here:

for(initialization; condition; itr-expr) statement;

Here, initialization sets a loop control variable to an initial value. The condition is an expression that is tested each time the loop repeats. As long as condition is true (nonzero), statement is executed and the loop keeps running. The itr-expr is an expression that determines how the loop control variable is changed each time the loop repeats.

The following program demonstrates the for. It prints the numbers 0 through 4 on the screen.

// Demonstrate the for loop.

#include <iostream>
using namespace std;

int main()
{
  int x;

  for(x = 0; x < 5; x = x+1)
    cout << "This is x: " << x << "\n";

  return 0;
}

The output is shown here.

This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4

In this example, x is the loop control variable. It is set to zero in the initialization portion of the for. At the start of each iteration (including the first one), the conditional test x < 5 is performed. If the outcome of this test is true, the cout statement is executed, and then x is increased by one. This process continues until the conditional test is false, at which point execution picks up at the bottom of the loop.

In professionally written C++ code, you will almost never see a statement like

x = x+1

because C++ includes a special increment operator that performs this operation more efficiently. The increment operator is ++ (two consecutive plus signs). The ++ operator increases its operand by 1. For example, the preceding for statement will generally be written like this:

for(x = 0; x < 5; x++)

You might want to try this. As you will see, the loop still runs exactly the same as it did before.

C++ also provides a decrement operator, which is specified as – –. It decreases its operand by 1.

 

Create a Code Block

Another key element of C++ is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for if and for statements. Consider this if statement:

if(w < h) {
  v = w * h;
  w = 0;
}

Here, if w is less than h, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block.

 

Putting it all together

Although you know only a little about C++ at this point, you can still use it to write a useful program. The following program creates a table of conversions from feet to meters, beginning with 1 foot and ending at 99 feet. This is accomplished through the use of a for loop. After every 10 conversions, it outputs a blank line. This is handled by an if statement that examines the value of a variable called count. After each conversion is displayed, the value of count is incremented. If it equals 10, a blank line is output and count is reset. Notice that the targets of the for and if are blocks of code.

// This program displays a conversion table of feet to meters.

#include <iostream>
using namespace std;

int main() {
  int f; // holds the length in feet
  int count; // holds the line count

  count = 0;

  for(f = 1; f < 100; f++) {
    // Convert to meters and display the result.
    cout << f << " feet is " << f / 3.28 << " meters.\n";

    // Increment the line counter.
    count++;

    // Every 10th line, print a blank line.
    if(count == 10) {
      cout << "\n"; // output a blank line
      count = 0; // reset the line counter
    }
  }

  return 0;
}

Here is a portion of the output.

1 feet is 0.304878 meters.
2 feet is 0.609756 meters.
3 feet is 0.914634 meters.
4 feet is 1.21951 meters.
5 feet is 1.52439 meters.
6 feet is 1.82927 meters.
7 feet is 2.13415 meters.
8 feet is 2.43902 meters.
9 feet is 2.7439 meters.
10 feet is 3.04878 meters.

11 feet is 3.35366 meters.
12 feet is 3.65854 meters.
13 feet is 3.96341 meters.
14 feet is 4.26829 meters.
15 feet is 4.57317 meters.
16 feet is 4.87805 meters.
17 feet is 5.18293 meters.
18 feet is 5.4878 meters.
19 feet is 5.79268 meters.
20 feet is 6.09756 meters.

 

A Short Word About Classes and Object-Oriented Programming

There is much more to C++ than the preceding simple examples show. One of the most important elements is the class, which provides support for object-oriented programming (OOP). Although the class and the other object-oriented features are beyond the scope of this article, they are an important part of C++ programming.

OOP is based on three key principles: encapsulation, inheritance, and polymorphism. Encapsulation binds together code and data, inheritance is the mechanism by which one class can inherit the functionality of another, and polymorphism lets you define one interface that describes a general set of actions. These attributes work together to enable the construction of reliable, reusable, and extensible programs. As you advance in your study of C++, you will see how the object-oriented features play an integral role in the way that C++ code is written.

 

Continuing Your Study of C++

This short introduction to C++ has shown you some of the key elements of the language, including the general form of a C++ program, variables, reading input from the keyboard, two control statements, and code blocks. Of course, you have only just begun your study of this powerful language. To continue, consider C++: A Beginner's Guide.

 

  © 2008  HerbSchildt.com  All rights reserved worldwide. No duplication allowed without prior written permission.