Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Structure of A Program

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Structure of a program

Probably the best way to start learning a programming language is by writing a


program. Therefore, here is our first program:

// my first program in C++ Hello World!

#include <iostream>
using namespace std;

int main ()
{
cout << "Hello World!";
return 0;
}

The first panel shows the source code for our first program. The second one shows
the result of the program once compiled and executed.

The way to edit and compile a program depends on the compiler you are using.
Depending on whether it has a Development Interface or not and on its version. It
is one of the simplest programs that can be written in C++, but it already contains
the fundamental components that every C++ program has. We are going to look
line

by line at the code we have just written:

// my first program in C++


This is a comment line. All lines beginning with two
slash signs (//) are considered comments and do not have
any effect on the behavior of the program.

The programmer can use them to include short


explanations or observations within the source codeitself.
In this case, the line is a brief description of

what our program is.

#include <iostream>

Lines beginning with a hash sign (#) are directives for the
preprocessor. They are not regular code lines with
expressions but indications for the compiler's
preprocessor.

In this case the directive #include <iostream> tells the


preprocessor to include the iostream standard file. This
specific file (iostream) includes the declarations of the
basic standard input-output library in C++, and it is
included because its functionality is going to be used
later in the program.

using namespace std;

All the elements of the standard C++ library are declared


within what is called a namespace, the namespace with
the name std.

So in order to access its functionality we declare with this


expression that we will be using these entities. This line
is very frequent in C++ programs that use the standard
library, and in fact it will be included in most of the
source codes included in these tutorials.

int main ()

This line corresponds to the beginning of the definition of


the main function. The main function is the point by
where all C++ programs start their execution,
independently of its location within the source code.It
does not matter whether there are other functions with
other names defined before or after it - the instructions
contained within this function's definition will always be
the first ones to be executed in any C++ program.

For that same reason, it is essential that all C++ programs


have a main function.

The word main is followed in the code by a pair of


parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function
declaration from other types of expressions are these
parentheses that follow its name. Optionally, these
parentheses may enclose a list of parameters within
them.

Right after these parentheses we can find the body of the


main function enclosed in braces ({}). What is contained
within these braces is what the function does when it is
executed

cout << "Hello World!";


This line is a C++ statement. A statement is a simple or
compound expression that can actually produce some
effect. In fact, this statement performs the only action
that generates a visible effect in our first program.

cout represents the standard output stream in C++, and


the meaning of the entire statement is to insert a sequence
of characters (in this case the Hello World sequence of
characters) into the standard output stream (which
usually is the screen). cout is declared in the iostream
standard file within the std namespace, so that's why we
needed to include that specific file and to declare that we
were going to use this specific namespace earlier in our
code.

Notice that the statement ends with a semicolon character


(;).

This character is used to mark the end of the statement


and in fact it must be included at the end of all expression
statements in all C++ programs (one of the most common
syntax errors is indeed to forget to include some
semicolon after a statement).

return 0;

The return statement causes the main function to finish.


return may be followed by a return code (in our example
is followed by the return code 0).

A return code of 0 for the main function is generally


interpreted as the program worked as expected without
any errors during its execution. This is the most usual
way to
end a C++ console program. The program has been
structured in different lines in order to be more readable,
but in C++, we do nothave strict
rules on how to separate instructions in different lines.

For example, instead of

int main ()
{
cout << " Hello World!";
return0;
}

We could have written:

int main () { cout << "Hello World!"; return0; }

All in just one line and this would have had exactly the
same meaning as the previous code. In C++, the separation
between statements is specified with an

ending semicolon (;) at the end of each one, so the


separation in different code lines does not matter at all for this
purpose.

We can write many statements per line or write a single


statement that takes many code lines. The division of code in
different lines serves only to

make it more legible and schematic for the humans that


may read it. Let us add an additional instruction to our first
program:
// my second program in Hello World! I'm a C++
C++ program
#include <iostream>
using namespace std;

int main ()
{
cout << "Hello World! ";
cout << "I'm a C++
program";
return0;
}

Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to insert
notes or descriptions embedded within the source code.

C++ supports two ways to insert comments:

// line comment

/* block comment */

/* my second program in C++ Hello World! I'm a


with more comments */ C++ program

#include <iostream>
using namespace std;

int main ()
{
cout << "Hello World! "; //
prints Hello World!
cout << "I'm a C++ program"; //
prints I'm a C++ program
return0;
}

The first of them, known as line comment, discards everything from where
the pair of slash signs (//) is found up to the end of that same line. The
second one, known as block comment, discards everything between the /*
characters and the first appearance of the */ characters, with the possibility
of including more than one line.

We are going to add comments to our second program: If you include


comments within the source code of your programs without using the
comment characters combinations //, /*or */, the compiler will take them as
if they were C++ expressions, most likely causing one or several error
messages when you compile it.

Variables. Data Types.

Identifiers (//Name of variable given by


programmers/you to variables)

A valid identifier is a sequence of one or more letters, digits or


underscore characters (_). Neither spaces nor punctuation marks or
symbols can be part of an identifier. Only letters, digits and single
underscore characters are valid. In addition, variable identifiers
always have to begin with a letter. They can also begin with an
underline character (_), but in some cases these may be reserved for
compiler specific keywords or external identifiers, as well as
identifiers containing two successive underscore characters anywhere.
In no case they can begin with a digit.

Another rule that you have to consider when inventing your own
identifiers is that they cannot match any keyword of the C++ language
nor your compiler's specific ones, which are reserved keywords. The
standard reserved keywords are:

C++ keywords
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue,
default, delete,

do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto,

if, inline, int, long, mutable, namespace, new, operator, private, protected,
public, register,

reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch,


template,

this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void,

volatile, wchar_t, while

Additionally, alternative representations for some operators cannot be


used as identifiers since they are reserved words under some circumstances:

and, and_eq, bitand, bitor, compl, not, not_eq, or,or_eq, xor, xor_eq

Your compiler may also include some additional specific reserved


keywords.

The C++ language is a "case sensitive" language


Very important: . That means that an identifier written in capital
letters is not equivalent to another one with the same name but written
in small letters. Thus, for example, the RESULTvariable is not the
same as the resultvariable or the Resultvariable. These are three
different variable identifiers.

Fundamental data types

When programming, we store the variables in our computer's


memory, but the computer has to know what kind of data we want to
store in them, since it is not going to occupy the same amount of
memory to store a simple number than to store a single letter or a
large number, and they are not going to be interpreted the same way.

The memory in our computers is organized in bytes. A byte is the


minimum amount of memory that we can manage in C++. A byte can
store a relatively small amount of data: one single character or a small
integer (generally an integer between 0 and 255). In addition, the
computer can manipulate more complex data types that come from
grouping several bytes, such as long numbers or non-integer numbers.

Next you have a summary of the basic fundamental data types in C++,
as well as the range of values that can be represented with each one:
* The values of the columns Size and Range depend on the system the
program is compiled for. The values shown above are those found on
most 32-bit systems. But for other systems, the general specification is
that int has the natural size suggested by the system architecture (one
"word") and the four integer types char, short, Int and long must each
one be at least as large as the one preceding it, with charbeing always
1 byte in size.

Declaration of variables

In order to use a variable in C++, we must first declare it specifying


which data type we want it to be. The syntax to declare a new variable
is to write the specifier of the esired data type (like int, bool, float...)
followed by a valid variable identifier. For example:

These are two valid declarations of variables. The first one declares a
variable of type intwith the identifier a. The second one declares a
variable of type floatwith the identifier mynumber. Once declared,
the variables aand my numbercan be used within the rest of their
scope in the program. If you are going to declare more than one
variable of the same type, you can declare all of them in a single
statement by separating their identifiers with commas. For example:

This declares three variables (a, band c), all of them of type int, and
has exactly the same meaning as:

The integer data types char, short, longand intcan be either signed or
unsigned depending on the range of numbers needed to be
represented. Signed types can represent both positive and negative
values, whereas unsigned types can only represent positive values
(and zero). This can be specified by using either the specifier signedor
the specifier unsignedbefore the type name. For example:
By default, if we do not specify either signedor unsignedmost
compiler settings will assume the type to be signed, therefore

instead of the second declarationabove we could have written:

with exactly the same meaning (with or without the keyword signed)
An exception to this general rule is the chartype, which exists by itself
and is considered a different fundamental data type from signed
charand unsigned char, thought to store characters. You should use
either signedor unsignedif you intend to store numerical values in a
char-sized variable. shortand longcan be used alone as type
specifiers. In this case, they refer to their respective integer
fundamental types: shortis equivalent to short intand longis
equivalent to long int. The following two variable declarations are
equivalent:

shortand longcan be used alone as type specifiers. In this case, they


refer to their respective integer fundamental types: shortis
equivalent to short intand longis equivalent to long int. The following
two variable declarations are equivalent:
Finally, signedand unsignedmay also be used as standalone type
specifiers, meaning the same as signed int and unsigned
intrespectively. The following two declarations are equivalent:

// operating with variables 4


#include <iostream>
using namespacestd;

intmain ()
{
// declaring variables:
int a, b;
int result;

// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;

// print out the result:


cout << result;

// terminate the program:


return0;
}

You might also like