SlideShare a Scribd company logo
Variables, Constants,
and Operators
(Computer Programming)
By
Dr. Muhammad Aleem,
Department of Computer Science,
Mohammad Ali Jinnah University, Islamabad
Fall Semester 2013
Scope
• The scope of a variable: the part of the
program in which the variable can be accessed
• A variable cannot be used before it is defined
• Example:…
Scope
• Different levels of scope:
1. Function scope
2. block scope
3. File scope
4. Class scope
Local variables
Global variables
Scope
• Function scope example…
• Block scope example…
• File scope example…
Visibility
 A variable is visible within its scope, and
invisible or hidden outside it.
Lifetime of Variables
• The lifetime of a variable is the interval of
time in which storage is bound to the variable.
• The action that acquires storage for a variable
is called allocation.
Lifetime of Variables
•Local Variables (function and block scope)
have lifetime of the function or block
•Global variable (having file level scope) has
lifetime until the end of program
•Examples…
Literals Constants
• Built-in types
– Boolean type
• bool
– Character types
• char
– Integer types
• int
–and short and
long
– Floating-point types
• double
–and float
• Standard-library types
– string
Literals
• Boolean: true, false
• Character literals
– 'a', 'x', '4', 'n', '$'
• Integer literals
– 0, 1, 123, -6,
• Floating point literals
– 1.2, 13.345, 0.3, -0.54,
• String literals
– "asdf”, “Helllo”, Pakistan”
• Named constants are declared and referenced by
identifiers:
const int max_marks = 100; // (MAX_MARKS rec..)
const string UNIVERSITY = “ALI";
const double PI = 3.141592654;
const char TAB = 't';
• Constants must be initialized in their declaration
• No further assignment possible within program
Constants (named)
• Implementation Limits
#include <climits> //Implementation constants defined here
INT_MIN INT_MAX
LONG_MIN LONG_MAX
#include <cfloat> //location of float constants
FLT_MIN FLT_MAX
DBL_MIN DBL_MAX
Lower and upper bounds
for Integer types.
C++ Standard Constants
Lower and upper bounds
for Decimal types.
Binary Arithmetic Operators
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2
Remainder operator is also known as modulus operator
Integer and Real Division
float result = 5 / 2; //  result equal to 2
float result = 5.0 / 2; //  result equal to 2.5
 If any of the operand is a real value (float or
double) the division will be performed as “Real
Division”
Remainder/Modulus operator
• Operands of modulus operator must be
integers
 34 % 5 (valid, result  4)
 -34 % 5 (valid, result  -4)
 34 % -5 (valid, result  4)
 -34 % -5 (valid, result  -4)
• 34 % 1.2 is an Error
Using Remainder Operator
• Class Exercise:
– Write Pseudocode/flow-chart to identify Odd and
Even numbers between M and N?
Arithmetic Expressions
)
94
(9
))(5(10
5
43
y
x
xx
cbayx
is translated to
result = (3+4*x)/5 – (10*(y-5)*(a+b+c))/x + 9*(4/x + (9+x)/y)
• Convert following expression into C++ code
result =
Example: Converting Temperatures
- Write a program that converts a Fahrenheit to
Celsius using the formula:
)32)((9
5
fahrenheitcelsius
23/09/2013
Shorthand/Compound Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
Increment and Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and
evaluates to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and
evaluates to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.
Increment and Decrement Operators
• Evaluate the followings:
int val = 10;
int result = 10 * val++;
cout<<val<<“ “<<result;
int val = 10;
int result = 10 * ++val;
cout<<val<<“ “<<result;
Example Program (Incr. Dec. Operators)
Numeric Type Conversion
Consider the following statements:
short i = 10;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
cout<<d;
Type Conversion Rules
• Auto Conversion of Types in C++
1. If one of the operands is long double, the other is converted
into long double
2. Otherwise, if one of the operands is double, the other is
converted into double.
3. Otherwise, if one of the operands is unsigned long, the other is
converted into unsigned long.
4. Otherwise, if one of the operands is long, the other is
converted into long.
5. Otherwise, if one of the operands is unsigned int, the other is
converted into unsigned int.
6. Otherwise, both operands are converted into int.
Implicit Type Conversion in C++
Typecasting
• A mechanism by which we can change the data
type of a variable (now matter how it was
originally defined)
• Two ways:
1. Implicit type casting (done by compiler)
2. Explicit type casting (done by programmer)
Implicit type casting
• As seen in previous examples:
void main()
{
char c = 'a';
float f = 5.0;
float d = c + f;
cout<<d<<“ “<<sizeof(d)<<endl;
cout<<sizeof(c+f);
}
Implicit Type Casting
Explicit type casting
• Explicit casting performed by programmer. It is
performed by using cast operator
float a=5.0, b=2.1;
int c = a%b; //  ERROR
• Three Styles
int c = (int) a % (int) b; //C-style cast
int c = int(a) % int(b); // Functional notation
int c = static_cast<int>(a) % static_cast<int>(b);
cout<<c;
Explicit Type Casting
- Casting does not change the variable being cast.
For example, d is not changed after casting in the
following code:
double d = 4.5;
int j = (int) d; //C-type casting
int i = static_cast<int>(d); // d is not changed
cout<<j<<“ “<<d;
• A "widening" cast is a cast from one type to
another, where the "destination" type has a larger
range or precision than the "source“
Example:
int i = 4;
double d = i;
Widening type casting
• A “narrowing" cast is a cast from one type to
another, where the "destination" type has a
smaller range or precision than the "source“
Example:
double d = 787994.5;
int j = (int) d;
// or
int i = static_cast<int>(d);
Narrowing type casting
Casting between char and Numeric Types
int i = 'a'; // Same as int i = (int) 'a';
char c = 97; // Same as char c = (char)97;
- The increment and decrement operators can also
be applied on char type variables:
-Example:
char ch = 'a';
cout << ++ch;
Using ++, -- on “char” type
-- C style (we will study in pointers topic)
-- C++ style:
-#include<sstream>
-void main() {
-int val=0;
-stringstream ss;
-cout<<“Enter Value: “; cin>>val;
-ss << val; //Using stream insertion op.
string str_val= ss.str();
cout<<“n Output string is: “<<str_val;
}
int to string Conversion
Equality and Relational Operators
• Equality Operators:
Operator Example Meaning
== x == y x is equal to y
!= x != y x is not equal to y
• Relational Operators:
Operator Example Meaning
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Logical Operators
• Logical operators are useful when we want to test
multiple conditions
• Three types:
1. boolean AND
2. boolean OR
3. boolean NOT
Boolean AND or logical AND
• Symbol: &&
• All the conditions must be true for the whole
expression to be true
–Example:
if ( (a == 10) && (b == 10) && (d == 10) )
cout<<“a, b, and d are all equel to 10”;
Boolean OR / Logical OR
• Symbol: ||
• ANY condition is sufficient to be true for the
whole expression to be true
–Example:
if (a == 10 || b == 9 || d == 1)
// do something
Boolean NOT/ Logical NOT
• Symbol: !
• Reverses the meaning of the condition (makes a
true condition false, OR a false condition true)
–Example:
if ( ! (marks > 90) )
// do something
Conditional Operator
• The conditional operator is a ternary operator (three
operands), is used to simplify an if/else statement.
• We will study this after if statement
41
Bitwise Operators (integers)
• Bitwise "and" operator &
• Bitwise "or" operator |
• Bitwise "exclusive or" operator ^
– (0 on same bits, 1 on different bits)
• Bitwise "ones complement" operator ~
• Shift left <<
• Shift right >>
Bitwise Operators (Example)
int i = 880;  1 1 0 1 1 1 0 0 0 0
int j = 453;  0 1 1 1 0 0 0 1 0 1
i & j (320) 0 1 0 1 0 0 0 0 0 0
i | j (1013) 1 1 1 1 1 1 0 1 0 1
i ^ j (693) 1 0 1 0 1 1 0 1 0 1
~j (-454) 1 0 0 0 1 1 1 0 1 0
i = i<<1; (1760) 1 0 1 1 1 0 0 0 0 0
i = i>>1; (440) 0 1 1 0 1 1 1 0 0 0
unsigned
int
Precedence Rules
• Precedence rules are vital when we have mix of many
operators in an expression: x = 3 * a - ++b%3;
• Two Important Terms:
1. Precedence Rules: specify which operator is
evaluated first when two operators are adjacent
in an expression.
2. Associativity Rules: specify which operator is
evaluated first when two operators with the same
precedence are adjacent in an expression.
Precedence Rules
(Unary Operators)
(Binary Operators)
Precedence Rules – Example 1
6 + 2 * 3 - 4 / 2
6 + 6 - 4 / 2
6 + 6 - 2
12 - 2
10
Precedence Rules – Example 2
3 * 4 / 2 + 3 - 1
12 / 2 + 3 - 1
6 + 3 - 1
9 - 1
8
Precedence Rules – Example 3
8 * 3 / 2 + 3 - 1
24 / 2 + 3 - 1
12 + 3 - 1
15 - 1
14
8 / 3 * 2 + 3 - 1
2 * 2 + 3 - 1
4 + 3 - 1
7 - 1
6
Precedence Rules (overriding)
• For example: x = 3 * a - ++b % 3;
• If we intend to have the statement evaluated
differently from the way specified by the
precedence rules, we need to specify it using
parentheses ( )
• Using parenthesis:
x = 3 * ((a - ++b)%3);

More Related Content

What's hot

Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
guptkashish
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
CtOlaf
 
What is c
What is cWhat is c
What is c
pacatarpit
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
mcollison
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
Md.Mojibul Hoque
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
Claus Wu
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Amir Ali
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
umar78600
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
SzeChingChen
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
ramya marichamy
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
Connex
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
Farag Zakaria
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 

What's hot (18)

Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
What is c
What is cWhat is c
What is c
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 

Viewers also liked

Unit iv
Unit ivUnit iv
Unit iv
snehaarao19
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Hitesh Kumar
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Java server pages
Java server pagesJava server pages
Java server pages
Tanmoy Barman
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
JavaTportal
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
APSMIND TECHNOLOGY PVT LTD.
 

Viewers also liked (9)

Unit iv
Unit ivUnit iv
Unit iv
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 

Similar to Cs1123 4 variables_constants

02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
shashikant pabari
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
valerie5142000
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
Vladislav Hadzhiyski
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
sunila tharagaturi
 
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
amankr1234am
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
C language
C languageC language
C language
Robo India
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
raksharao
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
Mukund Trivedi
 
Lab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressionsLab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressions
AksharVaish2
 
C fundamental
C fundamentalC fundamental
C fundamental
Selvam Edwin
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
3.Loops_conditionals.pdf
3.Loops_conditionals.pdf3.Loops_conditionals.pdf
3.Loops_conditionals.pdf
NoumanSiddiqui12
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
Sachin Sharma
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
Ralph Weber
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
Eric Chou
 

Similar to Cs1123 4 variables_constants (20)

02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
C language
C languageC language
C language
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Lab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressionsLab 4 reading material formatted io and arithmetic expressions
Lab 4 reading material formatted io and arithmetic expressions
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
3.Loops_conditionals.pdf
3.Loops_conditionals.pdf3.Loops_conditionals.pdf
3.Loops_conditionals.pdf
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
 

More from TAlha MAlik

Data file handling
Data file handlingData file handling
Data file handling
TAlha MAlik
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
TAlha MAlik
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
TAlha MAlik
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
TAlha MAlik
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
TAlha MAlik
 
Cs1123 1 intro
Cs1123 1 introCs1123 1 intro
Cs1123 1 intro
TAlha MAlik
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
TAlha MAlik
 

More from TAlha MAlik (12)

Data file handling
Data file handlingData file handling
Data file handling
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Cs1123 7 arrays
Cs1123 7 arraysCs1123 7 arrays
Cs1123 7 arrays
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
 
Cs1123 1 intro
Cs1123 1 introCs1123 1 intro
Cs1123 1 intro
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

Cs1123 4 variables_constants

  • 1. Variables, Constants, and Operators (Computer Programming) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad Fall Semester 2013
  • 2. Scope • The scope of a variable: the part of the program in which the variable can be accessed • A variable cannot be used before it is defined • Example:…
  • 3. Scope • Different levels of scope: 1. Function scope 2. block scope 3. File scope 4. Class scope Local variables Global variables
  • 4. Scope • Function scope example… • Block scope example… • File scope example…
  • 5. Visibility  A variable is visible within its scope, and invisible or hidden outside it.
  • 6. Lifetime of Variables • The lifetime of a variable is the interval of time in which storage is bound to the variable. • The action that acquires storage for a variable is called allocation.
  • 7. Lifetime of Variables •Local Variables (function and block scope) have lifetime of the function or block •Global variable (having file level scope) has lifetime until the end of program •Examples…
  • 8. Literals Constants • Built-in types – Boolean type • bool – Character types • char – Integer types • int –and short and long – Floating-point types • double –and float • Standard-library types – string Literals • Boolean: true, false • Character literals – 'a', 'x', '4', 'n', '$' • Integer literals – 0, 1, 123, -6, • Floating point literals – 1.2, 13.345, 0.3, -0.54, • String literals – "asdf”, “Helllo”, Pakistan”
  • 9. • Named constants are declared and referenced by identifiers: const int max_marks = 100; // (MAX_MARKS rec..) const string UNIVERSITY = “ALI"; const double PI = 3.141592654; const char TAB = 't'; • Constants must be initialized in their declaration • No further assignment possible within program Constants (named)
  • 10. • Implementation Limits #include <climits> //Implementation constants defined here INT_MIN INT_MAX LONG_MIN LONG_MAX #include <cfloat> //location of float constants FLT_MIN FLT_MAX DBL_MIN DBL_MAX Lower and upper bounds for Integer types. C++ Standard Constants Lower and upper bounds for Decimal types.
  • 11. Binary Arithmetic Operators Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 Remainder operator is also known as modulus operator
  • 12. Integer and Real Division float result = 5 / 2; //  result equal to 2 float result = 5.0 / 2; //  result equal to 2.5  If any of the operand is a real value (float or double) the division will be performed as “Real Division”
  • 13. Remainder/Modulus operator • Operands of modulus operator must be integers  34 % 5 (valid, result  4)  -34 % 5 (valid, result  -4)  34 % -5 (valid, result  4)  -34 % -5 (valid, result  -4) • 34 % 1.2 is an Error
  • 14. Using Remainder Operator • Class Exercise: – Write Pseudocode/flow-chart to identify Odd and Even numbers between M and N?
  • 15. Arithmetic Expressions ) 94 (9 ))(5(10 5 43 y x xx cbayx is translated to result = (3+4*x)/5 – (10*(y-5)*(a+b+c))/x + 9*(4/x + (9+x)/y) • Convert following expression into C++ code result =
  • 16. Example: Converting Temperatures - Write a program that converts a Fahrenheit to Celsius using the formula: )32)((9 5 fahrenheitcelsius
  • 18. Shorthand/Compound Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8
  • 19. Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.
  • 20. Increment and Decrement Operators • Evaluate the followings: int val = 10; int result = 10 * val++; cout<<val<<“ “<<result; int val = 10; int result = 10 * ++val; cout<<val<<“ “<<result;
  • 21. Example Program (Incr. Dec. Operators)
  • 22. Numeric Type Conversion Consider the following statements: short i = 10; long k = i * 3 + 4; double d = i * 3.1 + k / 2; cout<<d;
  • 23. Type Conversion Rules • Auto Conversion of Types in C++ 1. If one of the operands is long double, the other is converted into long double 2. Otherwise, if one of the operands is double, the other is converted into double. 3. Otherwise, if one of the operands is unsigned long, the other is converted into unsigned long. 4. Otherwise, if one of the operands is long, the other is converted into long. 5. Otherwise, if one of the operands is unsigned int, the other is converted into unsigned int. 6. Otherwise, both operands are converted into int.
  • 25. Typecasting • A mechanism by which we can change the data type of a variable (now matter how it was originally defined) • Two ways: 1. Implicit type casting (done by compiler) 2. Explicit type casting (done by programmer)
  • 26. Implicit type casting • As seen in previous examples: void main() { char c = 'a'; float f = 5.0; float d = c + f; cout<<d<<“ “<<sizeof(d)<<endl; cout<<sizeof(c+f); }
  • 28. Explicit type casting • Explicit casting performed by programmer. It is performed by using cast operator float a=5.0, b=2.1; int c = a%b; //  ERROR • Three Styles int c = (int) a % (int) b; //C-style cast int c = int(a) % int(b); // Functional notation int c = static_cast<int>(a) % static_cast<int>(b); cout<<c;
  • 29. Explicit Type Casting - Casting does not change the variable being cast. For example, d is not changed after casting in the following code: double d = 4.5; int j = (int) d; //C-type casting int i = static_cast<int>(d); // d is not changed cout<<j<<“ “<<d;
  • 30. • A "widening" cast is a cast from one type to another, where the "destination" type has a larger range or precision than the "source“ Example: int i = 4; double d = i; Widening type casting
  • 31. • A “narrowing" cast is a cast from one type to another, where the "destination" type has a smaller range or precision than the "source“ Example: double d = 787994.5; int j = (int) d; // or int i = static_cast<int>(d); Narrowing type casting
  • 32. Casting between char and Numeric Types int i = 'a'; // Same as int i = (int) 'a'; char c = 97; // Same as char c = (char)97;
  • 33. - The increment and decrement operators can also be applied on char type variables: -Example: char ch = 'a'; cout << ++ch; Using ++, -- on “char” type
  • 34. -- C style (we will study in pointers topic) -- C++ style: -#include<sstream> -void main() { -int val=0; -stringstream ss; -cout<<“Enter Value: “; cin>>val; -ss << val; //Using stream insertion op. string str_val= ss.str(); cout<<“n Output string is: “<<str_val; } int to string Conversion
  • 35. Equality and Relational Operators • Equality Operators: Operator Example Meaning == x == y x is equal to y != x != y x is not equal to y • Relational Operators: Operator Example Meaning > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y
  • 36. Logical Operators • Logical operators are useful when we want to test multiple conditions • Three types: 1. boolean AND 2. boolean OR 3. boolean NOT
  • 37. Boolean AND or logical AND • Symbol: && • All the conditions must be true for the whole expression to be true –Example: if ( (a == 10) && (b == 10) && (d == 10) ) cout<<“a, b, and d are all equel to 10”;
  • 38. Boolean OR / Logical OR • Symbol: || • ANY condition is sufficient to be true for the whole expression to be true –Example: if (a == 10 || b == 9 || d == 1) // do something
  • 39. Boolean NOT/ Logical NOT • Symbol: ! • Reverses the meaning of the condition (makes a true condition false, OR a false condition true) –Example: if ( ! (marks > 90) ) // do something
  • 40. Conditional Operator • The conditional operator is a ternary operator (three operands), is used to simplify an if/else statement. • We will study this after if statement
  • 41. 41 Bitwise Operators (integers) • Bitwise "and" operator & • Bitwise "or" operator | • Bitwise "exclusive or" operator ^ – (0 on same bits, 1 on different bits) • Bitwise "ones complement" operator ~ • Shift left << • Shift right >>
  • 42. Bitwise Operators (Example) int i = 880;  1 1 0 1 1 1 0 0 0 0 int j = 453;  0 1 1 1 0 0 0 1 0 1 i & j (320) 0 1 0 1 0 0 0 0 0 0 i | j (1013) 1 1 1 1 1 1 0 1 0 1 i ^ j (693) 1 0 1 0 1 1 0 1 0 1 ~j (-454) 1 0 0 0 1 1 1 0 1 0 i = i<<1; (1760) 1 0 1 1 1 0 0 0 0 0 i = i>>1; (440) 0 1 1 0 1 1 1 0 0 0 unsigned int
  • 43. Precedence Rules • Precedence rules are vital when we have mix of many operators in an expression: x = 3 * a - ++b%3; • Two Important Terms: 1. Precedence Rules: specify which operator is evaluated first when two operators are adjacent in an expression. 2. Associativity Rules: specify which operator is evaluated first when two operators with the same precedence are adjacent in an expression.
  • 45. Precedence Rules – Example 1 6 + 2 * 3 - 4 / 2 6 + 6 - 4 / 2 6 + 6 - 2 12 - 2 10
  • 46. Precedence Rules – Example 2 3 * 4 / 2 + 3 - 1 12 / 2 + 3 - 1 6 + 3 - 1 9 - 1 8
  • 47. Precedence Rules – Example 3 8 * 3 / 2 + 3 - 1 24 / 2 + 3 - 1 12 + 3 - 1 15 - 1 14 8 / 3 * 2 + 3 - 1 2 * 2 + 3 - 1 4 + 3 - 1 7 - 1 6
  • 48. Precedence Rules (overriding) • For example: x = 3 * a - ++b % 3; • If we intend to have the statement evaluated differently from the way specified by the precedence rules, we need to specify it using parentheses ( ) • Using parenthesis: x = 3 * ((a - ++b)%3);