0% found this document useful (0 votes)
7 views71 pages

Chapter 2 Basics C++ 11

The document provides an overview of the basics of C++ programming, including the compilation process, structure of a C++ program, comments, variables, data types, and constants. It explains how to declare and initialize variables, the importance of the main function, and the use of standard input-output libraries. Additionally, it covers the concept of identifiers and their rules, as well as the distinction between global and local variables.

Uploaded by

haileslassiet28
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)
7 views71 pages

Chapter 2 Basics C++ 11

The document provides an overview of the basics of C++ programming, including the compilation process, structure of a C++ program, comments, variables, data types, and constants. It explains how to declare and initialize variables, the importance of the main function, and the use of standard input-output libraries. Additionally, it covers the concept of identifiers and their rules, as well as the distinction between global and local variables.

Uploaded by

haileslassiet28
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/ 71

Basics of C++

C++ Program Compilation


Source code is entered with a
Source Code text editor by the programmer

Scans source code and


Preprocessor
searches for special lines that
begin with # symbol.
Modified Source
Code

Translate each source code


Compiler instruction in to appropriate
machine language

Object Code

Combines the object code with


Linker necessary library routines. E.g..
Hardware specific code for
Executable displaying message on screen or
Code reading input from keyboard
March 1, 2025 Mekelle University, Department of CS
Basics of C++
2.2 Structure of C++ Program
// my first program in C++
Hello World!
#include <iostream>
using namespace std;
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.
March 1, 2025 Mekelle University, Department of CS
Basics of C++
2.2 Structure of C++ Program cont…
#include <iostream>
Lines beginning with a hash sign (#) are directives for the
preprocessor.
In this case the directive #include <iostream> tells the preprocessor to
include the iostream 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.
using namespace std;
All the elements of the standard C++ library are declared within what is
called a namespace, the namespace with the name std. So in order to
access its functionality we declare with this expression that we will be
using these entities.
March 1, 2025 Mekelle University, Department of CS
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.
March 1, 2025 Mekelle University, Department of CS
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.

March 1, 2025 Mekelle University, Department of CS


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.
March 1, 2025 Mekelle University, Department of CS
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>
using namespace std;
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++ program
return 0;
}

March 1, 2025 Mekelle University, Department of CS


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.

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,

March 1, 2025 Mekelle University, Department of CS


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.
March 1, 2025 Mekelle University, Department of CS
Basics of C++
2.2 Structure of C++ Program cont…
Identifiers
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.
Theauto,
asm, standard reserved
bool, break,keywords are:
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
March 1, 2025 Mekelle University, Department of CS
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.
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.

March 1, 2025 Mekelle University, Department of CS


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

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)

March 1, 2025 Mekelle University, Department of CS


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
bool Boolean value. It can take 1 byte true or false
one of two values: true or
false.
float Floating point number. 4 byte +/- 3.4e +/- 38 (~7 digits)

double Double precision floating 8 byte +/- 1.7e +/- 308 (~15 digits)
point number.
long double Long double precision 10 +/- 1.7e +/- 308 (~15 digits)
floating point number. byte
March 1, 2025
wchar_t Wide character. 2 0r 4 Mekelle
1 wideUniversity,
characterDepartment of CS
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

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.

March 1, 2025 Mekelle University, Department of CS


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;

March 1, 2025 Mekelle University, Department of CS


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> 4
using namespace std;
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;
}

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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

When declaring a regular local variable, its value is by default


undetermined. But you may want a variable to store a concrete
value at the same moment that it is declared.
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 ;

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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

2.2.5. Initialization of variables


// initialization of variables
#include <iostream>
using namespace std;
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;
}

March 1, 2025 Mekelle University, Department of CS


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> and have
access to the std namespace

March 1, 2025 Mekelle University, Department of CS


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

2.2.6. Introduction to strings

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

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++

2.2.7. Constants

Constants are expressions with a fixed


value
Constants store concrete value, hence must be initialized when
they are created
C++ has two types of constants: Literal and Symbolic

A. Literal Constants
A value typed directly into your program whenever it is needed
For example
int myAge = 39;
myAge is a variable of type int; 39 is a literal constant.
You can't assign a value to 39, and its value can't be
changed.
Literal constants can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++

2.2.7. Constants

B. Symbolic Constants
A symbolic constant is a constant that is represented by a name, just as a
variable is represented.

Unlike a variable, however, after a constant is initialized, its value can't be


changed.
There are two ways to declare a constant in C++

1. Defining Constants with #define


The classical and now obsolete way is with a preprocessor directive,
#define.
Its syntax is:
#define identifier value
For example:

#define PI 3.14159
#define NEWLINE '\n'

This defines two new constants: PI and NEWLINE. Once they are defined,
you can use them in the rest of the code as if they were any other regular
constant,
March 1, 2025 Mekelle University, Department of CS
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;

circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;

return 0; 31.415
} 9

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++

2.2.7. Constants

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.

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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
You can also use
cin (keyborad) in cin to to
order request more
store it than
in this one datum
integer input from
variable.
the user:
This is equivalent cin >> a;
cin >> a >> b; to: cin >> b;

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++

2.2.7. Operators

Arithmetic Operators

The following table shows the common arithmetic


operators in C++.

March 1, 2025 Mekelle University, Department of CS


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)

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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.

March 1, 2025 Mekelle University, Department of CS


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

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

March 1, 2025 Mekelle University, Department of CS


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.

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


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;
March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
2.2.7. Operators
The postfix and suffix 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 suffix (a++) the value stored in a is


increased after being evaluated .

Example
Notice1 the difference: 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.
March 1, 2025 Mekelle University, Department of CS
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.

March 1, 2025 Mekelle University, Department of CS


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

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.2.7. Operators

sizeof()

This operator accepts one parameter, which can be either a type


or a variable itself and returns the size in bytes of that type or
object:

a = sizeof (char);

This will assign the value 1 to a because char is a one-byte long


type.

The value returned by sizeof is a constant, so it is always


determined before program execution.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.2.7. Operators
Explicit type casting operator

Type casting operators allows you to convert a datum of a given type


to another.

For example:
int i;
float f = 3.14;
i = (int) f;

The type casting operator (int) converts the float number 3.14 to an
integer value 3.

March 1, 2025 Mekelle University, Department of CS


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
March correct
1, 2025 answer is the first of the two expressions,
Mekelle University, with a result
Department of CS
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:
Associativit
Priority Operator Description
y
1 :: scope Left
1 () [ ] -> . sizeof Left
++ -- increment/decrement
! unary NOT
Reference and
2 &* Right
Dereference (pointers)
(type) Type casting
+- Unary plus and minus
3 */% arithmetical operations Left
4 +- arithmetical operations Left
5 < <= > >= Relational operators Left
6 == != Relational operators Left
7 && || Logic operators Left
8 ?: Conditional Right
= += -= *= /= %=
9 Assignment Right
March 1, 2025 >>= <<= &= ^= |= Mekelle University, Department of CS
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.

March 1, 2025 Mekelle University, Department of CS


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


March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
2.2.7. Operators
OPERATOR PRECEDENCE

Grouping with Parentheses

Parts of a mathematical expression may be grouped with


parentheses to force some operations to be performed before
others.
example:
a = 5 + 7 % 2;
might be written as:
a = 5 + (7 % 2); or
a = (5 + 7) % 2;

So if you want to write a complicated expression and you are not


sure of the precedence levels, always include parenthesis.

In the following statement, the sum of a, b, c, and d is divided by 4.


average = (a + b + c + d) / 4;
Without the parentheses, however, d would be divided by 4 and the
result added to a, b, and c.
March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
2.2.7. Operators
Converting Algebraic Expressions to Programming
Statements
In algebra it is not always necessary to use an operator for
multiplication. C++, however, requires an operator for any
mathematical operation.

When converting some algebraic expressions to C++, you may


have to insert parentheses that do not appear in the algebraic
expression.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.2.7. Operators
Converting Algebraic Expressions to Programming
Statements
Fore Example

y=(3*x)/2 or y= (3/2)*x

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.2.7. Operators
Converting Algebraic Expressions to Programming
Statements
C++ does not have an exponent operator.
Raising a number to a power requires the use of a library
function.
One of the library functions is called pow, and its purpose is
to raise a number to a power.
Example
area = pow(4, 2);
pow always raises the first argument to the power of the
Note that you should include the library <math.h> whenever
second argument
you want apply the function pow or some other related
mathematical functions in your program code

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.8. TYPE CONVERSION
Explicit Type Conversion

Type casting operators allows you to convert a datum of a


given type to another.
The first way to do this in C++ is to precede the expression
to be converted by the new type enclosed between
parenthesis ():
int i;
float f = 3.14;
i = (int) f;

Another way to do the same thing in C++ is using the


constructor form: preceding the expression to be converted
by the type and enclosing the expression between
parenthesis:

i = int ( f );

Both ways of type casting are valid in C++.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.8. TYPE CONVERSION

Implicit Type Conversion

When an operator’s operands are of different data types, C++


will automatically convert them to the same data type.

When a value is converted to a higher data type, it is said to be


promoted.
To demote a value means to convert it to a lower data type.

C++ follows a set of rules when performing mathematical


operations on variables of different data types.

Let’s look at the specific rules that govern the evaluation of


mathematical expressions.

Rule 1: char, short, and unsigned short are automatically


promoted to int.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.8. TYPE CONVERSION
Implicit Type Conversion
Rule 2: When an operator works with two values of
different data types, the lower-ranking value is promoted
to the type of the higher-ranking value.

Example: assume that years is an int and interestRate is a


double:

years * interestRate

Before the multiplication takes place, years will be promoted to a


double.

Rule 3: When the final value of an expression is assigned


to a variable, it will be converted to the data type of that
variable.

Fore example:
int x, y = 4;
double
March 1, 2025 z = 2.7; Mekelle University, Department of CS
Chapter 2
Basics of C++
2.8. TYPE CONVERSION
Implicit Type Conversion
Fore example:
// shows mixed expressions
#include <iostream.h>
int main()
{
int count = 7;
float avgWeight = 155.5F;
double totalWeight = count * avgWeight;
cout << “totalWeight=” << totalWeight << endl;
return 0;
}

The int value of count is converted to type float and stored in a


temporary variable before being multiplied by the float variable
avgWeight.

The result (still of type float) is then converted to double so that


it can be assigned to the double variable totalWeight.
This
March process is shown in the following figure
1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
Implicit Type Conversion

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.8. TYPE CONVERSION
Implicit Type Conversion
The following lists the data types in order of their rank, from
highest to lowest.

long double
double
float
unsigned long
long
unsigned int
int
short
char

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
The setw Manipulator
manipulators are operators used with the insertion operator (<<)
to modify— or manipulate—the way data is displayed.

For example the endl causes a linefeed to be inserted into the


stream, so that subsequent text is displayed on the next line.

It has the same effect as sending the ‘\n’ character, but is


somewhat clearer.

Example;

#include <iostream.h> //for cout, etc.


void main()
{
float rad; //variable of type float
const float PI = 3.14159F; //type const float
cout << “Enter radius of circle: “; //prompt
cin >> rad; //get radius
float area = PI * rad * rad; //find area
cout <<“Radius is”<<rad<<endl<<“PI is”<<PI<<endl<<
“Area is “ << area << endl; //display
March 1, 2025
answer
Mekelle University, Department of CS
Chapter 2
Basics of C++
The setw Manipulator
Setw changes the field width of output.

You can think of each value displayed by cout as occupying a


field: an imaginary box with a certain width.

The default field is just wide enough to hold the value.


That is, the integer 567 will occupy a field three characters wide,
and the string “programming” will occupy a field eleven
characters wide.

However, in certain situations this may not lead to optimal


results.

Here’s an example.

The WIDTH1 program prints the names of three cities in one


column, and their populations in another.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
The setw Manipulator
// width1.cpp
// demonstrates need for setw manipulator
#include <iostream.h>
int main()
{
long pop1=2425785, pop2=47, pop3=9761;
cout << “LOCATION “ << “POP.” << endl
<< “Portcity “ << pop1 << endl
<< “Hightown “ << pop2 << endl
<< “Lowville “ << pop3 << endl;
return 0;
}

Here’s the output from this program:

LOCATION POP.
Portcity 2425785
Hightown 47
Lowville 9761

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
The setw Manipulator
Unfortunately, this format makes it hard to compare the
numbers;

it would be better if they lined up to the right.

Also, we had to insert spaces into the names of the cities to


separate them from the numbers. This is an inconvenience.

Here’s a variation of this program, WIDTH2, that uses the setw


manipulator to eliminate these problems by specifying field
widths for the names and the numbers:

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
The setw Manipulator
// width2.cpp
// demonstrates setw manipulator
#include <iostream.h>
#include <iomanip.h> // for setw
int main()
{
long pop1=2425785, pop2=47, pop3=9761;
cout << setw(8) << “LOCATION” << setw(12)
<< “POPULATION” << endl
<< setw(8) << “Portcity” << setw(12) << pop1 << endl
<< setw(8) << “Hightown” << setw(12) << pop2 << endl
<< setw(8) << “Lowville” << setw(12) << pop3 << endl;
return 0;
}

The setw manipulator causes the number (or string) that follows
it in the stream to be printed within a field n characters wide,
where n is the argument to setw(n).

The value is right justified within the field.


March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
The setw Manipulator
The following figure shows how this looks.

Type long is used for the population figures, which prevents a


potential overflow problem on systems that use 2-byte integer
types, in which the largest integer value is 32,767.
March 1, 2025 Mekelle University, Department of CS
Chapter 2
Basics of C++
The setw Manipulator
Here’s the output of WIDTH2:

LOCATION POPULATION
Portcity 2425785
Hightown 47
Lowville 9761

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
Example
The following asks the user for a temperature in degrees
Fahrenheit, converts it to Celsius, and displays the result.
// fahren.cpp, demonstrates cin, newline
#include <iostream.h>
int main()
{
int ftemp; //for temperature in fahrenheit
cout << “Enter temperature in fahrenheit: “;
cin >> ftemp;
int ctemp = (ftemp-32) * 5 / 9;
cout << “Equivalent in Celsius is: “ << ctemp << ‘\n’;
return 0;
}

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.9 PROGRAMMING ERRORS

There are three types of programming errors:

Design errors
occur during the analysis, design, and implementation phases.

Design errors are usually difficult to detect.

Debugging them requires careful review of problem analysis,


algorithm design, translation, and test data.

Syntax Errors

are violations of syntax rules, which define how the elements of a


programming language must be written.

Depending on how serious the violation is, the diagnostic


message may be a warning message or an error message.

March 1, 2025 Mekelle University, Department of CS


Chapter 2
Basics of C++
2.9 PROGRAMMING ERRORS

A warning message indicates a minor error that may lead to a


problem during program execution.
These errors do not cause the termination of the compilation
process

If the syntax violation is serious, the compiler stops the


compilation process and produces error messages,

Run-time Errors

are detected by the computer while your program is being


executed.

When a run-time error is encountered, the computer produces an


error message and terminates the program execution.

March 1, 2025 Mekelle University, Department of CS


Thank
you!

March 1, 2025 Mekelle University, Department of CS

You might also like