Chapter 2
Chapter 2
Basics of C++
2.1 C++ Program Compilation
Source code is entered with a text
Source Code editor by the programmer
Object Code
In this case the directive #include <iostream.h> tells the preprocessor to include the
iostream.h 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.
The word main is followed in the code by a pair of parentheses (()). That is because it is a
function declaration:
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
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).
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
return 0;
The return statement causes the main function to finish.
This is the most usual way to end a C++ console program.
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.1. 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.
// line comment
/* block comment */
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.
a = 5;
b = 2;
a = a + 1;
result = a - b;
this is a very simple example since we have only used two small integer values, but
consider that your computer can store millions of numbers like these at the same
time and conduct sophisticated mathematical operations with them.
Therefore, we can define a variable as a portion of memory to store a determined
value. In programming a variable is a named storage location for holding data.
Variables allow you to store and work with data in the computer’s memory. Part of
the job of programming is to determine how many variables a program will need
and what type of information each will hold.
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,
June 2, 2024 Wolaita Sodo University, Department of CS & IT
June 2, 2024 Wolaita Sodo University, Depatrment of CS
& IT
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
Identifiers
Thus, for example, the RESULT variable is not the same as the result variable or the
Result variable. These are three different variable identifiers.
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)
Boolean Boolean value. It can take one of two 1 byte true or false
values: true or false.
float Floating point number. 4 byte +/- 3.4e +/- 38 (~7 digits)
June double
2, 2024 Double precision floating point 8 byte +/- 1.7eSodo
Wolaita +/- 308 (~15 digits)
University, Department of CS & IT
number.
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.4. 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 desired data
type (like int, bool, float...) followed by a valid variable identifier.
For example:
int a;
float mynumber;
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.
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.
int a, b, c;
This declares three variables (a, b and c), all of them of type int, and has exactly
the same meaning as:
int a;
int b;
int c;
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
signed or the specifier unsigned before the type name. For example:
Global Variables
Local Variables
Instructions
Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where
they are declared.
The first one is done by appending an equal sign followed by the value to which the
variable will be initialized:
For example,
if we want to declare an int variable called a initialized with a value of 0 at the
moment in which it is declared, we could write:
int a = 0;
Variables that can store non-numerical values that are longer than one single
character are known as strings.
The C++ language library provides support for strings through the standard string
class. This is not a fundamental type, but it behaves in a similar way as
fundamental types do in its most basic usage.
A first difference with fundamental data types is that in order to declare and use
objects (variables) of this type we need to include an additional header file in our
source code: <string.h> .
// my first string
#include<iostream.h>
#include<string.h>
int main()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
2.2.7. Constants
for example:
// defined constants: calculate circumference
#include <iostream.h>
#define PI 3.14159
#define NEWLINE '\n'
int main()
{
double r=5.0; // radius double circle;
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0; 31.4159
}
2.2.7. Constants
With the const prefix you can declare constants with a specific type in the
same way as you would do with a variable:
For example
They are treated just like regular variables except that their values cannot be
modified after their definition.
The biggest difference is that this constant has a type, and the compiler can
enforce that it is used according to its type.
In the iostream C++ library, standard input and output operations for a
program are supported by two data streams: cin for input and cout for output.
Output (cout)
The cout stream is used in conjunction with the overloaded operator <<
(a pair of "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of variable x on screen
The insertion operator (<<) may be used more than once in a same sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
Hello, I am a C++ sentence
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
Input (cin)
Handling the standard input in C++ is done by applying the overloaded operator of
extraction (>>) on the cin stream.
This must be followed by the variable that will store the data that is going to be read.
For example:
int age;
cin >> age;
declares the variable age as an int and then waits for an input from cin (keyborad) in
order to store it in this integer variable.
You can also use cin to request more than one datum input from the user:
Fore example
// i/o example
#include <iostream.h>
int main ()
{ int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;
}
2.2.7. Operators
Generally, there are three types of operators: unary, binary, and ternary. These
terms reflect the number of operands an operator requires.
Binary operators work with two operands. The assignment operator is in this category.
Ternary operators require three operands. C++ only has one ternary operator.
2.2.7. Operators
Arithmetic Operators
2.2.7. Operators
2.2.7. Operators
C++ offers a special set of operators designed specifically for these jobs.
The following table shows the combined assignment operators, also known as
compound operators or arithmetic assignment operators.
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
2.2.7. Operators
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Is Equivalent to
Relational operators allow you to compare numeric values and determine if one is
greater than, less than, equal to, or not equal to another.
Relational expressions are Boolean expressions, which means their value can only
be true or false.
All of the relational operators are binary. I.e. they use two operands.
The ! operator performs a logical NOT operation. It takes an operand and reverses
its truth or falsehood.
C++ provides a set of simple unary operators designed just for incrementing and
decrementing variables.
The increment operator is ++ .
The decrement operator is --.
The following statement uses the ++ operator to increment num:
num++; //is equvalent to num=num+1
The above examples so far show the increment and decrement operators used in
postfix mode, which means the operator is placed after the variable.
The operators also work in prefix mode, where the operator is placed before the
variable name:
++num;
--num;
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2.7. Operators
The postfix and perfix may have an important difference in their meaning:
In the case that the increase operator is used as a prefix (++a) the value is
increased before the result of the expression is evaluated
in case that it is used as a postfix (a++) the value stored in a is increased after
being evaluated .
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
//A contains 4, B contains 4 //A contains 3, B contains 4
Example
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2.7. Operators
Conditional operator ( ? )
Example
// conditional operator
#include <iostream>
int main () 7
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
When making complex expressions with several operands, we may have some
doubts about which operand is evaluated first and which later.
For example, in this expression:
a = 5 + 7 % 2
we may doubt if it really means:
a = 5 + (7 % 2) with result 6, or
a = (5 + 7) % 2 with result 0
The correct answer is the first of the two expressions, with a result of 6..
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE
There is an established order with the priority of each operators which can appear in C++.
From greatest to lowest priority, the priority order is as follows:
Priority Operator Description Associativity
1 :: scope Left
1 () [ ] -> . sizeof Left
++ -- increment/decrement
! unary NOT
June 2, 2024 5 < <= > >= Relational operators Left Department of CS & IT
Wolaita Sodo University,
Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE
The following table shows the precedence of the arithmetic operators.
The operators at the top of the table have higher precedence than the ones below it (Highest
to Lowest):
Fore example
The associativity of the division operator is left to right, so it divides the operand
June 2, 2024 on its left by the operand on its right. Wolaita Sodo University, Department of CS & IT
Thank you!