You are on page 1of 42

Variables and operators

In this lecture we will see


n Variable
n What
n Declaration
n Initialization
n By the programmer
n Input by the user
In this lecture we will see (cont)

n Operator
n What
n Types of operators
n Operator rules
Example – adding 2 numbers
n Yousof: Hey Khalifa, I just learned how to add two numbers
together.
n Khalifa: Cool!
n Yousof : Give me the first number.
n Khalifa: 2.
n Yousof : Ok, now give me the second number.
n Khalifa: 5.
n Yousof : Ok, here's the answer: 2 + 5 = 7.
n Khalifa: Wow! Yousof you are AMAZING!

after Khalifa says “2”, Yousof has to keep this number in his mind.
after Khalifa says “5”, Yousof also needs to keep this number in his
mind.
First number: 2 Second number: 5 Sum: 7
Variables
n A variable refers to memory location associated
with a memory address where a value of a
specified type may be stored
n The value of a variable can be changed during the
program execution
n The variable is referred to by a name
Variable: what for?

n To get input values from the users/files and


store these values into the defined variables
n To extract the content of these variables and
produce the output values
n To modify and change the content of these
variables to some other values
Variables Types
n Common data types
n Numeric types (NT) and Non-Numeric types (NNT)
Data types Description Size in Bytes example
int Integer 4 1234
NT float Single floating point 4 (6 Decimal Digits) 15.345
double Double floating point 8 (15 Decimal Digits) 7.883774
bool Boolean (true, false) 1 true/false
char Characters 1 ‘A’

n An integer type is a number without a fractional part


n Will be stored exactly (Example: 3, 7, 999, 100000)
n A floating-point type is a number with a fractional part
n Will be rounded off (Example: 5.54, 3.22)
Variable Declaration
n Tell the compiler, what variables you want to use
n Variables MUST be declared with a data type and a
name BEFORE they can be used
n Variables can be declared anywhere in the program
n Usually after the main() function directly

n Single variable declaration statement:


n Syntax: <datatype> <variable_name>;
n Example: int x;
n Declares a variable named x of type int

n Multiple variables declaration statement of same type


n Syntax: <datatype> <var1>, <var2>, <var3>;
n Example: int x,y,z;
Variables Declaration (cont)

n When you declare a variable, the compiler:


n Reserves a memory location in which to store the
value of the variable.
n Associates the name of the variable with the memory
location. (You will use this name for referring to the
constant or variable.)
n Specifies the type of the information that will be
stored in that location and defines its size.
Variables: Exercise-1
n We want to write a program that computes and
displays the area of a circle. Show what variables you
will need and how you will declare them, assuming
you have done the following analysis
Input: Radius of the circle
output: Area of the circle
Process : Compute the area
Variables: Exercise-1
- One variable for the radius , type : real number ;
- One variable for the area, type : real number ;

float Radius, Area ;


Comments about Variables naming
n Variables should be descriptive of what they stand for
n Example: to store a POBox number, you can declare it as:
int POBox;

n Rules for naming Variables


n Can only contain letters (A-Z,a-z), digits (0-9), underscores (_) and
dollar sign ($) in new versions
n Must starts with letters, underscore (_) or $
n Cannot begin with digit
n Cannot contain special characters (except for $)
n Cannot contains spaces or dot (.)
n Cannot use reserved words of C++ language
n Case sensitive
Comments about Variables naming
n Cannot use C++ reserved words
n C++ contains many reserved words and each keyword has a
predefined purpose in the language.

bool, break, case, char, const,


continue, do, default, double, else,
false, float, for, if, int, long,
namespace, return, short, static,
struct, switch, true, void, while
Examples
Variable VALID? REASON IF INVALID

integer1

Integer_1

integer$ Some special char are not


integer& allowed

integer.1/ integ 1 No(.) or spaces

1integer Cannot begin with digit

if, while, void Reserved words


Variable Initialization (1)
n First Way (programmer): Using the assignment operator (=)
n Assigns value to variable
n Used to store values results from expression to variables
variable = expression;

n Variables can be declared and then initialized


<datatype> <variable>;
<variable> = initial_value;
int sum; /* the value of sum can be anything (garbage) */
sum = 7;

n Variables can be declared and initialized simultaneously


<datatype> <variable> = initial_value;
15
int sum = 1;
Variables: Exercise-2
n Write the instructions that declare and
initialize to 0, the variables defined in
exercise 1
OR

float Radius, Area ;


float Radius =0 ;
Radius =0;
float Area =0 ;
Area = 0;
Constant Declarations
n Constants are used to store values that never change
during the program execution.
n Constant variables must be initialized at the same time of
declaration
n Constants must be declared before the main function
n Syntax:
const <type> <identifier> = <expression>;
<type> const <identifier> = <expression>;

Examples:
const float pi = 3.1415;
float const pi = 3.1415;
Variables: Exercise-3
n Using the variables of exercise-2, write
a program that computes the area of
circle. Assume the following:
n The program uses a constant for PI
n The value of radius is assigned by the
programmer at the initialization
Variables: Exercise-3
#include <iostream>
using namespace std;
const float PI = 3.1415; // PI constant declaration
int main()
{
float Area =0 ; //declaration and initialization of the area
float Radius =2.5 ; // declaration of the variable and assigning of
//a value to it by the programmer
Area = PI*Radius*Radius ;
cout << “The Area is ”<< Area<<endl ; // prints the Area
return 0;
}
Variable Initialization (2)
n Second Way (by the user): using Standard Input Stream
object cin (see-in) with the stream extraction operator >>:
n >> is used with cin (see-in)
n It waits for user to input value (the keyboard by default), then
process the data once the Enter (Return) key has been pressed
n It stores value in variable to right of operator
n Skips over white spaces (space, tab, newline).

n Example:
int num1;
cin >> num1;

20
Example
n Write a C++ program that reads two integer
numbers add them and print the result of
addition

n The program must ask the user to enter the first


number and the second number

n The program must also display the result of the


addition of the two numbers
Variable Initialization (2)
n Correct Way

/* Variables must be declared before */


/* being used. */
int num1, num2;

/* Variable Initialization by a user */


/* Request two values from the user */
/* First Way: Separate lines */
cin >> num1;
cin >> num2;

/* OR: Second Way: a single line */


cin >> num1 >> num2;
Variable Initialization (2)
n Incorrect Ways (generates syntax error)
n Using the insertion operator (wrong direction) with cin
cin << num1 << num2;

n Using comma between the two variables instead of >>


cin >> num1, num2;

n Using endl or \n with the cin is not allowed


cin >> endl;
cin >> “\n”;

n Putting variables within double quotation marks “ “


cin >> “num1”;
#include <iostream>
using namespace std;
int main()
{ int num1, num2, sum; //declaration
Notice how cin is used to get the user input.

cout << “ Please enter first number \n” ; // prompt


cin >> num1; // read the first integer
cout << “ Please enter second number \n” ; // prompt
cin >> num2; // read the second integer

sum = num1 + num2; // assignment


cout << “The sum is ”<<sum<<endl ; // print the value of sum
return 0;
} Variables can be output using cout << variableName.

Please enter first number


4
Please enter second number
5
The sum is 9
Find the errors in this program
/* This is a practice example
Find the errors in this program. */
#include <iostream>
using namespace std;
void main()
{ int num1; num2; 2sum;
cout << “ Please enter two numbers \n ”;
cin >> “num1”>>endl;
cin >> Num2;

cout << “The sum is ”<<“num1+ mun2” <<endline ;

return 0;
}
Correct version
/* This is a practice example
Solution . */
#include <iostream>
using namespace std;
int main()
{ int num1, num2, sum;
cout << “ Please enter two numbers \n“ ;
cin >> num1;
cin >> num2;
/* or you can write: cin >> num1 >> num2; */
sum= num1 + num2;
cout << “The sum is “<<sum<<endl ;
return 0;
}
Memory Concept
num1 4
cin >> num1;
– Assume user entered: 4
num1 4
num2 5
cin >> num2;
– Assume user entered: 5
num1 4
num2 5
sum = num1 + num2; sum 9
Operators
n Symbols telling the compiler to perform
a specific arithmetic or logical
operations
n Arithmetic operators
n Assignment operators
n Logical operators
n And more…
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
C++ operation Arithmetic Algebraic C++ expression Example
operator expression
Addition + x+7 x + 7 x = 4 + 2;
Subtraction - x-y x – y x = 4 - 2;
Multiplication * x*y x * y x = 4 * 2;
Division / x / y x / y x = 4 / 2;

Modulus % x mod y x % y x = 4 % 2;
Modulus (%)
n Modulus (%) returns the remainder of the division
n cout<< 3 % 2; // evaluates to 1
n cout<< 4 % 2; // evaluates to 0
n cout<< 6 % 2; // evaluates to 0
n cout<< 7 % 2; // evaluates to 1
n cout<< 8.0%2; // compiler error

n Note that both operands must be integers

n Modulus can only be used with integer types


Assignment operator =
Preliminary:
What is an expression?
An expression is a combination of variable, constants
and operators:
Examples:
2*Num1 + Num2 + 3
Num1+ 5
Num1/Num2
7–5
5
Assignment operator =
Syntax:
Variable_name = expression ;

Notes:
- It is not the equality operator
- It assigns the value (result) of the expression to a variable
Examples:
Area = Side*Side ;
Average = (Num1 + Num2)/2 ;
Num = 7 ;
Assignment operator =
Rule: The left side and the right side of an assignment
operation must be of the same type

int Num1; left-side = right-side


double Num2 ;

Num2 = 3.75 ;
What is wrong in this code?
Num1 = Num2 ;
Operator precedence
n5+Num*7
Which operation is performed first ?

n *, /, % are at higher level of precedence than +


and –

n If you want to impose a given operation to be


executed first, use the parenthesis
Example: (5 + Num1)* 7
Logical operators
&& logical AND
|| logical OR
! Logical NOT

When Logical operations are evaluated they can only


give true (non zero) or false (zero) value.
Logical Operators
X Y !X X && Y X || Y

True True False True True


True False False False True
False True True False True
False False True False False

n Note that (anything) will not be evaluated in


36
both cases: “short circuit”
Logical Operators
n Examples

37
Comparison operators
Operator Meaning
=========================
< less than
> greater than
<= less than or equal
>= greater than or equal
== equals to
!= not equals to
Comparison operators
n Comparison operators used to form conditions that are evaluated by
the compiler to either true or false
n Example: assume num1 = 3 and num2 =5, how the compiler will
evaluate each of these expressions:
num1 < num2
num1 <= num2
num1 > num2
num1 >= num2
num1 == num2
num1 != num2
Increment/Decrement operators
Increment operator ++
This operator adds 1 to a variable
Num++ ; // is equivalent to Num = Num +1 ;

Decrement operator --
This operator subtracts 1 from a variable
Num-- ; // is equivalent to Num =Num -1 ;
Operators Precedence (2)
Operator(s) Operation(s) Order of evaluation (precedence)

High () Parentheses If the parentheses are nested, the expression in the


innermost pair is evaluated first. If there are several
Priority pairs of parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
!, - Not, negative

*, /, or % Multiplication Division Evaluated left to right.


Modulus Arithmetic
+ or - Addition Evaluated left to right.
Subtraction
>, <, >=, <= Rational Operators Relation
==, != Equality Operator Equality
&& Logical AND
Logical
|| Logical OR
low
Priority = Assignment Operator Assignment
41
Example 1
n Given a = 2, b = 3, c = 6

n (a*2 > b && c < 10)


n True
n (c*b % 2)
n False
n (!true && true && false)
n (true || true && false)
n True
42

You might also like