You are on page 1of 32

COMPUTER PROGRAMMING

LECTURE # 2: VARIABLES &


OPERATORS

BSE 1
Joddat Fatima
1
joddat.fatima@gmail.com

Department of C&SE
Bahria University Islamabad
VALUES & VARIABLES

2
VALUE

 The only task a computer can do is arithmetic e.g.


multiplying, dividing, subtracting, etc.

 Therefore, everything in the computer is represented as a


value
 Numbers, letters, characters, etc. are all represented as values

 Values could change depending on their nature. For example


 The temperature today is different from the temperature yesterday
 The number of cars inside Lahore is different then the number of in
cars Islamabad.

3
VARIABLES

 To store a value inside a computer a ‘variable’ is used.

 A variable is a space in the memory to store a value.

 This space is reserved until the variable is required.

 Variable has three important characteristics:


 Type: How much memory do a variable need.
 Name: Name refers to the memory location assigned to this variable.
 Value: The actual value contained by a variable.
4
EXAMPLE OF VARIABLE

5
TYPES OF VARIABLES
Variable type Keyword used in Size in bits
declaration

Unsigned integer int 16 bits

signed integer signed int 16 bits

Long integer long int 32 bits

Floating point data float 32 bits

Floating point data double 64 bits


(with large fraction)

6
Text type data char 8 bits
TYPES OF VARIABLES
 To use a variable in our code
 First, we must have to declare it, variable are known with its
keywords. “Use the name of keyword” for declaration of a variable”.
 Example: int number1 = 10;
 Example: float floatData = 20.93;
 Example: signed int myData = -10;
 Example: char textData = ‘A’;

#include <stdio.h>
#include <stdio.h> void main (void)
void main (void) {
{ int number1 = 20, number2 = 10;
int number1 = 10; }
float floatData = 20.93;
7
}
MANIPULATING VARIABLES

 Assignment Statement
 In Mathematics the value x = x + 1 is not possible why?
 In C++ x = x +1 is possible because “=” is an assignment operator
and not an equality operator.
 Assignment operator means that the contents of the right hand side
is transferred to the memory location of the left hand side.

8
CONSTANTS
 Constants are values which cannot be modified e.g. the value
of Pi
 To declare a constant in C++, we write a keyword “const”
before the variable type.
const double pi = 3.14;

RESERVE WORDS
 Some names cannot be declared as variable names because
they are reserved words in C++

9
TYPE CHAR
 Computers process character data too char
 Shortfor character
 Can be any single character from the keyboard

 char constants
 Character constants are enclosed in single quotes
char letter = 'a';
 Strings of characters, even if only one character is enclosed in
double quotes
 "a" is a string of characters containing one character
 'a' is a value of type character

10
TYPE BOOLEAN

 bool is a new addition to C++


 Shortfor Boolean
 Boolean values are either true or false

 To declare a variable of type bool:


bool old_enough;

11
CASTING

 Converting a value of one type into another type


 Manual Casting

 static_cast<double> (intVar)

 Explicit type casting operator


 int i;
 float f = 3.14;
 i = (int) f;

 The code converts the float number 3.14 to an integer value


(3), the remainder is lost
12
VARIABLES EXAMPLES

int a; int a, b, c;
int a;
float mynumber; int b;
int c;
unsigned NextYear; short Year;
unsigned int NextYear; short int Year;

unsigned short int NumberOfSisters;


signed int MyAccountBalance;

13
VARIABLE CODE EXAMPLE

#include <iostream> Output:


using namespace std;
4
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
return 0; 14
}
STRING

 Variables that can store non-numerical values that are


longer than one single character are known as strings.

 The C++ language library provides support for strings


through the standard string class.

 Include an additional header file is required in our source


code: <string> and have access to the std namespace

15
STRING EXAMPLE

16
CHARACTER AND STRING LITERALS

 There also exist non-numerical constants, like:


'z'
'p'
"Hello world"
"How
do you do?“
 The first two expressions represent single character
constants, and the following two represent string literals
composed of several characters.

 Notice that to represent a single character we enclose it


between single quotes (') and to express a string we enclose 17
it between double quotes (").
CHARACTER AND STRING LITERALS

 When writing both single character and string literals, it is necessary to


put the quotation marks surrounding them to distinguish them from
possible variable identifiers or reserved keywords.
x and 'x‘
 x alone would refer to a variable whose identifier is x, whereas 'x'
would refer to the character constant.

 These are special characters that are difficult or impossible to express


otherwise in the source code of a program, like newline (\n) or tab (\t).
All of them are preceded by a backslash (\).

18
LIST OF ESCAPE CODES

 \n newline
 \r carriage return

 \t tab

 \v vertical tab

 \b backspace

 \f form feed (page feed)

 \a alert (beep)

 \' single quote (')

 \" double quote (")

 \? question mark (?)


19
 \\ backslash (\)
OPERATORS

20
OPERATOR PRECEDENCE AND ASSOCIATIVITY

 Operators Precedence and Associativity for C++ is


following:
 *, /, %  Do all multiplications, divisions and remainders from
left to right.
 +, -, Do additions and subtractions from left to right.

 So far the variable types that we have studied are primitive


data types.
 Primitive data types only have a memory space for storing
values.

21
MANIPULATING VALUES
 Mathematical Operators
• Common mathematical operators are available in C++ for
manipulating values e.g. addition(+), subtraction(-),
multiplication(*), division(/), and modulus (%).
 C++ has many other operators also which we will study in
due course.

ARITHMETIC EXPRESSIONS
 Operator Precedence
 Operator precedence controls the order in which operations are
performed
 Operator Associativity
22
 The associativity of an operator specifies the order in which
operations of the same precedence are performed
 Assignment (=)
a = 5;
 a = b;

 Arithmetic operators ( +, -, *, /, % )
 The five arithmetical operations supported by the C++ language are:
 + addition
 - subtraction

 * multiplication

 / division

 % modulo

23
 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=,
&=,^=, |=)

 Increase and decrease (++, --)


 c++;
 c+=1;
 c=c+1;

24
 Relational and equality operators ( ==, !=, >, <, >=, <= )
 == Equal to
 != Not equal to
 > Greater than
 < Less than
 >= Greater than or equal to
 <= Less than or equal to

 Logical operators ( !, &&, || )


 !0=1
 !1=0

25
 Comma operator ( , )
 The comma operator (,) is used to separate two or more expressions
that are included where only one expression is expected. For
example, the following code:
a = (b=3, b+2);

 Conditional operator ( ? )
 The conditional operator evaluates an expression returning a value if
that expression is true and a different one if the expression is
evaluated as false. Its format is:
condition ? result1 : result2

 If condition is true the expression will return result1, if it is not it


will return result2.
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. 26
FLOW CHARTS
 A flowchart is a visual or graphical representation of an
algorithm.
 The flowchart employs a series of blocks and arrows, each of which
represents a particular operation or step in the algorithm.
 The arrows represent the sequence in which the operations are
implemented.

27
EXAMPLES OF FLOW CHARTS

28
COMPARISON OF ALGORITHM, FLOWCHART
AND PSEUDO-CODE

29
FLOW CHART PRACTICE SESSION

30
CALCULATE AND PRINT THE AVERAGE GRADE
OF 3 TESTS FOR THE ENTIRE CLASS
 Input
 3 test scores for each student
 Output
 Average of 3 tests for each student
 Process
1. Get three scores
2. Add them together
3. Divide by three to get the average
4. Print the average
5. Repeat step 1 to 4 for next student
6. Stop if there are no more students
31

31
ALGORITHM ATM FOR WITHDRAWAL
 Output
 Money, error messages
 Inputs
 User Identification (ATM card), password, amount
 Process
1. Get the ATM card for identification and ask for password
2. Check password
3. If password is not valid, generate an error message and go to step number 8.
4. Get the amount from the user
5. Check the current balance
6. If amount is greater than current balance, generate an error message and go to
step number 8.
7. Subtract the amount from the balance and give out the cash.
8. Return the ATM card
9. Stop

32

You might also like