SlideShare a Scribd company logo
1 of 80
Chapter Two
BASIC CONCEPTS OF C++ PROGRAMMING
Structure of a C++ program
// my first program in C++
#include <iostream>
Using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Chapter 2: Basic Concepts of C++ Programming 2
OUTPUT
Hello World!
 This program includes the basic components that
every C++ program has
COMMENTS
 Comments are pieces of source code discarded from the
code by the compiler.
 They are used to insert notes or descriptions.
 C++ supports two ways to insert comments:
◦ // line comment
◦ /* block comment */
 The Line comment, discards everything from where the
double slash signs (//) is found up to the end of that same
line.
 The Block comment, discards everything between the /*
characters and the next appearance of the */ characters,
with the possibility of including several lines.
Chapter 2: Basic Concepts of C++ Programming 3
Example of Comments
/* my second program in C++ with more
comments */
#include <iostream.h>
int main ()
{
cout << "Hello World! "; // shows Hello World!
cout << “A C++ program";// shows A C++ program
return 0;
}
Chapter 2: Basic Concepts of C++ Programming 4
DATA TYPES
 There are many different types of data.
◦ In the realm of numeric information, for example,
there are whole numbers and fractional
numbers.
◦ There are negative numbers and positive
numbers.
◦ And there are numbers so large, and others so
small, that they don’t even have a name.
◦ Then there is textual information. Names and
addresses, for instance, are stored as groups of
characters.
Chapter 2: Basic Concepts of C++ Programming 5
Data Types
 C++ offers two very broadest data types:
◦ numeric and
◦ character.
 Numeric data types are broken into two additional
categories:
◦ integer and
◦ floating-point.
 Integers are whole numbers like 12, 157, –34, and 2.
 Floating-point numbers have a decimal point, like 23.7,
189.0231, and 0.987.
 Additionally, the integer and floating point data types are
broken into even more classifications.
Chapter 2: Basic Concepts of C++ Programming 6
Integer Data Types
 Includes
◦ short
◦ unsigned short
◦ Int
◦ unsigned int
◦ Long
◦ unsigned long
data types
Chapter 2: Basic Concepts of C++ Programming 7
Floating-Point Data Types
 Are data type that allows fractional values.
◦ If you are writing a program that works with dollar
amounts or precise measurements you need floating
point data types
 In C++ there are three data types that can
represent floating-point numbers.
 They are
◦ float
◦ double
◦ long double
Chapter 2: Basic Concepts of C++ Programming 8
Floating-Point Data Types
 Internally, floating-point numbers are stored in a manner
similar to scientific notation.
◦ In scientific notation the number 47,281.97 is 4.728197x104.
 Computers typically use E notation to represent floating-point
values.
◦ In E notation, the number 47,281.97 would be 4.728197E4. The part of
the number before the E is the mantissa, and the part after the E is the
power of 10.
 The following table shows other numbers represented in
scientific and E notation.
Chapter 2: Basic Concepts of C++ Programming 9
Char Data Type
 A char variable (used to hold characters) is most often one byte
long.
Chapter 2: Basic Concepts of C++ Programming 10
Size of Data Types
 The size of a variable is the number of bytes of
memory it uses.
 Our computer's memory is organized in bytes.
 A byte is the minimum amount of memory that
we can manage.
 A byte can store an integer 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.
Chapter 2: Basic Concepts of C++ Programming 11
List of the existing fundamental data types in C++
Name Bytes* Description Range*
char 1 character or integer 8 bits length.
signed: -128 to 127
unsigned: 0 to 255
short 2 integer 16 bits length.
signed: -32768 to 32767
unsigned: 0 to 65535
long 4 integer 32 bits length.
signed:-2147483648 to
2147483647
unsigned: 0 to 4294967295
int *
Integer. Its length traditionally
depends on the length of the
system's Word type, 2 (4) bytes.
See short, long
float 4 floating point number. 3.4e + / - 38 (7 digits)
double 8
double precision floating point
number.
1.7e + / - 308 (15 digits)
long double 10
long double precision floating point
number.
1.2e + / - 4932 (19 digits)
Chapter 2: Basic Concepts of C++ Programming 12
Variables
 You can use variables to store values and you can perform any
mathematical operation on those variables
 This can be expressed in C++ with the following instruction set:
◦ a = 5;
◦ b = 2;
◦ a = a + 1;
◦ result = a - b;
Chapter 2: Basic Concepts of C++ Programming 13
Declaration of variables
 In order to use a variable in C++, we must first declare it
 The syntax to declare a new variable is:
◦ data type specifier (like int, short, float...) followed by a
valid variable identifier.
 For example:
int a;
float mynumber;
// Are valid declarations of variables.
Chapter 2: Basic Concepts of C++ Programming 14
….Declaration of variables
 You can declare all of the variables of the same
data type 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;
Chapter 2: Basic Concepts of C++ Programming 15
Examples on operating with variables
Example-1
// operating with variables
int main ()
{
int a, b, result;
a = 5;
b = 2;
a = a + 1;
result = a - b;
cout << result; // print out the result
return 0; // terminate the program
}
Chapter 2: Basic Concepts of C++ Programming 16
Output
4
Example-2
 // a C++ program with a variable
int main()
{
int number;
number = 5;
cout << "The value of number is " << "number" << endl;
cout << "The value of number is " << number << endl;
number = 7;
cout << "Now the value of number is " << number << endl;
return 0;
}
Output
The value of number is number
The value of number is 5
Now the value of number is 7
Chapter 2: Basic Concepts of C++ Programming 17
Initialization of variables
 To make a variable to store a concrete value the moment
that it is declared, append an equal sign followed by the
value.
type identifier = initial_value ;
 For example:
int number = 5;
 Here is the other way:
int number;
number = 5; // this line is an assignment.
 The = sign is an operator that copies the value on its right
(5) into the variable named on its left (number).
Chapter 2: Basic Concepts of C++ Programming 18
CONSTANTS
 A constant is any expression that has a fixed value.
 You must initialize a constant when you create it,
◦ and you cannot assign a new value later.
 C++ has two types of constants:
◦ literal and
◦ symbolic.
Chapter 2: Basic Concepts of C++ Programming 19
1. Literal Constants
 A literal constant is a value typed directly into your
program.
 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.
 They can be divided in Integer Numbers, Floating-
Point Numbers, Characters and Strings.
Chapter 2: Basic Concepts of C++ Programming 20
Integer and Floating Point Constants
 Values 1776, 707, -273 are numerical constants
that identify integer numbers.
 Floating Point constants express numbers with
decimals and/or exponents.
 They can include a decimal point:
◦ 3.14159 // 3.14159
◦ 6.02e23 // 6.02 x 1023
◦ 1.6e-19 // 1.6 x 10-19
◦ 3.0 // 3.0
Chapter 2: Basic Concepts of C++ Programming 21
Characters and strings
 There also exist non-numerical constants, like:
◦ 'z', // single character
◦ 'p', // single character
◦ "Hello world", // strings of several characters
◦ "How do you do?". // strings of several characters
 Notice that:
◦ to represent a single character we enclose it between
single quotes (') and
◦ to express a string of more than one character we enclose
them between double quotes (").
 Notice this: x and 'x'. Here,
◦ x refers to variable x, whereas
◦ 'x' refers to the character constant 'x'.
Chapter 2: Basic Concepts of C++ Programming 22
2. Symbolic Constants
 A symbolic constant is a constant that is represented by a name.
 There are two ways to declare a symbolic constant in C++.
◦Defining Constants with #define
E.g. #define studentsPerClass 15
◦Defining Constants with const
E.g. const unsigned short int studentsPerClass = 15;
Chapter 2: Basic Concepts of C++ Programming 23
…Symbolic Constants
 For example:
◦ If your program has two integer variables named
students and classes, you could compute how many
students you have, given number of classes, if you know
there were 15 students per class:
students = classes * 15;
 In this example, 15 is a literal constant.
 If you substituted a symbolic constant for this
value:
students = classes * studentsPerClass
Chapter 2: Basic Concepts of C++ Programming 24
IDENTIFIERS
 An identifier is a programmer-defined name that
represents some element of a program.
◦ Variable names are examples of identifiers.
 A valid identifier is a sequence of one or more letters,
digits or underscore( _ ).
 Neither spaces nor special characters can be part of an
identifier.
 Variable identifiers should always begin with a letter
and underscore( _ ).
 They cannot begin with a digit.
 They cannot match any key word of the C++ language
nor your compiler's specific ones.
Chapter 2: Basic Concepts of C++ Programming 25
Legal Identifiers
 Here are some specific rules that must be followed
with all identifiers.
◦ The first character must be one of the letters a through
z, A through Z, or an underscore (_).
◦ After the first character you may use the letters a
through z or A through Z, the digits 0 through 9, or
underscores.
◦ Uppercase and lowercase characters are distinct. For e.g.
ItemsOrdered is not the same as itemsordered.
Chapter 2: Basic Concepts of C++ Programming 26
….Legal Identifiers
 The following table lists variable names and indicates whether
each is legal or illegal in C++.
Chapter 2: Basic Concepts of C++ Programming 27
Keywords
 Some words are reserved by C++, and you may not
use them as variable names.
 Keywords used by the compiler to control your
program.
 Keywords include if, while, for, and main.
 The key words make up the “core” of the
language and have specific purposes.
 They are words that have a special meaning.
◦ They may only be used for their intended purpose.
 They are also known as reserved words.
Chapter 2: Basic Concepts of C++ Programming 28
Key words according to the ANSI-C++
standard
Chapter 2: Basic Concepts of C++ Programming 29
SPECIAL CHARACTERS
AND
ESCAPE SEQUENCES
Chapter 2: Basic Concepts of C++ Programming 30
SPECIAL CHARACTERS
 There are several sets of special characters.
 The following table provides a short summary of
how they were used.
Chapter 2: Basic Concepts of C++ Programming 31
Escape Sequences
 Escape sequences are written as a backslash
character () followed by one or more control
characters
 They are used to control the way output is
displayed.
◦ They give you the ability to exercise greater control over the
way information is output by your program.
 There are many escape sequences in C++.
◦ The newline escape sequence (n) is just one of them.
◦ When cout encounters n in a string, interprets it as a
special command to advance the output cursor to the next
line.
Chapter 2: Basic Concepts of C++ Programming 32
….Escape Sequences
 Do not confuse the backslash () with the forward slash (/).
 Do not put a space between the backslash and the control character.
Chapter 2: Basic Concepts of C++ Programming 33
BASIC INPUT/OUTPUT
 In the iostream C++ library, standard input and output
operations are supported by two data streams:
◦ cin for input and
◦ cout for output.
 Therefore:
◦ cout (the standard output stream) is normally directed to the
Monitor
◦ and cin (the standard input stream) is normally assigned to
the Keyboard.
 By handling these two streams you can show messages
on the screen and receive input from the keyboard.
Chapter 2: Basic Concepts of C++ Programming 34
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
 When the << symbol is used this way, it is called the stream-
insertion operator,
◦ since it inserts the data that follows it into the stream that precedes it.
 The information immediately to the right of the operator is sent
to cout and then displayed on the screen.
◦ In the examples above it inserted the constant string Output sentence, the
numerical constant 120 and the variable x into the output stream cout.
Chapter 2: Basic Concepts of C++ Programming 35
…. Output (cout)
 To use constant strings of characters we must enclose them
between double quotes (")
◦ so that they can be clearly distinguished from variables.
◦ The output message is enclosed between double quotes (") because it
is a string of characters.
 For example, these two sentences are very different:
cout << "Hello"; // prints Hello on screen
cout << Hello; // prints the content of Hello variable on
screen
 The insertion operator (<<) may be used more than once in a
same sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
this would print the message Hello, I am a C++ sentence on
the screen.
Chapter 2: Basic Concepts of C++ Programming 36
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;
 cin can only process the input from the keyboard
once the ENTER key has been pressed.
Chapter 2: Basic Concepts of C++ Programming 37
…. Input (cin)
 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 for variable b that may be
separated by any valid blank separator:
◦ a space,
◦ a tab character or
◦ a newline.
Chapter 2: Basic Concepts of C++ Programming 38
Example on I/O
// i/o example
#include <iostream.h>
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << “nThe value you entered is " << i;
cout << " and its double is " << i*2 << ".n";
return 0;
}
OUTPUT
Please enter an integer value: 702
The value you entered is 702 and its double is 1404.
Chapter 2: Basic Concepts of C++ Programming 39
Operators
 An operand is usually a piece of data, like a number.
 There are three types of operators: unary, binary, and
ternary.
 Unary operators only require a single operand.
◦ For example, consider the following expression: -5
◦ The minus sign, when used this way, is called the negation operator.
 Binary operators work with two operands.
◦ The assignment operator is in this category.
◦ E.g. a=1
 Ternary operators require three operands.
◦ C++ only has one ternary operator (? – conditional operator).
◦ E.g. a>b ? a : b
Chapter 2: Basic Concepts of C++ Programming 40
Operators
 C++ provides operators to operate on variables
and constants
 Operators are a set of keywords and signs..
 Includes
◦ Assignment operator(=)
◦ Arithmetic operators ( +, -, *, /, % )
◦ Compound assignment operators (+=, -=, *=, /=, %=)
◦ Relational operators ( ==, !=, >, <, >=, <= )
◦ Logic operators ( !, &&, || )
◦ Conditional operator ( ? )
◦ The Increment and Decrement Operators(++, --)
Chapter 2: Basic Concepts of C++ Programming 41
Assignment operator(=)
 It serves to assign a value to a variable.
a = 5;
assigns the integer value 5 to variable a.
 Left value must always be a variable whereas
 Right value can be either a constant, a variable, the result
of an operation or any combination of them.
 For e.g.
a = b;
◦ assigns to variable a (lvalue) the value that contains variable b
(rvalue) independently of the value that was stored in a at that
moment.
Chapter 2: Basic Concepts of C++ Programming 42
…. Assignment operator(=)
 For example, if we take this code :
int a, b; // a:? b:?
a = 10; // a:10 b:?
b = 4; // a:10 b:4
a = b; // a:4 b:4
b = 7; // a:4 b:7
will give us the result that the value contained in a
is 4 and the one contained in b is 7.
 The final modification of b has not affected a,
(right-to-left rule).
Chapter 2: Basic Concepts of C++ Programming 43
Arithmetic operators ( +, -, *, /, %)
 The following table shows the common arithmetic operators in C++.
Chapter 2: Basic Concepts of C++ Programming 44
…. Arithmetic operators ( +, -, *, /, %)
 The addition operator returns the sum of its two operands.
◦ Here, the variable amount will be assigned the value 12:
amount = 4 + 8;
 The subtraction operator returns the value of its right
operand subtracted from its left operand.
◦ This statement will assign the value 98 to temperature:
temperature = 112 - 14;
 The multiplication operator returns the product of its two
operands.
◦ In the following statement, markUp is assigned the value 3:
markUp = 12 * 0.25;
Chapter 2: Basic Concepts of C++ Programming 45
…. Arithmetic operators ( +, -, *, /, %)
 The division operator returns the quotient of its
left operand divided by its right operand.
◦ In the next statement, points is assigned the value 5:
points = 100 / 20;
 The modulus operator, which only works with
integer operands, returns the remainder of an
integer division.
◦ The following statement assigns 2 to leftOver:
leftOver = 17 % 3;
Chapter 2: Basic Concepts of C++ Programming 46
Compound assignment operators (+=,
-=, *=, /=, %=)
 The following table shows the combined assignment
operators, also known as compound operators or arithmetic
assignment operators.
Chapter 2: Basic Concepts of C++ Programming 47
….. Compound assignment operators
(+=, -=, *=, /=, %=)
 Programs may 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.
◦ Effectively, this statement adds 1 to number.
 In a similar fashion, the following statement
subtracts 5 from number.
number = number – 5;
Chapter 2: Basic Concepts of C++ Programming 48
….. Compound assignment operators
(+=, -=, *=, /=, %=)
 Examples of statements: (Assume x = 6)
Chapter 2: Basic Concepts of C++ Programming 49
Relational operators
( ==, !=, >, <, >=, <= )
 They allow you to compare numeric values and determine
if one is greater than, less than, equal to, or not equal to
another.
 For example,
◦ the greater-than operator (>) determines if a value is
greater than another.
◦ The equality operator (==) determines if two values are
equal.
Chapter 2: Basic Concepts of C++ Programming 50
…. Relational operators
( ==, !=, >, <, >=, <= )
 The following table lists all of C++’s relational operators.
Chapter 2: Basic Concepts of C++ Programming 51
…. Relational operators
( ==, !=, >, <, >=, <= )
 All the relational operators are binary operators
◦ They use two operands.
 Here is an example of an expression using the
greater-than operator:
x > y
◦ This expression is called a relational expression.
◦ It is used to determine if x is greater than y.
 The following expression determines if x is less
than y:
x < y
Chapter 2: Basic Concepts of C++ Programming 52
…. Relational operators
( ==, !=, >, <, >=, <= )
 Relational expressions are Boolean expressions
◦ which means their value can only be true or false.
 If x is greater than y,
◦ the expression x>y will be true, while
◦ the expression y==x will be false.
 The == operator determines if the operand on its left is
equal to the operand on its right.
◦ If both operands have the same value, the expression is true.
◦ Assuming that a is 4, the following expression is true:
a == 4
◦ But the following is false:
a == 2
Chapter 2: Basic Concepts of C++ Programming 53
…. Relational operators
( ==, !=, >, <, >=, <= )
 The >= operator determines if the operand on its left is
greater than or equal to the operand on the right.
◦ Assuming that a is 4, b is 6, and c is 4, both of the following expressions
are true:
b >= a
a >= c
◦ But the following is false:
a >= 5
 The <= operator determines if the operand on its left is less
than or equal to the operand on its right.
◦ Assuming that a is 4, b is 6, and c is 4, both of the following expressions
are true:
a <= c
b <= 10
◦ But the following is false:
b <= a
Chapter 2: Basic Concepts of C++ Programming 54
…. Relational operators
( ==, !=, >, <, >=, <= )
 The != operator is the not-equal operator.
 It determines if the operand on its left is not equal to
the operand on its right.
 Is the opposite of the == operator.
 As before, assuming a is 4, b is 6, and c is 4,
◦ both of the following expressions are true because a is not
equal to b and b is not equal to c:
a != b
b != c
◦ But the following expression is false because a is equal to c:
a != c
Chapter 2: Basic Concepts of C++ Programming 55
…. Relational operators
( ==, !=, >, <, >=, <= )
 Examples of relational expressions and their true or false
values. (Assume x is 10 and y is 7.)
Chapter 2: Basic Concepts of C++ Programming 56
Logic operators (&&, ||, ! )
 They connect two or more relational expressions into one or
reverse the logic of an expression.
 The following table lists C++’s logical operators.
Chapter 2: Basic Concepts of C++ Programming 57
… Logic operators (&&, ||, ! )
 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.
Chapter 2: Basic Concepts of C++ Programming 58
…. Logic operators (&&, ||, ! )
 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.
Chapter 2: Basic Concepts of C++ Programming 59
…. Logic operators (&&, ||, ! )
 The ! operator performs a logical NOT operation.
 It takes an operand and reverses its truth or falsehood.
 In other words, if the expression is true, the ! operator
returns false, and if the expression is false, it returns true.
Chapter 2: Basic Concepts of C++ Programming 60
…. Logic operators (&&, ||, ! )
!(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.
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
Chapter 2: Basic Concepts of C++ Programming 61
•For example:
( (5 == 5) && (3 > 6) ) returns false ( true && false ).
( (5 == 5) || (3 > 6)) returns true ( true || false ).
Examples
Conditional operator ( ?: )
 This evaluates an expression and returns a different value according
to the evaluated expression, depending on whether it is true or
false.
 Its format is:
condition ? result1 : result2
◦ if condition is true the expression will return result1, if not it will return
result2.
Chapter 2: Basic Concepts of C++ Programming 62
…. Conditional operator ( ? )
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 a, since 5 is greater than 3.
a>b ? a : b returns the greater one, a or b.
Chapter 2: Basic Concepts of C++ Programming 63
•Example:
The Increment and Decrement
Operators (++ and -- )
 They are designed just for incrementing and decrementing
variables.
◦ The increment operator is ++ .
◦ The decrement operator is - -.
 They are unary operators
 E.g. The following statement uses the ++ operator to
increment num:
num++;
 And the following statement decrements num:
num--;
 The expression num++ is pronounced “num plus plus,” and
num--is pronounced “num minus minus.”
Chapter 3: Basic Concepts of C++ Programming
64
…. The Increment and Decrement
Operators (++ and -- )
 ++ and -- are operators that add and subtract 1 from their
operands.
 To increment a value means to increase it by one, and to
decrement a value means to decrease it by one.
 Both of the following statements increment the variable
num:
num = num + 1;
num += 1;
 And num is decremented in both of the following
statements:
num = num - 1;
num -= 1;
Chapter 2: Basic Concepts of C++ Programming 65
…. The Increment and Decrement
Operators (++ and -- )
 Increment and decrement operators are used in:
◦ postfix mode, where means the operator is placed after
the variable. E.g.
num ++;
num --;
◦ prefix mode, where the operator is placed before the
variable name. E.g.
++num;
--num;
Chapter 2: Basic Concepts of C++ Programming 66
Operator Precedence
 Deals 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.
Chapter 2: Basic Concepts of C++ Programming 67
… Operator Precedence
 The following table shows some expressions with
their values.
Chapter 2: Basic Concepts of C++ Programming 68
… Operator Precedence
 Grouping with Parentheses can force some operations to be
performed before others.
 All these precedence levels can be manipulated using
parenthesis signs ( and ), as in this example:
a = 5 + 7 % 2;
might be written as:
a = 5 + (7 % 2); or
a = (5 + 7) % 2;
 For example: consider the following statement
average = (a + b + c + d) / 4;
 Here the sum of a, b, c, and d is divided by 4.
 Without the parentheses, however, d would be divided by 4
and the result added to a, b, and c.
Chapter 2: Basic Concepts of C++ Programming 69
… Operator Precedence
 The following table shows more expressions and their values
with high- precedence operations enclosed between
parentheses.
Chapter 2: Basic Concepts of C++ Programming 70
EXPRESSIONS
 In algebra it is not always necessary to use an operator for
multiplication.
 C++ requires an operator for any mathematical operation.
 The following table shows some algebraic expressions that
perform multiplication and the equivalent C++ expressions.
Chapter 2: Basic Concepts of C++ Programming 71
… EXPRESSIONS
 When converting some algebraic expressions to C++,
you may have to insert parentheses in the algebraic
expression.
 For example, look at the following expression:
Chapter 2: Basic Concepts of C++ Programming 72
 To convert this to a C++ statement, a + b
will have to be enclosed in parentheses:
x = (a + b) / c;
… EXPRESSIONS
 The following table shows more algebraic expressions and their C++
equivalents.
Chapter 2: Basic Concepts of C++ Programming 73
PROGRAMMING ERRORS
 Debugging is the process of finding and correcting
errors in computer programs.
 Most programs you write will contain errors.
◦ Either they won't compile or they won't execute
properly.
 Program debugging is another form of problem
solving
 There are three types of programming errors:
◦ Design errors
◦ Syntax errors
◦ Run-time errors
Chapter 2: Basic Concepts of C++ Programming 74
Design Errors
 They occur during the analysis, design, and
implementation phases.
 They occur due to:
◦ Choosing an incorrect method of solution for the
problem to be solved,
◦ Making mistakes in translating an algorithm into a
program, or
◦ Designing erroneous data for the program.
 Design errors are usually difficult to detect.
 Debugging them requires careful review of
problem analysis, algorithm design, translation,
and test data.
Chapter 2: Basic Concepts of C++ Programming 75
Syntax Errors
 Syntax Errors are violations of syntax rules,
◦ which define how the elements of a programming
language must be written.
 They occur during the implementation phase
 They are detected by the compiler during the
compilation process.
◦ Another name for syntax errors is compilation errors.
 If your program contains syntax errors, the
compiler issues diagnostic messages.
 Depending on how serious the violation is, the
diagnostic message may be a warning message or
an error message.
Chapter 2: Basic Concepts of C++ Programming 76
… Syntax 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 and may or may not be important.
 It is good practice to take warning message seriously and
eliminate their causes in the program.
 If the syntax violation is serious, the compiler produces
error messages,
◦ telling you about the nature of the errors and where they are in the
program.
 Because of the explicit help we get from compilers,
debugging syntax errors is relatively easy.
Chapter 2: Basic Concepts of C++ Programming 77
Run-time Errors
 Run-time Errors are detected by the computer
while your program is being executed.
 They are caused by program instructions that
require the computer to do something illegal, such
as
◦ attempting to store inappropriate data or
◦ dividing a number by zero.
 When a run-time error is encountered, the
computer produces an error message and
terminates the program execution.
 You can use these error messages to debug run-
time errors
Chapter 2: Basic Concepts of C++ Programming 78
Review Question
• Write C++ expressions for the following algebraic expressions
Chapter 2: Basic Concepts of C++ Programming 79
Thank you
Chapter 2: Basic Concepts of C++ Programming 80

More Related Content

Similar to CHAPTER-2.ppt

Similar to CHAPTER-2.ppt (20)

02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Introduction to C++ lecture ************
Introduction to C++ lecture ************Introduction to C++ lecture ************
Introduction to C++ lecture ************
 
C++ programming
C++ programmingC++ programming
C++ programming
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Chapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory ConceptChapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory Concept
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
Module 1 PCD.docx
Module 1 PCD.docxModule 1 PCD.docx
Module 1 PCD.docx
 
C language
C language C language
C language
 
c++
c++c++
c++
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
Chap 3 c++
Chap 3 c++Chap 3 c++
Chap 3 c++
 
C chap02
C chap02C chap02
C chap02
 
C chap02
C chap02C chap02
C chap02
 
Intro
IntroIntro
Intro
 
C++
C++C++
C++
 
2 expressions (ppt-2) in C++
2 expressions (ppt-2) in C++2 expressions (ppt-2) in C++
2 expressions (ppt-2) in C++
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdf
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Mid term sem 2 1415 sol
Mid term sem 2 1415 solMid term sem 2 1415 sol
Mid term sem 2 1415 sol
 

More from Tekle12

Chapter 3 Naming in distributed system.pptx
Chapter 3 Naming in distributed system.pptxChapter 3 Naming in distributed system.pptx
Chapter 3 Naming in distributed system.pptxTekle12
 
Chapter Introductionn to distributed system .pptx
Chapter Introductionn to distributed system .pptxChapter Introductionn to distributed system .pptx
Chapter Introductionn to distributed system .pptxTekle12
 
Chapter 6emerging technology - EMTE.pptx
Chapter 6emerging technology - EMTE.pptxChapter 6emerging technology - EMTE.pptx
Chapter 6emerging technology - EMTE.pptxTekle12
 
Chapter 4about internet of things IoT.pptx
Chapter 4about internet of things IoT.pptxChapter 4about internet of things IoT.pptx
Chapter 4about internet of things IoT.pptxTekle12
 
Design and analysis of algorithm chapter two.pptx
Design and analysis of algorithm chapter two.pptxDesign and analysis of algorithm chapter two.pptx
Design and analysis of algorithm chapter two.pptxTekle12
 
Chapter1.1 Introduction to design and analysis of algorithm.ppt
Chapter1.1 Introduction to design and analysis of algorithm.pptChapter1.1 Introduction to design and analysis of algorithm.ppt
Chapter1.1 Introduction to design and analysis of algorithm.pptTekle12
 
Chapter 6 WSN.ppt
Chapter 6 WSN.pptChapter 6 WSN.ppt
Chapter 6 WSN.pptTekle12
 
Chapter 2.1.pptx
Chapter 2.1.pptxChapter 2.1.pptx
Chapter 2.1.pptxTekle12
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.pptTekle12
 
CHAPTER-5.ppt
CHAPTER-5.pptCHAPTER-5.ppt
CHAPTER-5.pptTekle12
 
CHAPTER-1.ppt
CHAPTER-1.pptCHAPTER-1.ppt
CHAPTER-1.pptTekle12
 
Chapter 1 - Intro to Emerging Technologies.pptx
Chapter 1 - Intro to Emerging Technologies.pptxChapter 1 - Intro to Emerging Technologies.pptx
Chapter 1 - Intro to Emerging Technologies.pptxTekle12
 
chapter 3.2 TCP.pptx
chapter 3.2 TCP.pptxchapter 3.2 TCP.pptx
chapter 3.2 TCP.pptxTekle12
 
Chapter 2.1.pptx
Chapter 2.1.pptxChapter 2.1.pptx
Chapter 2.1.pptxTekle12
 
Chapter 1 - EMTE.pptx
Chapter 1 - EMTE.pptxChapter 1 - EMTE.pptx
Chapter 1 - EMTE.pptxTekle12
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptxTekle12
 
Chapter 3.pptx
Chapter 3.pptxChapter 3.pptx
Chapter 3.pptxTekle12
 
chapter 6.1.pptx
chapter 6.1.pptxchapter 6.1.pptx
chapter 6.1.pptxTekle12
 
Chapter 4.pptx
Chapter 4.pptxChapter 4.pptx
Chapter 4.pptxTekle12
 
Chapter 5.pptx
Chapter 5.pptxChapter 5.pptx
Chapter 5.pptxTekle12
 

More from Tekle12 (20)

Chapter 3 Naming in distributed system.pptx
Chapter 3 Naming in distributed system.pptxChapter 3 Naming in distributed system.pptx
Chapter 3 Naming in distributed system.pptx
 
Chapter Introductionn to distributed system .pptx
Chapter Introductionn to distributed system .pptxChapter Introductionn to distributed system .pptx
Chapter Introductionn to distributed system .pptx
 
Chapter 6emerging technology - EMTE.pptx
Chapter 6emerging technology - EMTE.pptxChapter 6emerging technology - EMTE.pptx
Chapter 6emerging technology - EMTE.pptx
 
Chapter 4about internet of things IoT.pptx
Chapter 4about internet of things IoT.pptxChapter 4about internet of things IoT.pptx
Chapter 4about internet of things IoT.pptx
 
Design and analysis of algorithm chapter two.pptx
Design and analysis of algorithm chapter two.pptxDesign and analysis of algorithm chapter two.pptx
Design and analysis of algorithm chapter two.pptx
 
Chapter1.1 Introduction to design and analysis of algorithm.ppt
Chapter1.1 Introduction to design and analysis of algorithm.pptChapter1.1 Introduction to design and analysis of algorithm.ppt
Chapter1.1 Introduction to design and analysis of algorithm.ppt
 
Chapter 6 WSN.ppt
Chapter 6 WSN.pptChapter 6 WSN.ppt
Chapter 6 WSN.ppt
 
Chapter 2.1.pptx
Chapter 2.1.pptxChapter 2.1.pptx
Chapter 2.1.pptx
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.ppt
 
CHAPTER-5.ppt
CHAPTER-5.pptCHAPTER-5.ppt
CHAPTER-5.ppt
 
CHAPTER-1.ppt
CHAPTER-1.pptCHAPTER-1.ppt
CHAPTER-1.ppt
 
Chapter 1 - Intro to Emerging Technologies.pptx
Chapter 1 - Intro to Emerging Technologies.pptxChapter 1 - Intro to Emerging Technologies.pptx
Chapter 1 - Intro to Emerging Technologies.pptx
 
chapter 3.2 TCP.pptx
chapter 3.2 TCP.pptxchapter 3.2 TCP.pptx
chapter 3.2 TCP.pptx
 
Chapter 2.1.pptx
Chapter 2.1.pptxChapter 2.1.pptx
Chapter 2.1.pptx
 
Chapter 1 - EMTE.pptx
Chapter 1 - EMTE.pptxChapter 1 - EMTE.pptx
Chapter 1 - EMTE.pptx
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
Chapter 3.pptx
Chapter 3.pptxChapter 3.pptx
Chapter 3.pptx
 
chapter 6.1.pptx
chapter 6.1.pptxchapter 6.1.pptx
chapter 6.1.pptx
 
Chapter 4.pptx
Chapter 4.pptxChapter 4.pptx
Chapter 4.pptx
 
Chapter 5.pptx
Chapter 5.pptxChapter 5.pptx
Chapter 5.pptx
 

Recently uploaded

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

CHAPTER-2.ppt

  • 1. Chapter Two BASIC CONCEPTS OF C++ PROGRAMMING
  • 2. Structure of a C++ program // my first program in C++ #include <iostream> Using namespace std; int main () { cout << "Hello World!"; return 0; } Chapter 2: Basic Concepts of C++ Programming 2 OUTPUT Hello World!  This program includes the basic components that every C++ program has
  • 3. COMMENTS  Comments are pieces of source code discarded from the code by the compiler.  They are used to insert notes or descriptions.  C++ supports two ways to insert comments: ◦ // line comment ◦ /* block comment */  The Line comment, discards everything from where the double slash signs (//) is found up to the end of that same line.  The Block comment, discards everything between the /* characters and the next appearance of the */ characters, with the possibility of including several lines. Chapter 2: Basic Concepts of C++ Programming 3
  • 4. Example of Comments /* my second program in C++ with more comments */ #include <iostream.h> int main () { cout << "Hello World! "; // shows Hello World! cout << “A C++ program";// shows A C++ program return 0; } Chapter 2: Basic Concepts of C++ Programming 4
  • 5. DATA TYPES  There are many different types of data. ◦ In the realm of numeric information, for example, there are whole numbers and fractional numbers. ◦ There are negative numbers and positive numbers. ◦ And there are numbers so large, and others so small, that they don’t even have a name. ◦ Then there is textual information. Names and addresses, for instance, are stored as groups of characters. Chapter 2: Basic Concepts of C++ Programming 5
  • 6. Data Types  C++ offers two very broadest data types: ◦ numeric and ◦ character.  Numeric data types are broken into two additional categories: ◦ integer and ◦ floating-point.  Integers are whole numbers like 12, 157, –34, and 2.  Floating-point numbers have a decimal point, like 23.7, 189.0231, and 0.987.  Additionally, the integer and floating point data types are broken into even more classifications. Chapter 2: Basic Concepts of C++ Programming 6
  • 7. Integer Data Types  Includes ◦ short ◦ unsigned short ◦ Int ◦ unsigned int ◦ Long ◦ unsigned long data types Chapter 2: Basic Concepts of C++ Programming 7
  • 8. Floating-Point Data Types  Are data type that allows fractional values. ◦ If you are writing a program that works with dollar amounts or precise measurements you need floating point data types  In C++ there are three data types that can represent floating-point numbers.  They are ◦ float ◦ double ◦ long double Chapter 2: Basic Concepts of C++ Programming 8
  • 9. Floating-Point Data Types  Internally, floating-point numbers are stored in a manner similar to scientific notation. ◦ In scientific notation the number 47,281.97 is 4.728197x104.  Computers typically use E notation to represent floating-point values. ◦ In E notation, the number 47,281.97 would be 4.728197E4. The part of the number before the E is the mantissa, and the part after the E is the power of 10.  The following table shows other numbers represented in scientific and E notation. Chapter 2: Basic Concepts of C++ Programming 9
  • 10. Char Data Type  A char variable (used to hold characters) is most often one byte long. Chapter 2: Basic Concepts of C++ Programming 10
  • 11. Size of Data Types  The size of a variable is the number of bytes of memory it uses.  Our computer's memory is organized in bytes.  A byte is the minimum amount of memory that we can manage.  A byte can store an integer 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. Chapter 2: Basic Concepts of C++ Programming 11
  • 12. List of the existing fundamental data types in C++ Name Bytes* Description Range* char 1 character or integer 8 bits length. signed: -128 to 127 unsigned: 0 to 255 short 2 integer 16 bits length. signed: -32768 to 32767 unsigned: 0 to 65535 long 4 integer 32 bits length. signed:-2147483648 to 2147483647 unsigned: 0 to 4294967295 int * Integer. Its length traditionally depends on the length of the system's Word type, 2 (4) bytes. See short, long float 4 floating point number. 3.4e + / - 38 (7 digits) double 8 double precision floating point number. 1.7e + / - 308 (15 digits) long double 10 long double precision floating point number. 1.2e + / - 4932 (19 digits) Chapter 2: Basic Concepts of C++ Programming 12
  • 13. Variables  You can use variables to store values and you can perform any mathematical operation on those variables  This can be expressed in C++ with the following instruction set: ◦ a = 5; ◦ b = 2; ◦ a = a + 1; ◦ result = a - b; Chapter 2: Basic Concepts of C++ Programming 13
  • 14. Declaration of variables  In order to use a variable in C++, we must first declare it  The syntax to declare a new variable is: ◦ data type specifier (like int, short, float...) followed by a valid variable identifier.  For example: int a; float mynumber; // Are valid declarations of variables. Chapter 2: Basic Concepts of C++ Programming 14
  • 15. ….Declaration of variables  You can declare all of the variables of the same data type 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; Chapter 2: Basic Concepts of C++ Programming 15
  • 16. Examples on operating with variables Example-1 // operating with variables int main () { int a, b, result; a = 5; b = 2; a = a + 1; result = a - b; cout << result; // print out the result return 0; // terminate the program } Chapter 2: Basic Concepts of C++ Programming 16 Output 4
  • 17. Example-2  // a C++ program with a variable int main() { int number; number = 5; cout << "The value of number is " << "number" << endl; cout << "The value of number is " << number << endl; number = 7; cout << "Now the value of number is " << number << endl; return 0; } Output The value of number is number The value of number is 5 Now the value of number is 7 Chapter 2: Basic Concepts of C++ Programming 17
  • 18. Initialization of variables  To make a variable to store a concrete value the moment that it is declared, append an equal sign followed by the value. type identifier = initial_value ;  For example: int number = 5;  Here is the other way: int number; number = 5; // this line is an assignment.  The = sign is an operator that copies the value on its right (5) into the variable named on its left (number). Chapter 2: Basic Concepts of C++ Programming 18
  • 19. CONSTANTS  A constant is any expression that has a fixed value.  You must initialize a constant when you create it, ◦ and you cannot assign a new value later.  C++ has two types of constants: ◦ literal and ◦ symbolic. Chapter 2: Basic Concepts of C++ Programming 19
  • 20. 1. Literal Constants  A literal constant is a value typed directly into your program.  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.  They can be divided in Integer Numbers, Floating- Point Numbers, Characters and Strings. Chapter 2: Basic Concepts of C++ Programming 20
  • 21. Integer and Floating Point Constants  Values 1776, 707, -273 are numerical constants that identify integer numbers.  Floating Point constants express numbers with decimals and/or exponents.  They can include a decimal point: ◦ 3.14159 // 3.14159 ◦ 6.02e23 // 6.02 x 1023 ◦ 1.6e-19 // 1.6 x 10-19 ◦ 3.0 // 3.0 Chapter 2: Basic Concepts of C++ Programming 21
  • 22. Characters and strings  There also exist non-numerical constants, like: ◦ 'z', // single character ◦ 'p', // single character ◦ "Hello world", // strings of several characters ◦ "How do you do?". // strings of several characters  Notice that: ◦ to represent a single character we enclose it between single quotes (') and ◦ to express a string of more than one character we enclose them between double quotes (").  Notice this: x and 'x'. Here, ◦ x refers to variable x, whereas ◦ 'x' refers to the character constant 'x'. Chapter 2: Basic Concepts of C++ Programming 22
  • 23. 2. Symbolic Constants  A symbolic constant is a constant that is represented by a name.  There are two ways to declare a symbolic constant in C++. ◦Defining Constants with #define E.g. #define studentsPerClass 15 ◦Defining Constants with const E.g. const unsigned short int studentsPerClass = 15; Chapter 2: Basic Concepts of C++ Programming 23
  • 24. …Symbolic Constants  For example: ◦ If your program has two integer variables named students and classes, you could compute how many students you have, given number of classes, if you know there were 15 students per class: students = classes * 15;  In this example, 15 is a literal constant.  If you substituted a symbolic constant for this value: students = classes * studentsPerClass Chapter 2: Basic Concepts of C++ Programming 24
  • 25. IDENTIFIERS  An identifier is a programmer-defined name that represents some element of a program. ◦ Variable names are examples of identifiers.  A valid identifier is a sequence of one or more letters, digits or underscore( _ ).  Neither spaces nor special characters can be part of an identifier.  Variable identifiers should always begin with a letter and underscore( _ ).  They cannot begin with a digit.  They cannot match any key word of the C++ language nor your compiler's specific ones. Chapter 2: Basic Concepts of C++ Programming 25
  • 26. Legal Identifiers  Here are some specific rules that must be followed with all identifiers. ◦ The first character must be one of the letters a through z, A through Z, or an underscore (_). ◦ After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or underscores. ◦ Uppercase and lowercase characters are distinct. For e.g. ItemsOrdered is not the same as itemsordered. Chapter 2: Basic Concepts of C++ Programming 26
  • 27. ….Legal Identifiers  The following table lists variable names and indicates whether each is legal or illegal in C++. Chapter 2: Basic Concepts of C++ Programming 27
  • 28. Keywords  Some words are reserved by C++, and you may not use them as variable names.  Keywords used by the compiler to control your program.  Keywords include if, while, for, and main.  The key words make up the “core” of the language and have specific purposes.  They are words that have a special meaning. ◦ They may only be used for their intended purpose.  They are also known as reserved words. Chapter 2: Basic Concepts of C++ Programming 28
  • 29. Key words according to the ANSI-C++ standard Chapter 2: Basic Concepts of C++ Programming 29
  • 30. SPECIAL CHARACTERS AND ESCAPE SEQUENCES Chapter 2: Basic Concepts of C++ Programming 30
  • 31. SPECIAL CHARACTERS  There are several sets of special characters.  The following table provides a short summary of how they were used. Chapter 2: Basic Concepts of C++ Programming 31
  • 32. Escape Sequences  Escape sequences are written as a backslash character () followed by one or more control characters  They are used to control the way output is displayed. ◦ They give you the ability to exercise greater control over the way information is output by your program.  There are many escape sequences in C++. ◦ The newline escape sequence (n) is just one of them. ◦ When cout encounters n in a string, interprets it as a special command to advance the output cursor to the next line. Chapter 2: Basic Concepts of C++ Programming 32
  • 33. ….Escape Sequences  Do not confuse the backslash () with the forward slash (/).  Do not put a space between the backslash and the control character. Chapter 2: Basic Concepts of C++ Programming 33
  • 34. BASIC INPUT/OUTPUT  In the iostream C++ library, standard input and output operations are supported by two data streams: ◦ cin for input and ◦ cout for output.  Therefore: ◦ cout (the standard output stream) is normally directed to the Monitor ◦ and cin (the standard input stream) is normally assigned to the Keyboard.  By handling these two streams you can show messages on the screen and receive input from the keyboard. Chapter 2: Basic Concepts of C++ Programming 34
  • 35. 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  When the << symbol is used this way, it is called the stream- insertion operator, ◦ since it inserts the data that follows it into the stream that precedes it.  The information immediately to the right of the operator is sent to cout and then displayed on the screen. ◦ In the examples above it inserted the constant string Output sentence, the numerical constant 120 and the variable x into the output stream cout. Chapter 2: Basic Concepts of C++ Programming 35
  • 36. …. Output (cout)  To use constant strings of characters we must enclose them between double quotes (") ◦ so that they can be clearly distinguished from variables. ◦ The output message is enclosed between double quotes (") because it is a string of characters.  For example, these two sentences are very different: cout << "Hello"; // prints Hello on screen cout << Hello; // prints the content of Hello variable on screen  The insertion operator (<<) may be used more than once in a same sentence: cout << "Hello, " << "I am " << "a C++ sentence"; this would print the message Hello, I am a C++ sentence on the screen. Chapter 2: Basic Concepts of C++ Programming 36
  • 37. 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;  cin can only process the input from the keyboard once the ENTER key has been pressed. Chapter 2: Basic Concepts of C++ Programming 37
  • 38. …. Input (cin)  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 for variable b that may be separated by any valid blank separator: ◦ a space, ◦ a tab character or ◦ a newline. Chapter 2: Basic Concepts of C++ Programming 38
  • 39. Example on I/O // i/o example #include <iostream.h> int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << “nThe value you entered is " << i; cout << " and its double is " << i*2 << ".n"; return 0; } OUTPUT Please enter an integer value: 702 The value you entered is 702 and its double is 1404. Chapter 2: Basic Concepts of C++ Programming 39
  • 40. Operators  An operand is usually a piece of data, like a number.  There are three types of operators: unary, binary, and ternary.  Unary operators only require a single operand. ◦ For example, consider the following expression: -5 ◦ The minus sign, when used this way, is called the negation operator.  Binary operators work with two operands. ◦ The assignment operator is in this category. ◦ E.g. a=1  Ternary operators require three operands. ◦ C++ only has one ternary operator (? – conditional operator). ◦ E.g. a>b ? a : b Chapter 2: Basic Concepts of C++ Programming 40
  • 41. Operators  C++ provides operators to operate on variables and constants  Operators are a set of keywords and signs..  Includes ◦ Assignment operator(=) ◦ Arithmetic operators ( +, -, *, /, % ) ◦ Compound assignment operators (+=, -=, *=, /=, %=) ◦ Relational operators ( ==, !=, >, <, >=, <= ) ◦ Logic operators ( !, &&, || ) ◦ Conditional operator ( ? ) ◦ The Increment and Decrement Operators(++, --) Chapter 2: Basic Concepts of C++ Programming 41
  • 42. Assignment operator(=)  It serves to assign a value to a variable. a = 5; assigns the integer value 5 to variable a.  Left value must always be a variable whereas  Right value can be either a constant, a variable, the result of an operation or any combination of them.  For e.g. a = b; ◦ assigns to variable a (lvalue) the value that contains variable b (rvalue) independently of the value that was stored in a at that moment. Chapter 2: Basic Concepts of C++ Programming 42
  • 43. …. Assignment operator(=)  For example, if we take this code : int a, b; // a:? b:? a = 10; // a:10 b:? b = 4; // a:10 b:4 a = b; // a:4 b:4 b = 7; // a:4 b:7 will give us the result that the value contained in a is 4 and the one contained in b is 7.  The final modification of b has not affected a, (right-to-left rule). Chapter 2: Basic Concepts of C++ Programming 43
  • 44. Arithmetic operators ( +, -, *, /, %)  The following table shows the common arithmetic operators in C++. Chapter 2: Basic Concepts of C++ Programming 44
  • 45. …. Arithmetic operators ( +, -, *, /, %)  The addition operator returns the sum of its two operands. ◦ Here, the variable amount will be assigned the value 12: amount = 4 + 8;  The subtraction operator returns the value of its right operand subtracted from its left operand. ◦ This statement will assign the value 98 to temperature: temperature = 112 - 14;  The multiplication operator returns the product of its two operands. ◦ In the following statement, markUp is assigned the value 3: markUp = 12 * 0.25; Chapter 2: Basic Concepts of C++ Programming 45
  • 46. …. Arithmetic operators ( +, -, *, /, %)  The division operator returns the quotient of its left operand divided by its right operand. ◦ In the next statement, points is assigned the value 5: points = 100 / 20;  The modulus operator, which only works with integer operands, returns the remainder of an integer division. ◦ The following statement assigns 2 to leftOver: leftOver = 17 % 3; Chapter 2: Basic Concepts of C++ Programming 46
  • 47. Compound assignment operators (+=, -=, *=, /=, %=)  The following table shows the combined assignment operators, also known as compound operators or arithmetic assignment operators. Chapter 2: Basic Concepts of C++ Programming 47
  • 48. ….. Compound assignment operators (+=, -=, *=, /=, %=)  Programs may 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. ◦ Effectively, this statement adds 1 to number.  In a similar fashion, the following statement subtracts 5 from number. number = number – 5; Chapter 2: Basic Concepts of C++ Programming 48
  • 49. ….. Compound assignment operators (+=, -=, *=, /=, %=)  Examples of statements: (Assume x = 6) Chapter 2: Basic Concepts of C++ Programming 49
  • 50. Relational operators ( ==, !=, >, <, >=, <= )  They allow you to compare numeric values and determine if one is greater than, less than, equal to, or not equal to another.  For example, ◦ the greater-than operator (>) determines if a value is greater than another. ◦ The equality operator (==) determines if two values are equal. Chapter 2: Basic Concepts of C++ Programming 50
  • 51. …. Relational operators ( ==, !=, >, <, >=, <= )  The following table lists all of C++’s relational operators. Chapter 2: Basic Concepts of C++ Programming 51
  • 52. …. Relational operators ( ==, !=, >, <, >=, <= )  All the relational operators are binary operators ◦ They use two operands.  Here is an example of an expression using the greater-than operator: x > y ◦ This expression is called a relational expression. ◦ It is used to determine if x is greater than y.  The following expression determines if x is less than y: x < y Chapter 2: Basic Concepts of C++ Programming 52
  • 53. …. Relational operators ( ==, !=, >, <, >=, <= )  Relational expressions are Boolean expressions ◦ which means their value can only be true or false.  If x is greater than y, ◦ the expression x>y will be true, while ◦ the expression y==x will be false.  The == operator determines if the operand on its left is equal to the operand on its right. ◦ If both operands have the same value, the expression is true. ◦ Assuming that a is 4, the following expression is true: a == 4 ◦ But the following is false: a == 2 Chapter 2: Basic Concepts of C++ Programming 53
  • 54. …. Relational operators ( ==, !=, >, <, >=, <= )  The >= operator determines if the operand on its left is greater than or equal to the operand on the right. ◦ Assuming that a is 4, b is 6, and c is 4, both of the following expressions are true: b >= a a >= c ◦ But the following is false: a >= 5  The <= operator determines if the operand on its left is less than or equal to the operand on its right. ◦ Assuming that a is 4, b is 6, and c is 4, both of the following expressions are true: a <= c b <= 10 ◦ But the following is false: b <= a Chapter 2: Basic Concepts of C++ Programming 54
  • 55. …. Relational operators ( ==, !=, >, <, >=, <= )  The != operator is the not-equal operator.  It determines if the operand on its left is not equal to the operand on its right.  Is the opposite of the == operator.  As before, assuming a is 4, b is 6, and c is 4, ◦ both of the following expressions are true because a is not equal to b and b is not equal to c: a != b b != c ◦ But the following expression is false because a is equal to c: a != c Chapter 2: Basic Concepts of C++ Programming 55
  • 56. …. Relational operators ( ==, !=, >, <, >=, <= )  Examples of relational expressions and their true or false values. (Assume x is 10 and y is 7.) Chapter 2: Basic Concepts of C++ Programming 56
  • 57. Logic operators (&&, ||, ! )  They connect two or more relational expressions into one or reverse the logic of an expression.  The following table lists C++’s logical operators. Chapter 2: Basic Concepts of C++ Programming 57
  • 58. … Logic operators (&&, ||, ! )  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. Chapter 2: Basic Concepts of C++ Programming 58
  • 59. …. Logic operators (&&, ||, ! )  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. Chapter 2: Basic Concepts of C++ Programming 59
  • 60. …. Logic operators (&&, ||, ! )  The ! operator performs a logical NOT operation.  It takes an operand and reverses its truth or falsehood.  In other words, if the expression is true, the ! operator returns false, and if the expression is false, it returns true. Chapter 2: Basic Concepts of C++ Programming 60
  • 61. …. Logic operators (&&, ||, ! ) !(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. a b a && b a || b true true true true true false false true false true false true false false false false Chapter 2: Basic Concepts of C++ Programming 61 •For example: ( (5 == 5) && (3 > 6) ) returns false ( true && false ). ( (5 == 5) || (3 > 6)) returns true ( true || false ). Examples
  • 62. Conditional operator ( ?: )  This evaluates an expression and returns a different value according to the evaluated expression, depending on whether it is true or false.  Its format is: condition ? result1 : result2 ◦ if condition is true the expression will return result1, if not it will return result2. Chapter 2: Basic Concepts of C++ Programming 62
  • 63. …. Conditional operator ( ? ) 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 a, since 5 is greater than 3. a>b ? a : b returns the greater one, a or b. Chapter 2: Basic Concepts of C++ Programming 63 •Example:
  • 64. The Increment and Decrement Operators (++ and -- )  They are designed just for incrementing and decrementing variables. ◦ The increment operator is ++ . ◦ The decrement operator is - -.  They are unary operators  E.g. The following statement uses the ++ operator to increment num: num++;  And the following statement decrements num: num--;  The expression num++ is pronounced “num plus plus,” and num--is pronounced “num minus minus.” Chapter 3: Basic Concepts of C++ Programming 64
  • 65. …. The Increment and Decrement Operators (++ and -- )  ++ and -- are operators that add and subtract 1 from their operands.  To increment a value means to increase it by one, and to decrement a value means to decrease it by one.  Both of the following statements increment the variable num: num = num + 1; num += 1;  And num is decremented in both of the following statements: num = num - 1; num -= 1; Chapter 2: Basic Concepts of C++ Programming 65
  • 66. …. The Increment and Decrement Operators (++ and -- )  Increment and decrement operators are used in: ◦ postfix mode, where means the operator is placed after the variable. E.g. num ++; num --; ◦ prefix mode, where the operator is placed before the variable name. E.g. ++num; --num; Chapter 2: Basic Concepts of C++ Programming 66
  • 67. Operator Precedence  Deals 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. Chapter 2: Basic Concepts of C++ Programming 67
  • 68. … Operator Precedence  The following table shows some expressions with their values. Chapter 2: Basic Concepts of C++ Programming 68
  • 69. … Operator Precedence  Grouping with Parentheses can force some operations to be performed before others.  All these precedence levels can be manipulated using parenthesis signs ( and ), as in this example: a = 5 + 7 % 2; might be written as: a = 5 + (7 % 2); or a = (5 + 7) % 2;  For example: consider the following statement average = (a + b + c + d) / 4;  Here the sum of a, b, c, and d is divided by 4.  Without the parentheses, however, d would be divided by 4 and the result added to a, b, and c. Chapter 2: Basic Concepts of C++ Programming 69
  • 70. … Operator Precedence  The following table shows more expressions and their values with high- precedence operations enclosed between parentheses. Chapter 2: Basic Concepts of C++ Programming 70
  • 71. EXPRESSIONS  In algebra it is not always necessary to use an operator for multiplication.  C++ requires an operator for any mathematical operation.  The following table shows some algebraic expressions that perform multiplication and the equivalent C++ expressions. Chapter 2: Basic Concepts of C++ Programming 71
  • 72. … EXPRESSIONS  When converting some algebraic expressions to C++, you may have to insert parentheses in the algebraic expression.  For example, look at the following expression: Chapter 2: Basic Concepts of C++ Programming 72  To convert this to a C++ statement, a + b will have to be enclosed in parentheses: x = (a + b) / c;
  • 73. … EXPRESSIONS  The following table shows more algebraic expressions and their C++ equivalents. Chapter 2: Basic Concepts of C++ Programming 73
  • 74. PROGRAMMING ERRORS  Debugging is the process of finding and correcting errors in computer programs.  Most programs you write will contain errors. ◦ Either they won't compile or they won't execute properly.  Program debugging is another form of problem solving  There are three types of programming errors: ◦ Design errors ◦ Syntax errors ◦ Run-time errors Chapter 2: Basic Concepts of C++ Programming 74
  • 75. Design Errors  They occur during the analysis, design, and implementation phases.  They occur due to: ◦ Choosing an incorrect method of solution for the problem to be solved, ◦ Making mistakes in translating an algorithm into a program, or ◦ Designing erroneous data for the program.  Design errors are usually difficult to detect.  Debugging them requires careful review of problem analysis, algorithm design, translation, and test data. Chapter 2: Basic Concepts of C++ Programming 75
  • 76. Syntax Errors  Syntax Errors are violations of syntax rules, ◦ which define how the elements of a programming language must be written.  They occur during the implementation phase  They are detected by the compiler during the compilation process. ◦ Another name for syntax errors is compilation errors.  If your program contains syntax errors, the compiler issues diagnostic messages.  Depending on how serious the violation is, the diagnostic message may be a warning message or an error message. Chapter 2: Basic Concepts of C++ Programming 76
  • 77. … Syntax 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 and may or may not be important.  It is good practice to take warning message seriously and eliminate their causes in the program.  If the syntax violation is serious, the compiler produces error messages, ◦ telling you about the nature of the errors and where they are in the program.  Because of the explicit help we get from compilers, debugging syntax errors is relatively easy. Chapter 2: Basic Concepts of C++ Programming 77
  • 78. Run-time Errors  Run-time Errors are detected by the computer while your program is being executed.  They are caused by program instructions that require the computer to do something illegal, such as ◦ attempting to store inappropriate data or ◦ dividing a number by zero.  When a run-time error is encountered, the computer produces an error message and terminates the program execution.  You can use these error messages to debug run- time errors Chapter 2: Basic Concepts of C++ Programming 78
  • 79. Review Question • Write C++ expressions for the following algebraic expressions Chapter 2: Basic Concepts of C++ Programming 79
  • 80. Thank you Chapter 2: Basic Concepts of C++ Programming 80