0% found this document useful (0 votes)
3 views

Chapter 2

The document discusses the basics of C++ programming language including program compilation process, structure of a C++ program with examples, comments in C++, variables, data types and identifiers. It explains how a C++ program is compiled from source code to executable code and the typical elements and syntax of a simple C++ hello world program.

Uploaded by

Sam Ked
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 2

The document discusses the basics of C++ programming language including program compilation process, structure of a C++ program with examples, comments in C++, variables, data types and identifiers. It explains how a C++ program is compiled from source code to executable code and the typical elements and syntax of a simple C++ hello world program.

Uploaded by

Sam Ked
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 2

Basics of C++
2.1 C++ Program Compilation
Source code is entered with a text
Source Code editor by the programmer

Scans source code and searches for


Preprocessor
special lines that begin with # symbol.

Modified Source Code

Translate each source code instruction in


Compiler to appropriate machine language

Object Code

Combines the object code with necessary


Linker library routines. E.g.. Hardware specific
code for displaying message on screen or
reading input from keyboard
Executable Code
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2 Structure of C++ Program
// my first program in C++ Hello World!
#include <iostream.h>
int main ()
{
cout << "Hello World!";
return 0;
}

// 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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
#include <iostream.h>
Lines beginning with a hash sign (#) are directives for the preprocessor.

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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
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.
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:

Optionally, these parentheses may enclose a list of parameters within them.

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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
cout << "Hello World!";
This line is a C++ statement.
A statement is a simple or compound expression that can actually produce some
effect.

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.

C++ supports two ways to insert comments:

// 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.

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

/* my second program in C++


with more comments */
#include <iostream.h>
int main()
{
cout << "Hello World! "; // prints Hello
World!
cout << "I'm a C++ program"; // prints I'm
a C++ program
return 0;
}
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.2. Variables. Data Types.

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

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.
Variable identifiers always have to begin with a letter.
They can also begin with an underline (Underscore) 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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
Identifiesr
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:
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 and, and_eq, bitand, bitor, compl,
not, not_eq, or, or_eq, xor, xor_eq
June 2, 2024 Wolaita Sodo University, Department of CS & IT
Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
Identifiers
Very important:
The C++ language is a "case sensitive" language.
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 RESULT variable is not the same as the result variable or the
Result variable. These are three different variable identifiers.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.3. 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)

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.3. Fundamental data types
Name Description Size Range

char Character or small integer. 1byte signed: -128 to 127


unsigned: 0 to 255

short int(short) Short Integer. 2 byte signed: -32768 to 32767


unsigned: 0 to 65535

int Integer. 4 byte signed: -2147483648 to 2147483647


unsigned: 0 to 4294967295

long int (long) Long integer. 4 byte signed: -2147483648 to 2147483647


unsigned: 0 to 4294967295

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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.4. Declaration of variables
For example:

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:

unsigned short int NumberOfSisters;


signed int MyAccountBalance;

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…
2.2.4. Declaration of variables
For example:
// operating with variables
#include <iostream.h> 4
int main ()
{
// 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:
return 0;
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.5. Scope of variables

A variable can be either of global or local scope.


A global variable is a variable declared in the main body of the source code,
outside all functions,
while a local variable is one declared within the body of a function or a block.

Global Variables

Local Variables

Instructions

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.5. Scope of variables

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.

2.2.5. Initialization of variables

There are two ways to do this in C++:

The first one is done by appending an equal sign followed by the value to which the
variable will be initialized:

type identifier = initial_value ;

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.5. Initialization of variables

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;

The other way to initialize variables, known as constructor initialization, is done by


enclosing the initial value between parentheses (()):
type identifier(initial_value);
For example:
int a(0);

Both ways of initializing variables are valid and equivalent in C++.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.5. Initialization of variables


// initialization of variables
#include <iostream.h>
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.6. Introduction to strings

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> .

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2 Structure of C++ Program cont…

2.2.6. Introduction to strings

// my first string
#include<iostream.h>
#include<string.h>
int main()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

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
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. Constants

2. Declared constants (const)

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

const int pathwidth = 100;


const char tabulator = '\t';

Here, pathwidth and tabulator are two typed constants.

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.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. BASIC INPUT/OUTPUT

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++

2.2.7. BASIC INPUT/OUTPUT

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:

cin >> a >> b; cin >> a;


This is equivalent to:
cin >> b;

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. BASIC INPUT/OUTPUT

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;
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

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.

Unary operators only require a single operand. For example -5

Binary operators work with two operands. The assignment operator is in this category.

Ternary operators require three operands. C++ only has one ternary operator.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. Operators

Arithmetic Operators

The following table shows the common arithmetic operators in C++.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. Operators

Combined Assignment Operators


Quite often programs have assignment statements of the following form:
number = number + 1;
On the right-hand side of the assignment operator, 1 is added to number.
The result is then assigned to number, replacing the value that was previously stored
there.
Fore example (Assume x=6)

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. Operators

Combined Assignment 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

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++

2.2.7. Operators

Combined Assignment Operators

Examples Using Combined Assignment Operators and Arithmetic Operators

Is Equivalent to

Is Equivalent to

Is Equivalent to

Is Equivalent to

Is Equivalent to

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
Relational Operators

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.

•This table lists all of C++’s


relational operators.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
Relational Operators

Fore example (Assume x is 10 and y is 7.)

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
Logical Operators

Logical operators connect two or more relational expressions into one


or reverse the logic of an expression.

The following table lists C++’s logical operators.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
The && Operator

The && operator is known as the logical AND operator.


It takes two expressions as operands and creates an expression that is true only
when both sub-expressions are true.
Here is an example of an if statement that uses the && operator:
if (temperature < 20 && minutes > 12)
cout << "The temperature is in the danger zone.";

Truth table for the && operator

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
The || Operator

The || operator is known as the logical OR operator. It takes two expressions as


operands and creates an expression that is true when either of the sub expressions
are true.
Here is an example of an if statement that uses the || operator:
if (temperature < 20 || temperature > 100)
cout << "The temperature is in the danger zone.";

Truth table for the || operator

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
The ! Operator

The ! operator performs a logical NOT operation. It takes an operand and reverses
its truth or falsehood.

Here is an if statement using the ! operator:

if (!(temperature > 100))


cout << "You are below the maximum temperature.\n";

Truth table for the ! operator

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
The Increment and Decrement Operators

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

And the following statement decrements 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 .

Notice the difference:

Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
//A contains 4, B contains 4 //A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A.

While in Example 2, the value of B is copied to A and then B is increased.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
Conditional operator ( ? )

The conditional operator evaluates an expression returning a value if that


expression is true and a different one if the expression is evaluated as false.

Its syntax is:

condition ? result1 : result2


If condition is true the expression will return result1, if it is not it will return result2.

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;
}

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE

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

2 &* Reference and Dereference Right


(pointers)
(type) Type casting
+- Unary plus and minus

3 */% arithmetical operations Left

4 +- arithmetical operations Left

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):

multiplication, division, and modulus operators have the same precedence.


This is also true of the addition and subtraction operators.

June 2, 2024 Wolaita Sodo University, Department of CS & IT


Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE

Fore example

Associativity is the order in which an operator works with its operands.


Associativity is either left to right or right to left.

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!

June 2, 2024 Wolaita Sodo University, Department of CS & IT

You might also like