Sei sulla pagina 1di 10

About C++

C++ is a high-level, general purpose, object-oriented programming language. What does


the term OOP means? Leave it until your end term. Right now, just try to focus on
programming fundamentals.

C++ can be used to get the computer to do virtually anything. But, on the other hand,
when executing a program that you wrote the computer only does what you have
programmed it to do, no less, but also no more. If you forget anything, or the output does
not look pretty, or the results of computations are incorrect, there's nobody to blame but
yourself.

A Simple Sample Program

Here is a simple program (in source code), written according to the C++ standard.

Task/Goal: Create a program that will compute the volume of a sphere, given its radius.

In most cases when we need to solve a particular programming problem, we will proceed
in different stages. Each stage will bring us closer to solving the desired task.

Stage 0: This stage is the basic outline for every C++ program. In other words, every C+
+ program you create will include at least the following lines:

#include <iostream.h>
#include <conio.h>

int main(void)
{
some stuff here
getch();
return 0;
}

Of course, the phrase some stuff here must be replaced by suitable C++ compliant
statements. We will discuss later what exactly these lines mean; for now, just remember
that every C++ program will include them.

Stage 1: Next, we will break up our task into several sub-tasks. This is actually the most
important part of creating a program: defining the sub-tasks so that each is responsible for
solving one small, well-defined piece of the total task. If this step is performed carefully,
the rest is usually easy. In our case, there are three different subtasks:

• asking the user to enter a value for the radius of the sphere
• computing the volume of the sphere according to the formula V = 4/3 * Pi *
r^3
• displaying the answer on the screen
At this stage, we will not worry about how to actually solve these subtasks; we will
merely state what they are:

#include <iostream.h>
#include <conio.h>

int main(void)
{
// ask user for the value of the radius
// compute the volume of the sphere (V = 4/3 * Pi * r^3)
// display the answer on the screen
getch();
return 0;
}

Note that I have used "plain english" to describe subtasks, prefaced by a double-slash //.
That is called a comment: a comment consists of one or more lines of plain english text,
describing what a program is supposed to accomplish at that particular point. Comments
are prefaced by a double-slash //. The compiler will simply ignore everything after a
double-slash until the end of the line. Therefore, the compile would interpret the stage-0
and stage-1 programs as being the same.

Stage 2: Now that I have broken down the task into various subtasks, I can go about
solving each subtask separately. Here is the code, with the explanations later:

#include <iostream.h>
#include <conio.h>

int main(void)
{
// ask user for the value of the radius
double r;
cin >> r;
// compute the volume of the sphere (V = 4/3 * Pi * r^3)
double V = 4.0 / 3.0 * Pi * r^3;
// display the answer on the screen
cout << V;
getch();
return 0;
}

These lines are written according to the vocabulary and grammar of the C++
programming language (they may contain mistakes for now). Here is a brief explanation
of what they mean:

• double r: We are informing the compiler to reserve memory for a variable


named r. That variable will contain a decimal number, which in C++ are called
"double".
• cin >> r: The cin statement "connects" the keyboard to the variable r. It has the
effect that anything the user types will be redirected into the variable r as soon as
the user hits the RETURN key.
• double V = 4.0 / 3.0 * Pi * r^3: This statement actually accomplishes two
things simultaneously. First, it defines a new variable V which will again be of
type "double" (i.e. a decimal number). Also, it computes a number according to
the formula 4.0 / 3.0 * Pi * r^3 and stores the result in the variable V that
was just defined.
• cout << V: Just as the cin >> r statement connects the keyboard to the variable
r, this statement connects the variable V to the screen. In effect, the value of V will
appear on the screen.

Our program is finished, or at least we hope it is finished. We would now save this
program in a file that we might call "volume.cpp", where the cpp extension indicates
that our file is a C++ source code file. We can now use a C++ compiler to compile the
program and produce the corresponding object code file volume.obj. However, the
compiler will not be able to create the object file, because our source code contains
errors. The compiler will inform us that

• the variable Pi is unknown, or undeclared, and


• the operation r^3 is unknown to the C++ compiler.

Stage 3: An error message during the compilation stage is nothing unusual. In fact, it is
very common, and you should really think of compiler error messages as helpful hints of
how to modify your program so that it adheres exactly to the C++ grammar and
vocabulary. In our case, we need to modify our program as follows:

#include <iostream.h>
#include <conio.h>

int main(void)
{
// defining Pi as a constant
const double Pi = 3.1415;
// ask user for the value of the radius
double r;
cin >> r;
// compute the volume of the sphere (V = 4/3 * Pi * r^3)
double V = 4.0 / 3.0 * Pi * r*r*r;
// display the answer on the screen
cout << V;
getch();
return 0;
}

In other words, we added two lines at the beginning of our program:

• The first line is simply a comment, indicating what we are about to do - because it
is prefaced by the double-slash - and is therefore ignored by the compiler
• The next line informs the compiler that we are planning to use a decimal (or
double) variable named Pi which we set to the value 3.1415. We also use the
const keyword to indicate that Pi is considered a constant, i.e. its value will not
change in our program.

We have also replaced the statement r^3 (which the compiler did not like) by the
statement r*r*r. After all, mathematically they mean the same thing, and if the compiler
does not like one way (r^3), perhaps it understands the second way (r*r*r).

After saving this new version again as file volume.cpp, it will compile without any error
messages.

We are now ready to execute our program. If we do that, we will simply see a blinking
cursor. We need to remember that one of the first things our program does is wait for the
user to enter a value for the radius. However, no message informing us appears, because
we have not programmed such a message into our program. If we enter the value, say,
2.0, our program will then display another number representing the volume of a sphere
with radius 2. But, it will not display a message saying what this number means (because
again we did not program that in).

Stage 4: Therefore, we'll improve our program one more time by adding the appropriate
"prompts" to it. Here's our code:

#include <iostream.h>

int main(void)
{
// defining Pi as a constant
const double Pi = 3.1415;
// ask user for the value of the radius
cout << "Please enter the radius: ";
double r;
cin >> r;
// compute the volume of the sphere (V = 4/3 * Pi * r^3)
double V = 4.0 / 3.0 * Pi * r*r*r;
// display the answer on the screen
cout << "The volume of the sphere is: " << V;
return 0;
}

This will again compile fine and produce - almost - reasonable output.

When you write C++ programs, there are several things to keep in mind:

• your program does exactly and only what you define, no more and no less
• a C++ program executes one line at a time, from top to bottom, unless specified
otherwise
• C++ programs can use cin to get input from a user, and cout to display output
• C++ programs usually store some information
• C++ programs usually do some computations

C++ Basics

There are a few basic rules for every C++ program:

Basic C++ Rules:

• every C++ program uses certain keywords that have special meaning (e.g. int,
main, void, return)
• every C++ program uses certain operators that perform specific actions (e.g. +, *,
cin, cout)
• every C++ program is case-sensitive, i.e. the capitalization of keywords and
operators counts (e.g. int is different from Int or INT)
• every C++ program uses curly brackets to group statements together
• every C++ program has a semicolor at the end of every instruction
• almost every C++ program that handles user input and output will contain the line
#include <iostream.h>
• almost every c++ program will contain the lines

int main(void)
{
// other stuff
return 0;
}

Declaring Variables

• C++ provides several different basic data types. The most important ones are:
• double: decimal numbers between a smallest, negative one and a largest, positive
one
• int: a whole number between a smallest, negative one and a sargest, positive one
• char: a single letter or special symbol, anything that is on your keyboard

If you need to store information anywhere in your program, you need to tell the compiler
what type of info you plan to store and what name you want to use to refer to that
information. In C++, you need to declare a variable:

Syntax for declaring a variable:

• type varName [1, varName2, ..., varNameN];

where type is one of the basic (or other known) data types, and varName is the name of a
variable. The variable can be declared anywhere in your program. You usually declare it
just before it is needed, unless the variable represents something very important to your
program in which case you declare it at the beginning of the program.

Example:

double x;
int X, Y, Z;
char cc;

This means that you can now use these variables to store and manipulate
information.Note that x and X are two different variables, i.e. C++ is case-sensitive.

Assigning values to variables

• Once a variable is declared, you can assign values to it, and use it in
computations. To assign a value to a variable, the assignment operator = is used.
Note that this operation looks like the math symbol for equal, but it works
differently.

Syntax for assignment:

• varName = expression

where varName is the name of a variable that has been declared previously, and
expression is a valid C++ expression.

Example:

double x;
x = 10.0;

C++ Expression and Standard Operations

A valid C++ expression can consists of constants, declared variables, or combinations of


constants, declared variables, and operations. The standard operations are +, -, *, /, and
%, where % stands for the remainder after integer division. The usual order of operations
applies, and can be modified using standard parenthesis.

Note: When you assign an expression to a variable, the following happens:

• first, the value of the right side is computed


• second, that computed value is assigned to the variable on the left

It is that order of events that make the assignment operator different from the
mathematical equal sign.

Example:
double x, y;
int i, k;
x = 2.8;
y = -1.4*x;
i = 9;
k = (i % 2) * (7 + 5*i);

Combined Declaration and Assignment:

In C++, you can declare a new variable, and at the same time assign a value to it (or
initialize the variable).

Example;

double x = 1.0;
int i = 10, j = 20;
int k = i + j;

Sometimes you also need a number that represents a particular constant (for example, Pi
= 3.1415, or e = 2.71). C++ allows you to define constants like this:

Defining Constants

To define a constant in C++ you preface the type of the variable by the keyword const.
The value of a variable declared as a constant can not change inside your program.
Constants are usually declared at the beginning of your program, and they must be
assigned a value at the time you declare them.

Example:

const double Pi = 3.1415;

Now we can produce some more interesting programs.

Task 1: Create a program that asks the user for the radius of a disk, then computes the
area and circumference.

Stage 0: As usual, our stage-0 program is:

#include <iostream.h>

int main(void)
{
// stuff
return 0;
}

Stage 1: As usual, we use comments to break up our task into smaller subtasks:
#include <iostream.h>

int main(void)
{
// get the radius from the user
// compute the area
// compute the circumference
// display the answers
}

Stage 2: Now we get into the details of which variables and formulas to use:

#include <iostream.h>

int main(void)
{
// need a variable r for the radius
double r;
// getting the input from the user
cin >> r;
// computing the area A = Pi * r^2
double A = Pi * r^2;
// computing the circumference C = 2 * Pi * r;
double C = 2 * Pi * r;
// displaying both answers
cout << A;
cout << C;
return 0;
}

At this point, we let the compiler tell us if the C++ grammar is correct or not. The
compiler will tell us the r^2 is "unknown", so we change that line to:

double A = Pi * r^2;

Also, the compiler will tell us that it does not know what Pi stands for. Therefore, we
declare it as a constant at the beginning of our program:

const double Pi = 3.1415;

Then we compile it again. It will now compile, so we can link it to produce the
executable file. Finally, we execute the program to test it, and we find that everything
works, but it does not look good. So, we'll modify the program one more time:

Stage 3: We add some more input/output statements to make our program more
"appealing" to the user:

#include <iostream.h>

int main(void)
{
// defining the constants needed in this program
const double Pi = 3.1415;
// need a variable r for the radius
double r;
// getting the input from the user
cout << "Please enter the radius: ";
cin >> r;
// computing the area A = Pi * r^2
double A = Pi * r^2;
// computing the circumference C = 2 * Pi * r;
double C = 2 * Pi * r;
// displaying both answers
cout << "The area is: ";
cout << A;
cout << "The circumference is: ";
cout << C;
return 0;
}

Acutally, the last four statements can be linked together. Instead of saying:

cout << "The area is: ";


cout << A;
cout << "The circumference is: ";
cout << C;

we can also say:

cout << "The area is: " << A << " and the circumference is " << C;

After changing that, our program will work correctly, and produce reasonably nice
looking results on the screen.

This is the end of this tutorial.

Potrebbero piacerti anche