Chapter 2-C++ Basics
Chapter 2-C++ Basics
C++ began as an expanded version of C. The C++ extensions were first invented by
Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially
called the new language "C with Classes." However, in 1983 the name was changed to
C++. C++ allows programmers to comprehend and manage larger, more complex
programs because it includes Object Oriented features.
C++ is a high-level language: when you write a program in it, the short hands are
sufficiently expressive that you don’t need to worry about the details of processor
instructions.
C++ is a cross-platform language that can be used to create high-performance
applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and
memory.
The first of them, known as single 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
1
Programming I 2023
The above example program has been structured in different lines in order to be more
readable, but in C++, we do not have strict rules on how to separate instructions in
different lines. For example, we could write the above program as:
int main () { cout << "Hello World!"; return 0; }
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:
I/O streams
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. A stream is an object where a
program can either insert or extract characters to/from it. The standard C++ library
includes the header file iostream, where the standard input and output stream objects are
declared.
1
Programming I 2023
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):
cout << "First sentence.\n ";
cout << "Second sentence.\nThird sentence.";
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:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
Would print out:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n' does.
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:
int age;
cin >> age;
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 Enter 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 Enter 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
1
Programming I 2023
You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and another one for variable
b that may be separated by any valid blank separator: a space, a tab character or a
newline.
Debugging
A mistake in a program is called a bug. For this reason, the process of eliminating
mistakes in your program is called debugging. Debugging is the process of correcting
errors from the program via testing. There are three commonly recognized types of bugs
or errors, which are known as syntax errors, run-time errors, and logic errors.
A syntax error is a grammatical mistake in your program; that is, a mistake in the
allowed arrangement of words and punctuations. If you violate one of these rules-for
example, by omitting a required punctuation-it is a syntax error. The compiler will catch
syntax errors and output an error message telling you that it has found the error, where it
thinks the error is, and what it thinks the error is. If the compiler says you have a syntax
error, you undoubtedly do. However, the compiler could be incorrect about where and
what the error is.
An error that is not detected until your program is run is called a run-time error. If the
computer detects a run-time error when your program is run, then it will output an error
message. The error message may not be easy to understand, but at least it lets you know
that something is wrong. For example, division by zero: If there is any place(instruction )
which attempts to any number by zero, this error will not be syntax error instead runtime
error.
1
Programming I 2023
2.4.2. Keywords
1
Programming I 2023
Variable Names
1
Programming I 2023
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 has 8 bits.
C++ supports a variety of data types and the programmer can choose the type to the
needs of the application. The basic data types in C++ are the following:
Character denoted by char is the data type that holds an integer value
corresponding to the representation of an element of the ASCII character set.
Integer denoted by int is the data type that holds an integer value or whole number.
Real denoted by:
o float is the data type that holds single precision floating point value or real
number.
o double is the data type that holds a double precision floating point value or
real number.
Boolean denoted by bool is the data type that holds a Boolean value of true or false.
The basic data types byte size are as follows:
char takes 1 byte double takes 8/10 bytes depending on
int takes 2/4 bytes depending on the the compiler
compiler bool takes 1 byte
float takes 4 bytes
1
Programming I 2023
Variable Declaration/Definition
A declaration of a variable is a statement that gives information about the variables to the
C++ compiler. A variable must be defined before using it in a program. It reserves
memory required for data storage and associates it with a symbolic name. The syntax for
defining a variable is:
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:
int a;
int b;
int c;
Initialization of variables
In C++, a variable can be assigned with a value during its definition or during the
execution of the program. The assignment operator (=) used in both cases. The syntax for
variable initialization during its definition:
int a = 0;
When multiple variables are being declared in a single statement, initialization is carried
out in the following way:
Data type variable name1 = value1, variable name2 = value2,…, variable nameN = valueN;
Example:
int i=10,j=5,k=8;
i. Arithmetic Operators
C++ provides five basic arithmetic operators that are summarized in Table 2.3.
1
Programming I 2023
% Remainder 13 % 3 // gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of integer and
real operands. Generally, if both operands are integers then the result will be an integer.
However, if one or both of the operands are reals then the result will be a real (or double
to be exact).
When both operands of the division operator (/) are integers then the division is
performed as an integer division and not the normal division we are used to. Integer
division always results in an integer outcome (i.e., the result is always rounded down).
For example:
9/2 // gives 4, not 4.5!
It is possible for the outcome of an arithmetic operation to be too large for storing in a
designated variable. This situation is called an overflow. The outcome of an overflow is
machine-dependent and therefore undefined. It is illegal to divide a number by zero. This
results in a run-time division-by-zero failure, which typically causes the program to
terminate.
1
C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
1
Programming I 2023
The assignment operator has a number of variants, obtained by combining it with the
arithmetic operators
Operator Example Equivalent To
(Table 2.6).
= n = 25
+= n + = 25 n = n + 25
-= n - = 25 n = n - 25
*= n * = 25 n = n * 25
/= n / = 25 n = n / 25
1
%= n %= 25 n = n % 25
Programming I 2023
() Parentheses
[] array subscript
++ Unary post increment left to right
-- unary post decrement
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
< relational less than relational less left to right
< than or equal to relational greater
=> than relational greater than or
>= equal to
== relational is equal to relational is
!= not equal to
= assignment right to left
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment
Table 2.8: Operator Precedence Levels
For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then
added to b because + has a higher precedence than ==, and then == is evaluated.
Precedence rules can be overridden using brackets. For example, rewriting the above
expression as
a == (b + c) * d
causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the last
column of Table 2.8.
For example, in
a = b += c
1
Programming I 2023