2. Initialize variable
⢠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.
⢠In order to do that, you can initialize the variable.
⢠There are two ways to do this in C++:
⢠The first one, known as c-like, is done by appending an equal sign followed
by the value to which the variable will be initialized:
type identifier = initial_value ;
⢠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;
3. Initialize variable
⢠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++.
4. Example of program
// 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;
}
Output:
6
5. Identifier scope:local, global
⢠All the variables that we intend to use in a
program must have been declared with its type
specifier in an earlier
⢠point in the code, like we did in the previous code
at the beginning of the body of the function main
when we declared that a, b, and result were of
type int.
⢠A variable can be either of local or global scope.
⢠A local variable is one declared within the body of
a function or a block.
6. ⢠A global variable is a variable declared in the
main body of the source code, outside all
functions.
⢠Global variables can be referred from
anywhere in the code, even inside functions,
whenever it is after its declaration.
7. Example of program:
#include<iostream>
using namesopace std;
int num1,num2;
char name;
int main()
{
float total;
cout<<âFirst number is:â;
cin>>num1;
cout<<âSecond number is:â;
cin>>num2;
total=num1+NUM2;
cout<<âTOTAL OF TWO NUMBERS IS:â<<total;
return 0;
}
Global Variable
Local Variable
8. keyword
⢠Keywords (also called reserved words)
â Reserved words in the C++ language for specific use.
â Must be used as they are defined in the programming
language
â Keywords that identify language entities such as
statements, data types, language attributes, etc.
â Have special meaning to the compiler, cannot be used as
identifiers (variable, function name)
â Should be typed in lowercase.
â Example: const, double, int, main,
void,printf, while, for, else (etc..)
9. ⢠Cannot be used as identifiers or variable
namesKeywords common to the
C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
10. Data Types
⢠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,
⢠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).
⢠In addition, the computer can manipulate more complex data types
that come from grouping several bytes, such as long numbers or
non-integer numbers.
⢠Next you have a summary of the basic fundamental data types in
C++, as well as the range of values that can be represented with
each one:
11. Data Type C++
keyword
Syntax Bit
Width
Example
value
Range
integer int int no1,no2; 32 -1 ,1,34000 -32768-32767
long integer long long amount; 64 1000000 -4294967296 to
4294967296
short
integer
short short totalweight; 16 127 -127-128
unsigned
integer
unsigned unsigned sum; 32 200 0 to 65535
character char char name; 8 âzâ 0 to 255
floating
point
float float amount; 32 20.00 Approximately 6
digits of
precision
double
floting point
double double totalweight; 64 100.85321 Approximately
12 digits of
precision
boolean bool bool found; N/A True/false True/false
12. Input and output statement
⢠Input/output statement operation is fundamental to any programming language.
⢠In c++ cin and cout are used to input data and to output the data.
cin>> is used to get data from keyboard
cout<< is used to send the output to the screen.
⢠Preprocessor directive #include<iostream> must be used in order to handle
the input cin>> and output cout<< statement.
⢠The other type of input is gets(variableName) and
cin.getline(variablename,length).
⢠The gets(variableName) should be handle by preprocessor directive
#include<stdio>
⢠While cin.getline(variablename,length) should be handle by
preprocessor directive #include<string>
13. Example of input statement
Task Usage/sample input data
To input numeric data type int num1;
float num2;
cin>>num1>>num2; //input 10 5.5
To input 2 character data types char letter, symbol;
cin>>letter>>symbol; //input A #
To input sequence of characters (string) char custName[50];
gets(custName);
char custName[50];
cin.getline(custName,50);
14. Example of output statement
Task Usage/sample input data
To display labels
Enter 2 number:
cout<<âEnter 2 numbersâ;
To display result from an arithmetic
expression
cout<<5*2;
cout<<sum/count;
To display label Total is: and a value stored
in variable total. Complete output is
Total is:10
int total=10;
cout<<âTotal is:â<<total;
To display formatted output and
predefined symbol,
endl n
cout<<ânâ;
cout<<endl;
15. Operator and Expression
Operator
⢠An operator is a symbol that causes the compiler to take an
action
⢠Operators act an operands and in c++ all operands are
expressions.
⢠In c++ there are several different categories of operators.
These categories are:
a) Arithmetic operator
b) Assignment operator
c) Increment and Decrement operator
d) Relational operator
e) Logical operator
17. Compound Assignment
⢠Compound assignment
⢠(+=, -=, *=, /=, %=, >>=, <<=)
⢠When we want to modify the value of a
variable by performing an operation on the
value currently stored in that variable we can
use compound assignment operators:
18. Compound Assignment
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
19. Assignment Opertaor
⢠C++ has several assignment operators. The most
commonly used assignment operator is :
=
⢠Assignment operator using = has the general form:
identifier = expression
⢠Where identifier generally represent variable and
expression represent constant, a variable or a more
complex expression.
20. Assignment Statement
⢠An assignment statement is used to place a value into another
variable coded directly within the program.
⢠In other words, the variable gets the value initially assigned to it in
the program (hard-coded) and not from the value keyed in by the
user.
⢠Example:
quantity=20;
price=5.50;
amount=basic_pay+overtime;
Another example:
counter ++; or also can written as counter=counter + 1;
sum=sum+num; or also can writen as sum+=num;
21. Increment and decrement operator
⢠increase operator (++) and the decrease operator (--)
⢠increase operator (++) increase by one the value stored in a variable.
⢠the decrease operator (--) reduce by one the value stored in a variable.
⢠They are equivalent to +=1 and to -=1, respectively.
⢠c++;
⢠c+=1;
⢠c=c+1;
⢠The three of them increase by one the value of c.
22. ⢠A characteristic of this operator is that it can be used both
as a prefix and as a suffix.
⢠That means that it can be written either before the variable
identifier (++a) or after it (a++).
⢠Although in simple expressions like a++ or ++a both have
exactly the same meaning.
⢠increase operator is used as a prefix (++a) the value is
increased before the result of the expression is evaluated.
⢠Used suffix (a++) the value stored in a is increased after
being evaluated and therefore the value stored before the
increase operation is evaluated in the outer expression.
23. Example 1
B=3;
A=++B;
// A contains 4, B contains 4
Example 2
B=3;
A=B++;
// 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.
24. RELATIONAL OPERATOR
⢠Relational operators (>, <, >=, <=)(==, !=, )
⢠In order to evaluate a comparison between two
expressions we can use the relational
⢠The result of a relational operation is a Boolean
value that can only be true or false, according to
its Boolean result.
⢠We may want to compare two expressions, for
example, to know if they are equal or if one is
greater than the other is.
25. ⢠Here is a list of the relational operators that can be used in C++:
⢠> Greater than
⢠< Less than
⢠>= Greater than or equal to
⢠<= Less than or equal to
⢠== Equal to
⢠!= Not equal to
⢠Here there are some examples:
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) / / evaluates to false.
26. ⢠Of course, instead of using only numeric constants, we
can use any valid expression, including variables.
Suppose that:
a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
27. ⢠Be careful! The operator = (one equal sign) is not the
same as the operator == (two equal signs).
⢠The first one is an assignment operator (=) is assigns
the value at its right to the variable at its left.
⢠(==) is the equality operator that compares whether
both expressions in the two sides of it are equal to
each other.
⢠Thus, in the last expression ((b=2) == a), we first
assigned the value 2 to b and then we compared it to a,
that also stores the value 2, so the result of the
operation is true.
28. LOGICAL OPERATOR
⢠Logical operators ( !, &&, || )
⢠The Operator ! is the C++ operator to perform the Boolean operation NOT.
⢠It has only one operand, located at its right, and the only thing that it does is
to inverse the value of it, producing false if its operand is true and true if its
operand is false.
⢠Basically, it returns the opposite Boolean value of evaluating its operand. For
example:
!(5 == 5) // evaluates to false because the expression at its right
(5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
29. ⢠The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
⢠The operator && corresponds with Boolean logical operation AND.
This operation results true if both its two operands are true, and
false otherwise.
⢠The following panel shows the result of operator && evaluating the
expression a && b:
⢠&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
30. ⢠The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its two operands is true,
thus being false only when both operands are false themselves.
⢠Here are the possible results of a|| b:
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
⢠For example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
31. Precedence of operators
⢠When writing 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
32. ⢠a = 5 + (7 % 2) // with a result of 6, or
⢠a = (5 + 7) % 2 // with a result of 0
33. ⢠The correct answer is the first of the two
expressions, with a result of 6.
⢠There is an established order with the priority
of each operator, and not only the arithmetic
ones (those whose preference come from
mathematics) but for all the operators which
can appear in C++.
⢠From greatest to lowest priority, the priority
order is as follows:
35. EXPRESSION
⢠Anything that evaluates to a value is an
expression in c++.
⢠This expression is said to return a value.
⢠Thus, 3+2 return a value of 5 and so is an
expression.
⢠All expression are statement
Example:
x=a+b+c;
Num1+num2;