2.Programming and problem Solving

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

2.

Programming Languages &

Fundamental Programming
Concepts

Categories of Programming Languages


Programming languages could be divided into two main categories:

1. low-level languages

2. high-level languages.

The first category is also known as the machine-oriented languages, while the
second category includes the problem-oriented or human-oriented language.

In the early times of computer science, only the machine language was available
for programming. Many difficulties has been encountered by using this machine
oriented approach which meant that only specialists can perform computer
programming. This period was followed by using symbolic languages known as
the assembly language. These languages, which are still machine oriented, use
memories instead of directly coding the instructions in their equivalent binary
patterns. This represented a very important development in programming but

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

1
assemblers are to be used corresponding machines forms known as translators to
convert the assembly code into the object code. This process is illustrated in the
following figure.

Figure: Translation from assembly code program to executable program.

The fifties of the twenties century has witnessed the invention of the early high-
level languages. High level languages used English-like words for coding the
instructions, such as print, read, write, etc.

High level languages such as Fortran, Pascal, C and C++.

Programs written using a high level languages, i.e. user-oriented programs, need
translators to be run or executed. These translators are known as interpreters and
compilers.

As it is represented in the following figure, compilers have the function to


transform the source program written in a high level language into an object
program ready for execution as a whole if it is error-free. In other words, the
function of a compiler is to transform the user-oriented representation of a given
software into its machine-oriented representation ready for any eventual execution
on the computer.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

2
Figure: Translation from high level code to executable program

C++ Programming Language & Structure of


a C++ program:
C++ is the most important object-oriented programming language. It is currently
the most popular implementation language for applications in different areas.

The best way to start learning a programming language is with a program. So here
is our first program:

The left side shows the source code for our first program, which we can name, for
example, hiworld.cpp. The right side shows the result of the program once
compiled and executed.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

3
The previous program is the first program that most programming apprentices
write, and its result is the printing on screen of the "Hello World!" sentence. It is
one of the simpler programs that can be written in C++, but it already includes the
basic components that every C++ program has. We are going to take a look at them
one by one:

// my first program in C++


This is a comment line. All the lines beginning with two slash signs (//) are
considered comments and do not have any effect on the behavior of the program.
They can be used by the programmer to include short explanations or observations
within the source itself. In this case, the line is a brief description of what our
program is.
#include <iostream.h>
Sentences that begin with a pound sign (#) are directives for the preprocessor.
They are not executable code lines but indications for the compiler. In this case the
sentence #include<iostream.h> tells the compiler's preprocessor to include
the iostream standard header file. This specific file includes the declarations of the
basic standard input-output library in C ++, and it is included because its
functionality is used later in the program.

int main ()
This line corresponds to the beginning of the main function declaration. The
main function is the point by where all C++ programs begin their execution. It is
independent of whether it is at the beginning, at the end or in the middle of the
code - its content is always the first to be executed when a program starts. In

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

4
addition, for that same reason, it is essential that all C++ programs have a main
function.
main is followed by a pair of parenthesis () because it is a function. In C++ all
functions are followed by a pair of parenthesis () that, optionally, can include
arguments within them.
The content of the main function immediately follows its formal declaration and
it is enclosed between curly brackets ({}), as in our example.
cout << "Hello World";
This instruction does the most important thing in this program. cout is the
standard output stream in C++ (usually the screen), and the full sentence inserts a
sequence of characters (in this case "Hello World") into this output stream (the
screen). cout is declared in the iostream.h header file, so in order to be able
to use it that file must be included. Notice that the sentence ends with a semicolon
character (;). This character signifies the end of the instruction and must be
included after every instruction in any C++ program (one of the most common
errors of C++ programmers is indeed to forget to include a semicolon ; at the end
of each instruction).
return 0;
The return instruction causes the main() function finish and return the code
that the instruction is followed by, in this case 0. This it is most usual way to
terminate a program that has not found any errors during its execution. As you will
see in coming examples, all C++ programs end with a sentence similar to this.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

5
Therefore, you may have noticed that not all the lines of this program did an
action. There were lines containing only comments (those beginning by //), lines
with instructions for the compiler's preprocessor (those beginning by #), then there
were lines that initiated the declaration of a function (in this case, the main
function) and, finally lines with instructions (like the call to cout <<), these last
ones were all included within the block delimited by the curly brackets ({}) of the
main function.
The program has been structured in different lines in order to be more readable, but
it is not compulsory to do so. For example, instead of
int main ()

cout << " Hello World ";


return 0;
}

we could have written:


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

in just one line and this would have had exactly the same meaning.
In C++ the separation between instructions is specified with an ending semicolon
(;) after each one.
Here is a program with some more instructions:

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

6
In this case we used the cout << method twice in two different instructions.
Once again, the separation in different lines of the code has just been done to give
greater readability to the program, since main could have been perfectly defined
thus:
int main () { cout << " Hello World! "; cout << " I'm
to C++ program "; return 0; }
The result would have been exactly the same than in the previous examples.

Comments:
Program comments are explanatory statements that you can include in the C++ code that
you write and helps anyone reading its source code. All programming languages allow
for some form of comments. The comments do nothing
C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example:

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

7
A comment can also start with //, extending to the end of the line. For
example:

When the above code is compiled, it will ignore // prints Hello World and
final executable will produce the following result:

We are going to add comments to our second program:

If you include comments within the sourcecode of your programs without using the
comment characters combinations //, /* or */, the compiler will take them as if
they were C++ instructions and, most likely causing one or several error messages.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

8
Variables. Data types. Constants:
The programming is not limited only to printing texts on screen. In order to go a
little further on and to become able to write programs that perform useful tasks that
really save us work we need to introduce the concept of the variable.
A variable is a named location that stores a value.
Although variables are physically stored in the RAM, their actual memory address
is not known to the programmer. We can use the variables via the name we give
them. This same process can be expressed in C++ with the following instruction
set:
a = 5;
b = 2;
a = a + 1;
result = a - b;
Each variable needs an identifier that distinguishes it from the others, for example,
in the previous code the variable identifiers were a, b and result.

Identifiers:
A C++ identifier is a name used to identify a variable, function, class, module, or
any other user-defined item. The rules of identifier:
1. The name must begin with a letter (A to Z or a to z) or an underscore ( _ )
and can be followed by zero or more letters, underscores, and digits (0 to 9).
2. Special characters such as ? - + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . can‘t be used
in variable name.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

9
3. A variable name must not be the same as a reserved keyword such as (int ,
if, for, void).
4. Variables with the same scope can’t have the same name.
Scope: C++ is a block - structured language. The scope of the variable extends
from the point of its declaration till the end of the block containing the declaration.

Very important Note: C++ is a case-sensitive programming language. That that


means that an identifier written in capital letters is not equivalent to another one
with the same name but written in small letters. For example the variable
RESULT is not the same as the variable result nor the variable Result.

Here are some examples of acceptable identifiers:

Data types:
When programming, we store the variables in our computer's memory, but the
computer must know what we want to store in them since storing a simple number,
a letter or a large number is not going to occupy the same space in memory.
Our computer's memory is organized in bytes. A byte is the minimum amount of
memory that we can manage. A byte can store a relatively small amount of data,
usually an integer between 0 and 255 or one single character. But in addition, the
computer can manipulate more complex data types that come from grouping
several bytes, such as long numbers or numbers with decimals. Next you have a list
of the existing fundamental data types in C++.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

10
Several of the basic types can be modified using one or more of these type
modifiers:
 signed
 unsigned
 short
 long

The following table shows the variable type, how much memory it takes to store
the value in memory, and what is maximum and minimum value, which can be
stored in such type of variables.
Data Type Size Description Range
char 1 byte A single character /letter
/number, or ASCII values.
bool 1 byte Stores true or false values
int 4 bytes Stores numbers without Signed: 2147483648 to
floating point. 2147483647
Unsigned: 0 to 4294967295
float 4 bytes Floating point number. 3.4e+ / -38 (7 digits)

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

11
double 8 bytes Double precision 1.7e+ / -308 (15 digits)
floating point number.
long double 10 bytes Long double precision 1.2e+ / -4932 (19 digits)
floating point number.

Declaration of variables
In order to use a variable in C++, we must first declare it specifying which of the
data types above we want it to be. The syntax to declare a new variable is to write
the data type that we want (like int, short, float...) followed by a valid
variable identifier. For example:
int a;
float mynumber;
Are valid declarations of variables. The first one declares a variable of type int
with the identifier a. The second one declares a variable of type float with the
identifier mynumber. Once declared, variables a and mynumber can be used
within the rest of their scope in the program.
If you need to declare several variables of the same type and you want to save
some writing work you can declare all of them in the same line separating the
identifiers with commas.
For example:
int a, b, c;
declares three variables (a, b and c) of type int , and has exactly the same
meaning as if we had written:

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

12
int a;
int b;
int c;

To see what variable declaration looks like in action in a program, we are going to
show the C++ code of the example:

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

13
Initialization of variables
When declaring a local variable, its value is undetermined by default. But you may
want a variable to store a concrete value the moment that it is declared. In order to
do that, you have to append an equal sign followed by the value wanted to the
variable declaration:
type identifier = initial_value ;
For example, if we want to declare an int variable called a that contains the
value 0 at the moment in which it is declared, we could write:
int a = 0;

Scope of variables
The scope of the variable is the region of code from which the variable can be
accessed.
All the variables that we are going to use must have been previously declared.
The traditional way to declare variables is to include their declaration at the
beginning of each function (for local variables) or directly in the body of the
program outside any function (for global variables).

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

14
Global variables can be referred to anywhere in the code, within any function,
whenever it is after its declaration.
The scope of the local variables is limited to the code level in which they are
declared. If they are declared at the beginning of a function (like in main) their
scope is the whole main function.
In the example above, this means that if another function existed in addition to
main(), the local variables declared in main could not be used in the other
function and vice versa (the global variables could be used).
In C++, the scope of a local variable is given by the block in which it is declared (a
block is a group of instructions grouped together within curly brackets {} signs).
If it is declared within a function it will be a variable with function scope, if it is
declared in a loop its scope will be only the loop, etc...

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

15
Constants (const):
A constant is a variable whose value can’t be changed throughout its life time.
Prefixing a variable with the const keyword when it is declared and initialized
designates that variable as a constant:
const int width = 100; //this value can’t be changed
const char abc = 'M';

Basic Input/Output
Until now, the example programs of previous sections provided very little
interaction with the user, if any at all. Using the standard input and output library,
we will be able to interact with the user by printing messages on the screen and
getting the user's input from the keyboard.
C++ uses a convenient abstraction called streams to perform input and output
operations in sequential media such as the screen or the keyboard.
The standard C++ library includes the header file iostream, where the standard
input and output stream objects are declared.

Standard Output (cout)


By default, the standard output of a program is the screen, and the C++ stream
object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as <<
(two "less than" signs).

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

16
The << operator inserts the data that follows it into the stream preceding it. In the
examples above it inserted the constant string Output sentence, the numerical
constant 120 and variable x into the standard output stream cout.
Notice that the sentence in the first instruction is enclosed between double quotes
(") because it is a constant string of characters. Whenever we want to use constant
strings of characters we must enclose them between double quotes (") so that they
can be clearly distinguished from variable names. For example, these two
sentences have very different results:

The insertion operator (<<) may be used more than once in a single statement:

This last statement would print the message Hello, I am a C++ statement on the
screen. The utility of repeating the insertion operator (<<) is demonstrated when
we want to print out a combination of variables and constants or more than one
variable:

If we assume the age variable to contain the value 24 and the zipcode variable to
contain 90064 the output of the previous statement would be:

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

17
It is important to notice that cout does not add a line break after its output unless
we explicitly indicate it, therefore, the following statements:

will be shown on the screen one following the other without any line break
between them:
This is a sentence.This is another sentence.
even though we had written them in two different insertions into cout. In order to
perform a line break on the output we must explicitly insert a new-line character
into cout. In C++ a new-line character can be specified as \n (backslash, n):

This produces the following output:


First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For
example:

would print out:


First sentence.
Second sentence.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

18
The endl manipulator produces a newline character, exactly as the insertion of '\n'
does, so you can generally use both the \n escape character and the endl
manipulator in order to specify a new line without any difference in its behavior.

Standard Input (cin).


The standard input device is usually the keyboard. Handling the standard input in
C++ is done by applying the overloaded operator of extraction (>>) on the cin
stream. The operator must be followed by the variable that will store the data that
is going to be extracted from the stream. For example:

The first statement declares a variable of type int called age, and the second one
waits for an input from cin (the keyboard) in order to store it in this integer
variable.
cin can only process the input from the keyboard once the RETURN key has been
pressed. Therefore, even if you request a single character, the extraction from cin
will not process the input until the user presses RETURN after the character has
been introduced.
You must always consider the type of the variable that you are using as a container
with cin extractions. If you request an integer you will get an integer, if you
request a character you will get a character and if you request a string of characters
you will get a string of characters.

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

19
The user of a program may be one of the factors that generate errors even in the
simplest programs that use cin (like the one we have just seen). Since if you
request an integer value and the user introduces a name (which generally is a string
of characters), the result may cause your program to mis-operate since it is not
what we were expecting from the user. So when you use the data input provided by
cin extractions you will have to trust that the user of your program will be
cooperative and that he/she will not introduce his/her name or something similar
when an integer value is requested. You can also use cin to request more than one
datum input from the user:

is equivalent to:

In both cases the user must give two data, one for variable a and another one for
variable b .

Dr. Omaima Bahaidara........................................................ Programming and problem Solving

20

You might also like