Chapter One (Fundamentals of C++ Programming Language)
Chapter One (Fundamentals of C++ Programming Language)
Chapter One (Fundamentals of C++ Programming Language)
C++ is one of the most widely used, fastest and most powerful of compiled languages
Structure of C++ Program
Pre-processor Directives (#include<iostream.h>)
global declaration
void main(){
local declaration
statements
}
int sub-function(){
local declaration
statements
}
#include <iostream.h>
Sentences that begin with a pound sign (#) are directives for the pre-processor. They are
not executable code lines but indications for the compiler. In this case the sentence
#include <iostream.h> tells the compiler's pre-processor 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.
1
The pre-processor directive #include to include the content of the header file iostream.h
in the program. iostream.h is a standard C++ header file and contains the definition and
declaration for input and output (cin and cout).
Other header files
Header files Functions Uses
#include<iostream.h> cin and cout For input and output
#include<math.h> Sqrt(value),abs(value),sin(value) To use mathematical
cos(value),tan(value), pow(x, y) functions
#include<string.h> Strlen(string),strcmp(str1,str2) To predefined string
strrev(str1) function
#include<iomanip.h> Setw(number) To set equal space b/n
outputs
void main ()
This line corresponds to the beginning of the main function declaration. The main
function is the point 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 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.
A program written in C++ must always have a few basic components:
The pre-processor directive and header file
A main function – this is the function that will be executed, so this is where you
will write your program statements. The contents of the main function are
enclosed in curly brackets {}
Executable statements – these are the commands that will be executed, and they
should come after the variable declarations
Basic Elements of C++ Programming
A. Variables and constants
What are variables and constants?
A variable or a constant is just an identifier (or name) which is stored by the
computer and which has a specific value
A constant always has the same value, whereas the value of a variable can be
changed as the program runs.
Declaring variables
data_type identifier ,
example: int x;
2
Declaring constants
const data_type identifier=value;
example: const int x=20
#define identifier value: -this is also used to declaring constant
example: define PI 3.14
B. Identifiers
A valid identifier is a sequence of one or more letters, digits or underline symbols ( _ ).
The length of an identifier is not limited, although for some compilers only the 32 first
characters of an identifier are significant (the rest are not considered).
Neither spaces nor marked letters can be part of an identifier. Only letters, digits and
underline characters are valid. In addition, variable identifiers should always begin with a
letter. They can also begin with an underline character ( _ ), but this is usually reserved
for external links. They can never begin with a digit.
Another rule that you have to consider when inventing your own identifiers is that they
cannot match any key word of the C++ language nor your compiler's specific ones since
they could be confused with these. For example, the following expressions are always
considered key words according to the ANSI-C++ standard and therefore they must not
be used as identifiers:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, 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
Additionally, alternative representations for some operators do not have to 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 more specific reserved keywords. For example,
many compilers which generate 16 bit code (like some compilers for DOS) also include
far, huge and near as key words.
Very important: The C++ language is "case sensitive", 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 variable RESULT is not the same as the variable
result nor the variable Result.
C. 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
3
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++, as well as the range of values that can be represented with each one of them:
Data Types
Name Bytes* Description Range*
signed: -128 to 127
Char 1 character or integer 8 bits length.
unsigned: 0 to 255
signed: -32768 to
32767
Short 2 integer 16 bits length.
unsigned: 0 to
65535
signed:-
2147483648 to
Long 4 integer 32 bits length. 2147483647
unsigned: 0 to
4294967295
Integer. Its length traditionally depends on
the length of the system's Word type, thus
in MSDOS it is 16 bits long, whereas in 32
int * bit systems (like Windows 9x/2000/NT See short, long
and systems that work under protected
mode in x86 systems) it is 32 bits long (4
bytes).
3.4e + / - 38 (7
float 4 floating point number.
digits)
1.7e + / - 308 (15
double 8 double precision floating point number.
digits)
long long double precision floating point 1.2e + / - 4932 (19
10
double number. digits)
Boolean value. It can take one of two
values: true or false NOTE: this is a type
recently added by the ANSI-C++ standard.
bool 1 true or false
Not all compilers support it. Consult
section bool type for compatibility
information.
Wide character. It is designed as a type to
store international characters of a two-byte
wchar_t 2 character set. NOTE: this is a type recently wide characters
added by the ANSI-C++ standard. Not all
compilers support it.
* Values of columns Bytes and Range may vary depending on your system. The values
included here are the most commonly accepted and used by almost all compilers.
4
Scope of variables
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.
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...
Notes: - There are 5 different types of statements
declaration statement E.g int a;
initialization statement E.g. a=0;
input statement E.g cin>>a;
output statement E.g cout<<a;
expression statement a=a*2;
N.B All c++ statement must end with a semicolon
Input and Output Statements
You can input information from the user, or output information to the user, using the
commands cin and cout respectively. For example, the following program will print a
message to the screen, then read in two int values from the user:
#include <iostream.h>
main() {
int n1, n2;
cout << “Enter 2 numbers:” << endl;
cin >> n1 >> n2;
Cout<<n1<<n2;
Comment statements
A comment is some text in your program which is ignored by the compiler (like
REM in Basic)
Comments are a very useful way of making your code understandable to others
and to yourself – they are very good programming practise
You can add comments in C++ in two ways:
// this causes the compiler to ignore the rest of the line
/* … */ this pair of symbols causes the enclosed text to be ignored
Example
// this is a comment
5
/*
another comment
*/
D. C++ operators
o Arithmetic operators
The following arithmetic operators can be used in C++:
„+‟: addition
„-„: subtraction
„*‟: multiplication
„/‟: division
„%‟: modulo (the remainder from a division)
o Assignment statements
The assignation operator serves to assign a value to a variable.
a = 5;
assigns the integer value 5 to variable a. The part at the left of the = operator is known as
lvalue (left value) and the right one as rvalue (right value). lvalue must always be a
variable whereas the right side can be either a constant, a variable, the result of an
operation or any combination of them.
o Compound assignation operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
A feature of assignation in C++ that contributes to its fame of sparing language when
writing is the compound assignation operators (+=, -=, *= and /= among others), which
allow modifying the value of a variable with one of the basic operators:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
price *= units + 1; is equivalent to price = price * (units + 1);
and the same for all other operations.
o Increase and decrease
Another example of saving language when writing code are the increase operator (++)
and the decrease operator (--). They increase or reduce by 1 the value stored in a variable.
They are equivalent to +=1 and to -=1, respectively. Thus:
a++;
a+=1;
a=a+1;
are all equivalent in its functionality: the three increase by 1 the value of a. A
characteristic of this operator is that it can be used both as a prefix and as a suffix. That
means it can be written before the variable identifier (++a) or after (a++). Although in
simple expressions like a++ or ++a they have exactly the same meaning, in other
operations in which the result of the increase or decrease operation is evaluated as
another expression they may have an important difference in their meaning: In case that
6
the increase operator is used as a prefix (++a) the value is increased before the expression
is evaluated and therefore the increased value is considered in the expression; in case that
it is used as a suffix (a++) the value stored in a is increased after being evaluated and
therefore the value stored before the increase operation is evaluated in the expression.
o Logic operators ( !, &&, || )
Operator! is equivalent to boolean operation NOT, it has only one operand, located at its
right, and the only thing that it does is to invert the value of it, producing false if its
operand is true and true if its operand is false. It is like saying that it returns the opposite
result of evaluating its operand. For example:
!(5 == 5) returns false because the expression at its right (5 == 5) would be true.
!(6 <= 4) returns true because (6 <= 4) would be false
!true returns false
!false returns true
Logic operators && and || are used when evaluating two expressions to obtain a single
result. They correspond with boolean logic operations AND and OR respectively. The
result of them depends on the relation between its two operands:
First Second
result result
Operand Operand
a && b a || b
a b
True true true true
True false false true
False true false true
False false false false
For example:
((5==5) && (3>6)) returns false (true && false)
( (5 == 5) || (3 > 6)) returns true ( true || false)
Relational operators (==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the Relational
operators. As specified by the ANSI-C++ standard, the result of a relational operation is a
bool value that can only be true or false, according to the result of the comparison.
We may want to compare two expressions, for example, to know if they are equal or if
one is greater than the other. Here is a list of the relational operators that can be
performed in C++:
== Equal
!= Different
> Greater than
< Less than
7
>= Greater or equal than
<= Less or equal than
int a=5;
int b=7;
float a=5.0;
float b=7.0;
What is the result of:
a / b (=1)
a % b (=2)
a / d (=1.4)
c % d (=error)
c / d (=1.4)
The increment and decrement operators have two forms which have slightly different
effects: prefix and postfix:
Prefix form:
x = ++a;
y = --b;
Add/subtract one to/from the variable, then return the current value of the variable
Postfix form:
x = a++;
y = b--;
Return the current value then add/subtract one to/from the variable
Exercise on increment/decrement – what is the output of this program?
#include <iostream.h>
main () {
int a=10, b=10, x, y;
x = a++;
y = ++b;
cout << “a=” << a << endl;
cout << “b=” << b << endl;
cout << “c=” << c << endl;
cout << “d=” << d << endl;
}
Output: a = 11, b=11, x=10, y=11
Order of Precedence
Consider the following expression:
6 +3*4/2+2
A purely left-to-right evaluation will give a result of 20. But in C++, arithmetic operators
have an order of precedence
8
First: Increment, decrement
Second: Multiply, divide, modulo
Third: Addition, subtraction
So the correct result of the above expression is 14
If two or more operators have the same precedence, they are evaluated from left to right
Exercise
1. Write a C++ program which evaluates the result and remainder of the expression
„(2 + 3 * 3) / n‟, where n is an integer number entered by the user. The program
should use integer arithmetic to compute the result and should print out both the
result and the remainder.
2. Write a new program which reads in a floating point number from the user, and
then calculates and prints out the square root, the square and the cube of the
number (you can calculate the square root in C++ using the sqrt() function).
3. Write a c++ program which convert Dc to Df where dc=(5(df-32)) /9
4. What will be the output for this program
#include<iostream.h>
Void main() {
int x=5;
cout<<x++;
cout<<++x;
x+=3;
cout<<x++;
cout<<++x;
C=cout<<x;
}