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

Variables and Operators: C++ Basics

This document discusses variables and operators in C++. It defines variables as memory locations that can store values of a specified type. Variables must be declared with a data type and name before use. Common data types include integers, floats, booleans and characters. The document also discusses initializing variables through programmer assignment or user input via cin. Constants are variables that do not change value and must be initialized at declaration. Operators are also introduced but not explained in detail.

Uploaded by

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

Variables and Operators: C++ Basics

This document discusses variables and operators in C++. It defines variables as memory locations that can store values of a specified type. Variables must be declared with a data type and name before use. Common data types include integers, floats, booleans and characters. The document also discusses initializing variables through programmer assignment or user input via cin. Constants are variables that do not change value and must be initialized at declaration. Operators are also introduced but not explained in detail.

Uploaded by

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

VARIABLES AND OPERATORS

C++ BASICS
IN THIS LECTURE WE WILL SEE

• Variable
• What
• Declaration
• Initialization
• By the programmer
• Input by the user
IN THIS LECTURE WE WILL SEE
(CONT)
• Operator
• What
• Types of operators
• Operator rules
EXAMPLE – ADDING 2 NUMBERS
• Yousof: Hey Khalifa, I just learned how to add two numbers together.
• Khalifa: Cool!
• Yousof : Give me the first number.
• Khalifa: 2.
• Yousof : Ok, now give me the second number.
• Khalifa: 5.
• Yousof : Ok, here's the answer: 2 + 5 = 7.
• 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

A variable refers to memory location associated


with a memory address where a value of a
specified type may be stored
The value of a variable can be changed during the
program execution
The variable is referred to by a name
VARIABLE: WHAT FOR?
• To get input values from the users/files and store these values into the defined
variables
• To extract the content of these variables and produce the output values
• To modify and change the content of these variables to some other values
VARIABLES TYPES
• Common data types
• Numeric types (NT) and Non-Numeric types (NNT)
Data types Description Size in Bytes example
int Integer 4 1234
float Single floating point 4 (6 Decimal Digits) 15.345
NT double Double floating point 8 (15 Decimal Digits) 7.883774
bool Boolean (true, false) 1 true/false
char Characters 1 ‘A’

• An integer type is a number without a fractional part


• Will be stored exactly (Example: 3, 7, 999, 100000)
• A floating-point type is a number with a fractional part
VARIABLES DECLARATION
 Variables can be declared anywhere in the program
 Usually after the main() function directly
 Variables MUST be declared with a data type and a name BEFORE they can be used

 Single variable declaration statement:


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

 Multiple variables declaration statement of same type


 Syntax: <datatype> <var1>, <var2>, <var3>;
 Example: int x,y,z;
VARIABLES DECLARATION (CONT)
• When you declare a variable, the compiler:
• Reserves a memory location in which to store the value of the variable.
• Associates the name of the variable with the memory location. (You will use this name for
referring to the constant or variable.)
• Specifies the type of the information that will be stored in that location and defines its
size.
VARIABLES: EXERCISE-1
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
•Variables should be descriptive of what they stand for
• Example: to store a POBox number, you can declare it as:
int POBox;

• Rules for naming Variables


• Can only contain letters (A-Z,a-z), digits (0-9), underscores (_) and
dollar sign ($) in new versions
• Must starts with letters, underscore (_) or $
• Cannot begin with digit
• Cannot contain special characters (except for $)
• Cannot contains spaces or dot (.)
• Cannot use reserved words of C++ language
• Case sensitive
COMMENTS ABOUT VARIABLES
NAMING
Cannot use C++ reserved words
 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)
• First Way (programmer): Using the assignment operator (=)
• Assigns value to variable
• Used to store values results from expression to variables
variable = expression;

• Variables can be declared and then initialized


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

• Variables can be declared and initialized simultaneously


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

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

Examples:
const float pi = 3.1415;
float const pi = 3.1415;
VARIABLES: EXERCISE-3
• Using the variables of exercise-2, write a program that computes the area of
circle. Assume the following:
• The program uses a constant for PI
• 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)
• Second Way (by the user): using Standard Input Stream
object cin (see-in) with the stream extraction operator >>:
• >> is used with cin (see-in)
• It waits for user to input value (the keyboard by default), then
process the data once the Enter (Return) key has been pressed
• It stores value in variable to right of operator
• Skips over white spaces (space, tab, newline).

• Example:
int num1;
cin >> num1;

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

• The program must ask the user to enter the first number
and the second number

• The program must also display the result of the addition


of the two numbers
VARIABLE INITIALIZATION (2)
• 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)
Incorrect Way (generates syntax error)
 Using the insertion operator (wrong direction) with cin
cin << num1 << num2;

 Using comma between the two variables instead of >>


cin >> num1, num2;

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


cin >> endl;
cin >> "\n";

 Putting variables within double quotation marks " "


cin >> "num1";
#include <iostream>
using namespace std;
int main()
{ int num1, num2, sum; Notice how cin is//declaration
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
Variables can be output using cout <<
variableName.
Please enter first number
sum = num1 + num2; // assignment
4
Pleasecout
enter
<< second number
“The sum is ”<<sum<<endl ; // print the value of
5
Thesum
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"


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 >>
MEMORY CONCEPT
num1 4
cin >> num1;
Assume user entered: 4
num1 4

cin >> num2; num2 5


Assume user entered: 5

num1 4
num2 5
sum = num1 + num2;
sum 9
OPERATORS
• Symbols telling the compiler to perform a specific arithmetic or logical
operations
• Arithmetic operators
• Assignment operators
• Logical operators
• And more…
ARITHMETIC OPERATORS
+ Addition
- Subtraction
* Multiplication
/ Division
%C ++ o p eModulus
ra tio n Arith m e tic
o p e ra to r
Alg e b ra ic
e xp re ssio n
C ++ e xp re ssio n Exa m p le

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 (%)
• Modulus (%) returns the remainder of the division
• cout<< 3 % 2; // evaluates to 1
• cout<< 4 % 2; // evaluates to 0
• cout<< 6 % 2; // evaluates to 0
• cout<< 7 % 2; // evaluates to 1
• cout<< 8.0%2; // compiler error

• Note that both operands must be integers

• Modulus can only be used with integer types


ASSIGNMENT OPERATOR =
Preliminary:
What is an expression?
An expression is any 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 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;

double Num2 ;
left-side = right-side

Num2 = 3.75 ;
What is wrong in this code?

Num1 = Num2 ;
OPERATOR PRECEDENCE
5+Num*7
Which operation is performed first ?

*, /, % are at higher level of preference than + and –

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

36
LOGICAL OPERATORS
 Examples

37
COMPARISON OPERATORS
OperatorMeaning
=========================

< less than


> greater than
<= less than or equal
>= greater than or equal
== equals to
!= not equals to
COMPARISON OPERATORS
 Comparison operators used to form conditions that are evaluated by the compiler to either true or
false
 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
=
41
Assignment Operator Assignment
EXAMPLE 1
• Given a = 2, b = 3, c = 6

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


• True

• (c*b % 2)
• False

• (!true && true && false)


• (true || true && false)
• True
END

You might also like