Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
178 views46 pages

Introduction To Computer Programming: Instructor: Mahwish Shahid

This document provides an introduction to C++ programming and integrated development environments (IDEs). It begins with a recap of basic concepts like hardware components, data types, and programming languages. It then discusses starting C++ programs, including the main function structure and basic syntax elements like comments, variables, data types, operators, and expressions. The document explains how to compile and run C++ programs using an IDE. It also covers important C++ concepts like preprocessor directives, header files, namespaces, input/output streams, and modifying output using escape sequences.

Uploaded by

sufyan very
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)
178 views46 pages

Introduction To Computer Programming: Instructor: Mahwish Shahid

This document provides an introduction to C++ programming and integrated development environments (IDEs). It begins with a recap of basic concepts like hardware components, data types, and programming languages. It then discusses starting C++ programs, including the main function structure and basic syntax elements like comments, variables, data types, operators, and expressions. The document explains how to compile and run C++ programs using an IDE. It also covers important C++ concepts like preprocessor directives, header files, namespaces, input/output streams, and modifying output using escape sequences.

Uploaded by

sufyan very
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/ 46

Introduction to Computer

Programming
Introduction to C++ and IDE
Chapter # 02

Instructor: Mahwish Shahid


Recap of Basic Concepts
 Course Objectives
 What is Computer, Data, Information
 Elements of Computer: H/w and S/w
 Basic Hardware Components
 Data Hierarchy, Storage Unit / Byte Measurement and Binary
Numbers
 Computer Software, Programming languages and its types
 Language Translator: Compiler and Interpreter
 Debugger and IDE
 Pseudo Code, Algorithm and Flow Chart
Introduction to C++ and IDE

 Starting 'C++'
 Our First Program
 Modify First program
 Identifiers
 Key words
 Variables / Constants
 Data Types
 Operators
 Expression
 Precedence of Operators
Starting C++
 Computer Program: Set of instructions
 System Program
 Application program
 Low Level Language:
 Machine Language: Binary Language: logically Binary Digits represent current’s availability in circuit
 High Level Language:
 C++ (Intermediate level language)
 What is important / needed to learn a natural language? E.g. Subject Verb Object
 Set of Alphabets  Word  Grammar  Phrase / Sentences  Rules / Syntax  Valid Words and
 What is needed to Learn C++? sentence
List of Special characters e.g.
 Set of Characters: English Alphabets (a-z) (A-Z) Digits (0-9) # { } ( ) < > & + - * / ! || , ;
 Constants, variable, Keywords Main, Int, Long, For, While, Do, If
 Syntax / Rules  Instruction  Program
/ Statement
Intro to C++ Program
1. #include <iostream> Iostream: input output stream: built in Library include: to invoked that library : header file / pre processor Directive
2. using namespace std; Class of elements : an abstract container, holding definition of Input (cin) Output (cout) Functions,
3. int main () Function: Name, Inputs of Function (Argument), Output of Function (Return)
4. { Starting point of function Body
5. //variable declaration Function Body /
// are used for single line comments
Scope of Function
6. //read values input from user //Indentation is for the convenience of the reader;
7. //computation and print output to user Compiler ignores all spaces and new line
8. return 0; If function has an output
9. } End of function Body

 After writing a C++ program in editor, you need to compile that program to checks whether the
program follows the C++ syntax
 If there are errors, it lists those errors down
 If there are no errors, it translates the C++ program into a program in machine Code which you can execute.
 All statements ended by semicolon (;), the delimiter for the compiler is the semicolon
 Case Sensitive Void is different than void
Main is different than main
Parts of a First C++ Program
1 // sample C++ Program Comment (//) forward slashes

2 # include <iostream> Preprocessor Directive

3 using namespace std; which namespace to use

4 int main() beginning of Function named main


Having No Arguments and Int return type.
Output Statement
Keyword “cout” 5{ beginning of Body / Block of main Function
To display String constant in double quotes
something on 6 cout << "Hello, there!"; Text to display on screen
screen
7 return 0; send 0 to Processor as return value of Function

8 } end of block / body of main


Preprocessor Directives
 Provide instructions to the compiler to preprocess the information before actual
compilation starts.
 Begin with (#)
 C++ has many directories:
 E.g. #Include, #define, #if, #else
 Preprocessor directives are not C++ statements, works like macros
 So there is no semicolon (;) at the end of this statement.
 General syntax: # Preprocessor_Directive <library_name/ header_file_name>
 # Include <iostream>
 Directive to "add" contents of library file to your program
 Executes before compilation,
 It simply "copies“ library file into your program file
 Directive lines cannot seen by compiler
Header Files / Library Files
 C++ Standard libraries
 Syntax
 Start with # symbol enclosed in < >
 #include <headerFileName>
 Example : #include <iostream>
 By including header file,
 It copies into each source file that needs it.
 Inserts the contents of another file into the program
 Header files inserts the contents of another file into the
program
 C++ has many libraries
 Input/output, math, strings, etc.
Namespace
 To define scope, its an additional information to differentiate similar functions, classes, variables etc.
with the same name available in different libraries.
 Using namespace, you can define the context in which names are defined.
 Namespace is required when we use names that we’ve brought into the program by the preprocessor
directive e.g. #include <iostream>.
 General Syntax: namespace_Name:: Member_Name
 E.g. std :: cout, Std :: cin, Std :: out,

 “Using” is the keyword of directive to tell the compiler that the subsequent code is making use of
names in the specified namespace.
 This will enable to omit std:: before each use of a name (member) in the std namespace
 #include <iostream>
 using namespace std;
 C++ uses streams for input and output: Stream - is a sequence of data to be read (input stream) or a
sequence of data generated by the program to be output (output stream)
Other Features in C++ Program
 Blank Lines and White Space
 You use blank lines, space characters and tab characters (i.e., “tabs”) to make
programs easier to read.
 Together, these characters are known as white space.
 White-space characters are normally ignored by the compiler.
 The Main Function
 part of every C++ program
 Program execution always begin from main function.
 Main Function: Return type and Arguments.
 Left curly brace {, begin the body of every function.
 A corresponding right curly brace, }, must end each function’s body.
 Block
 A set of statements contained within a pair of braces
Other Features in C++ Program (cont’d)
 An Output Statement
 To print the string of characters enclosed b/w double quotation marks.
 A string is called a character string / string literal / simply string.
 White-space characters in strings are not ignored by the compiler.
 General syntax: cout<<“Text_to_Print_on_Screen. ”;
 Cout << "hello, there!";
 Every c++ statement must end with a semicolon (statement terminator).
 Output and input in c++ are accomplished with streams of characters.
 So, it sends the stream of characters to the standard output stream object which is
normally “connected” to the screen.

 The Stream Insertion Operator (<<)


 The value to the operator’s right, is inserted in the output stream.
 The Return Statement
 To exit / end a function
Modify First C++ Program 1 // sample C++ Program
 “COUT” Displays information on computer screen 2 # include <iostream>
 Console Output 3 using namespace std;
 cout << "Hello, there!"; 4 int main()
 Lets modify by using CASCADING feature: 5 {
Or cout << "Hello, ";
6 cout << "Hello, there!";
 cout << "Hello, " << "there!"; cout << "there!";
7 return 0;
 To add Blank lines in output on screen using endl or \n feature: 8 }
 cout << "Hello, there!" << endl;  cout << "Hello, there! \n";
 To display Variables in output on screen:
anything within double quotes will be output as it is.
 cout << number_of_Bars;  cout << “Total # of candy bars \n";
cout << "Welcome \n to \n C++ !\n";
 cout << numberOf_Bars << ”candy bars \n”;
cout << "Welcome \n to \n \n C++ !\n";
 To display Arithmetic expressions on screen:
 cout << ”The total cost is $” << (price + tax);
Escape Sequence
 Sequences of symbols starts with a backslash (\) make special meaning to the computer.
 Used to manipulate output by instructing compiler that a special "escape character" is coming.
 Always used within double quotes.
 Following character treated as "escape sequence char"
 cout << "The total is \t "<< sum << “\n”;
Special Characters
Character Name Meaning
// Double Forward slash Beginning of a comment
# Pound sign Beginning of preprocessor directive
<> Open/close Angle brackets Enclose filename in #include
() Open/close parentheses Used when naming a function
{} Open/close Curly bracket / Delimiters Encloses a group of statements
"" Open/close Double quotation marks Encloses string of characters
; Semicolon End of a programming statement
[] Open/close Square Brackets Size specification
<< Double open Angular bracket Cascade, Stream insertion
>> Double close Angular bracket Cascade, Stream extraction
\ Back slash Use with escape sequence in
combination with other characters.
‘‘ Single Quotation Mark To specify a character
Program Example
 Write a Program to Add two Integers.
1. #include <iostream>
2. using namespace std;
3. int main() // function main begins program execution
4. {
5. //Variable declaration
6. int number1; // first integer to add Program Output
7. int number2; // second integer to add Enter first integer:
8. int sum; // sum of number1 and number2 Enter second integer:
Sum is
9. cout << "Enter first integer: "; // prompt user for data
10. cin >> number1; // read first integer from user into number1

11. cout << "Enter second integer: "; // prompt user for data
12. cin >> number2; // read second integer from user into number2

13. sum = number1 + number2; // add the numbers; store result in sum

14. cout << "Sum is " << sum << endl; // display sum; end line
15. } // end function main
Other Features in C++ Program (cont’d)
 An Input Statement
 To Store data in the computer's memory requires two steps
 Allocate the memory by declaring a variable
 Fetch a value from the input device and place it in the allocated memory location
 Console Input: to get the values of variables from user
 When input statement is read by program
 it just pauses the execution until the user types something and presses <Enter> key
Program Output
 General syntax: cin >> Variable_to_hold_value_ of_User’s_choice; 1234
Example:
 cin >> number1;
cin >> x
 The Stream Extraction Operator (>>)
 To obtain a value from the keyboard stream.
 Using multiple stream insertion operators (<<) in a single statement is referred to
as concatenating, chaining or cascading stream insertion operations.
Other Features in C++ Program (cont’d)
 Comments
 To increase the readability of the code
 Not displayed on output screen
 Single Line Comment : using // comment
 Multi –Line Comment: using
 /* please enter your comment text here if its more than one line */
Basic Concepts C++ Program
 Identifiers
 Key words / Reserve Words
 Variable & Constants
 Data Types
 Operators
 Arithmetic
 Assignment
 Logical  Increment / Decrement
 Relational

 Expressions
 Operators Precedence
Identifier
 Identifiers
 a name used to identify a variable, function, class, module, or any other user-defined item.
 Keywords cannot be used as identifiers.
 Can starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
 C++ does not allow following punctuation characters:
 @, $, and % within identifiers. C++ is a case-sensitive programming language.
 C++ is case sensitive, Upper- and lower-case characters are distinct
 Thus, Manpower and manpower are two different identifiers in C++.

Valid Examples:
Invalid Examples:
X, x_1, _abc, A2b,
12, 3X, %change, myFirst.c, data-1
ThisIsAVeryLongIdentifier
Identifier: Programming Tips
 Identifiers should be
 Short enough to be reasonable to type (single word is norm)
 Standard abbreviations are acceptable
 Long enough to be understandable
 Careful selection of identifiers makes your program clearer
 Two styles of identifiers
 C-style - terse, use abbreviations and underscores to separate the words, never use capital letters for
variables
 Camel Case I - if multiple words: capitalize, do not use underscores
 Camel Case II variant: first letter lowercased Identifier Valid / Reason if invalid
 Pick style and use consistently invalid
Camel Case I C-style Camel Case II totalSales Yes
Min min min total_Sales Yes
Temperature temperature temperature total.Sales No Cannot contain .
CameraAngle Camera_angle cameraAngle 4thQtrSales No Cannot begin with digit
CurrentNumberPoints Cur_Num_Point currentNumberPoints
totalSale$ No Cannot contain $
Class Activity (I-a)
 Which of the following are legal variable names in C++? What’s wrong with the
illegal names?
3rdItem Item2 IsGood? _left
float TaxRate pi_r_sqrd table4.1 m

 Classify as good, legal but not recommended, or illegal:


e.g. percent - good

if tax_rate num_students 1999pay


y2k# my_data m Days_off
_1994tax variable y2k_fig2 Last.year
xr3_yz57 Tax-Rate pay99 exam1_avg
Keywords / Reserve Words
 Key words / Reserve Words
 Identifiers that are reserved to the use of the C++ language
 Example: int, break, if, else,
 return, float, double
 Cannot be used by the programmer to name things
 Consist of lowercase letters only asm do if return typedef

 Have special meaning to the compiler auto double else break typeid

 Total keywords: 48 new dynamic_cast switch case typename


class delete int sizeof union
goto reinterpret_cast long while register
default friend short for static
continue public signed unsigned true
inline protected float struct false
try private char this using
catch throw bool const_cast static_cast
const virtual void namespace enum
Variable and Constants
x 12.5 1001
 Variable 1002
temperature 32
 A memory location whose content may change during program execution 1003
grade ‘c’
 Has a name and a data type e.g. int x; Double Number; Char grade; 1004
Number -
 Must be defined before use 1005
 ALWAYS has a value stored in it. 1006
 Implemented as a memory location. 1007
 Memory locations are actually labeled with variable names 1008
 Information stored is binary -- 0s and 1s 1009
 Every variable should be declare prior to use and must have a data type.
 When a block is nested inside another block:
 Constants  a variable declared in the inner block may
 A memory location whose content cannot be changed have the same name as a variable in the outer
block.
 Also known as Literals Example: const double PI = 3.14159;
 The variable in the inner block takes
 Scope of Variable: limited to the block in which it is declared. precedence over the variable in the outer
block.
 Local Variable
NOTE: Avoid this situation as much as possible
 Global Variable
Declaration / Initialization
 Declaration
 Declaration specifies that a variable will hold what type of values
 General Syntax: Example:
Data_type identifier_name; double x;
 Variables with same data types can be declared using Comma separated list Example: int number1, number2, sum;
 Can be placed anywhere in the program, (practice to declare at the beginning of program)
 Use meaningful variable names. i.e. easier to read and debug
 variable contains arbitrary value after it is declared.

 Initialization
 Assignment of an initial value for a variable using (=) assignment operator
 General Syntax: Syntax: Example: int y = 45
Data_type identifier_name = value; CONST data_type identifier = value; Double x;
 Uninitialized variable will contain garbage value x = 4;
 Few compilers will catch this error, but most will issue a warning.
Example: CONST double PI = 3.14159;
 If not corrected, it will cause a logic error.
 To avoid logical error try to Initialize all variables when they are declared
 Note: initialization of the variable is optional with declaration of variable.
 Note initialization of the constant is required at the time of declaration.
Data Types
 Data Types: what type of data store in memory
 A set of values + a set of operations.
 Based on the data type of a variable, the operating system allocates memory and decides what can
be stored in the reserved memory.
 The set of values for each type is known as the domain of data type
 Specify the space required in memory by declaring a variable
Standard Data Type Keyword
 Primitive Built-in Types Boolean bool
 offers the programmer built-in as well as user defined data types
Character char
 Provided as an integral part of C++
Integer int
 Requires no external code
Floating point float
 Consists of basic numerical types
 Majority of operations are symbols (e.g. +,-,*,…) Double floating point double
Valueless void
 Class data type
Wide character wchar_t
 Programmer-created data type
 Set of acceptable values and operations defined by a programmer using C++ code
Data Type Modification
 Several of the basic types can be modified using following type modifiers:
 Signed, Unsigned
 Short, Long
 Different compilers have different internal limits on the largest and smallest values that can be stored in
each data type.

 Void: Represents the absence of type. It has no values and no operations. (Empty)
 Int: Natural size of integer
 Float: A single-precision floating point value
 Double: A double-precision floating point value
 Char: To hold ASCII character. It is of one byte.
 Bool: Stores either value true or false
Integer Data Types
 A number without a fractional part, i.E. Int, short int and long int.
 Most common allocation for int is four bytes. Set of values are whole numbers:
integers
 Explicit signs allowed
 Commas, decimal points, and special signs not allowed a= 10
 Overwrite Value 1.int main() b=20
2.{ a= 10
3. Int a=10, b=20; b=10
4. cout << "a = " << a << " \n b= " << b<< endl;
5. b=a;
Type Sign Byte Number of bits
6. cout << "a = " << a << " \n b= " << b<< endl;
size
7.return 0;
8. } Short int Signed 2 16
 Examples of int: unsigned
 Valid: 0 5 -10 +25 1000 253 -26351 +36 Int Signed 4 32
Unsigned
 Invalid: $255.62 2,523 3. 6,243,982 1,492.89
Long int Signed 4 32
Unsigned
Floating Point Data Types
 Number with a fractional part, such as 43.32.
 The C++ language supports three different sizes of floating-point: Type Byte Number of
size bits
1. Float
Float 4 32
2. Double Double 8 64
3. Long double Long double 10 80
 sizeof (float) <= sizeof (double) <= sizeof (long double)
1.int main()
 Round off / Truncate a= 10
2.{
3. Int a=10, b=20.5
4. float b=20.5; a= 20
5. cout << "a = " << a << " \n b= " << b<< endl; b=20.5
6. a=b;
7. cout << "a = " << a << " \n b= " << b<< endl;
8.return 0;
9. }
 Although the physical size of floating-point types is machine dependent, many
computers support the sizes shown below.
Character Data Types
 A variable or a constant of char type can hold an ASCII character.
 Single character value: letter, digit, or special character enclosed in
single quotes
 Examples: ‘A’ ‘$’ ‘b’ ‘7’ ‘y’ ‘!’ ‘M’ ‘q’
 Examples:
 const char star = '*';
 char letter, one = '1';
 Used to store single characters
 Each character contained in two bytes
 Letters of the alphabet (upper- and lowercase)
 Digits 0 through 9
 Special symbols such as + $ . , - !
Bool Data Types
 Represents Boolean (logical) data
 Restricted to true or false values
 Often used when a program must examine a specific condition
 If condition is true, the program takes one action;
 if false, it takes another action.
 Boolean data type uses an integer storage code
String Data Type
 A Programmer-defined type #include <iostream>
using namespace std;
 Requires #include <string> int main()
{
 A string is a sequence of characters int x=10;
 Enclosed in double quotes float y = 20.5;
char z = 'z', a= 65;
 "Hi Mom" cout << " Integer= " << x<<endl;
 "We're Number 1!" cout << "\n Size of Int=" << sizeof(int)<<endl;
cout << "\n Float= " << y << endl;
 "75607" cout << "\n Size of Float=" << sizeof(float)<<endl;
cout << " \n Char in z= " << z << endl;
cout << "\n Size of Char=" << sizeof(char)<<endl;
cout << " \n Char in a= " << a << endl;
cout << "\n Size of Short Int=" << sizeof(short int)<< endl;
cout << "\n Size of Long Int=" << sizeof(long int) << endl;
cout << "\n Size of Double=" << sizeof(double)<<endl;
cout << "\n Size of Boolean=" << sizeof(bool) << endl;
system("pause");
return 0;
} // end function main
How much memory type takes to store the value in
memory?
Type Bit Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int Range 0 to 65,535

signed short int Range -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character


Operators
 Operators
 To perform various operations
 A symbol that tells the compiler to perform specific mathematical or logical manipulations
 Associativity of Operator: the direction in which an Operator evaluates
 Left Associated
 Right Associated
 Arity of Operators: # of Operands on which an Operator operates
 Unary
 Binary Home Work:
 Ternary  PreFix
 Types of Operator (Based on Operations)  PostFix
 Following are built –in types of C++ Operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Other Operators
Arithmetic Operators Program Output
 To perform arithmetic/mathematical operations on operands (DMAS Rule) The sum of 6 and 15 is 21
 Precedence same as in algebraic usage
 Display result of a numerical expression
 parentheses use to change the precedence
 Example:
 If Same Level of precedence:
 Cout << “The sum of 6 and 15 is ” << (6 + 15);
 Left to right
Operation Operator Operands Description
Addition + Op1+ Op2 Adds two operands
Subtraction - Op1 - Op2 Subtracts second operand from the first
Multiplication * Op1 * Op2 Multiplies both operands
Division / Dividend / divisor Divides numerator by de-numerator – return
Quotient
Modulus Division % Dividend % divisor Divides numerator by de-numerator – return
Remainder
Increment ++ Op1 ++ Increases integer value by one
Decrement -- Op1 -- Decreases integer value by one
Relational Operators
 To compare the values of two operands  Display result of a Relational expression
 Parentheses use to change the precedence  Example: Program Output
 bool res = 6 < 15; 6 <15 is 1
 If Same Level of precedence:
 cout << "6 < 15 is " << res;
 Left to right

Operation Operator Operands Description


Equal == (Op1 == Op2) True if the values of two operands are equal.
Not Equal != (Op1 != Op2) True if the values of two operands are not equal.
Greater than > (Op1 > Op2) True if the value of left operand is greater than the value of right operand.
Less than < (Op1 < Op2) True if the value of left operand is less than the value of right operand.
Greater than >= (Op1 >= Op2) True if the value of left operand is greater than or equal to the value of right
Equal operand.
Less than <= (Op1 <= Op2) True if the value of left operand is less than or equal to the value of right operand.
Equal
Logical Operators
 To combine two or more conditions/constraints or to complement the
evaluation of the original condition 1. int age;
2. cout << "Enter your age: ";
 Result of logical operator is a Boolean value (true / false) 3. cin >> age;
4. if(age >= 35 && age <= 80)
 Has Truth tables Op1 Op2 && ||
5. {
 Example: F F F F 6. cout << "You're between 35 and 80 and can save
F T F T money on your car insurance!" << endl;
Op ! 7. }
T F F T 8. else
F T 9. {
T T T T
T F 10. cout << "Sorry, we don't have any deals for you
today!" << endl;
11. }
12. return 0;

Operation Operator Operands Description


AND && (Op1 && Op2) If both the operands are True, then condition becomes true.
OR || (Op1 || Op2) If any of the two operands is True, then condition becomes true.
NOT ! Op1 ! If a condition is true, then NOT operator will make false.
Bit Wise Operators
 To perform bit-level operations on the operands.
 The operators are first converted to bit-level and then calculation is performed
on the operands.
 The mathematical operations such as addition etc. can be performed at bit-level
for faster processing p q p&q p|q p^q
 Example: 0 0 0 0 0
 Booleans: 0 1 0 1 1
 0 = false = no 1 1 1 1 0
 1 = true = yes 1 0 0 1 1
Operation Operator Operands Description
AND & Op1 & Op2 copies a bit to the result if it exists in both operands.
OR | Op1 | Op2 copies a bit if it exists in either operand.
XOR ^ Op1 ^ Op2 copies the bit if it is set in one operand but not both.
Complement ~ ~ Op1 unary and has the effect of 'flipping' bits
Assignment Operator
 To set the value of the variable on the left hand side of the equation to what is
written on the right hand side
 It looks like a math equation, but it is not an equation.
 Example:
 numberOfBars = 37;
 totalWeight = oneWeight;
 totalWeight = oneWeight * numberOfBars;
 numberOfBars = numberOfBars + 3;

Operation Operator Operands Description


Assignment = Op2 = (Expression / Op1) Assigns values from right side operands to left side operand.
Operator
Other Operators
 some other operators available in C++ used to perform some specific

Operation Operator Operands Description


Size of Sizeof() sizeof(a) Sizeof operator returns the size of a variable.

Conditional ? Condition ? X : Y If condition is true then it returns value of X otherwise returns value of Y.

Comma , Causes a sequence of operations to be performed.

Pointer * * Op1 Pointer to a variable.

Address of & & Op1 Returns the address of a variable.


Operator Precedence
Category Operator Associativity
 Determines the grouping of terms in Postfix () [] -> . ++ -- Left to right
an expression, when two or more Unary/Prefix ! ~ ++ -- (type) * & sizeof Right to left
operators appear. Multiplicative * / % Left to right

 This affects how an expression is Additive + - Left to right

evaluated. Shift << >> Left to right

Relational < <= > >= Left to right


 For example
Equality == != Left to right
 x = 7 + 3 * 2; Bitwise AND & Left to right
 First gets multiplied with 3*2 Bitwise XOR ^ Left to right
 Then adds into 7. Bitwise OR | Left to right

 x = (7 + 3) * 2; Logical AND && Left to right

Logical OR || Left to right


 x = 7 + 3 * 8 / 2;
Conditional ?: Right to left

Assignment = Right to left

Comma , Left to right


Operator Precedence Rules
 Rules for expressions with multiple operators
 Two binary operators cannot be placed side by side
 Parentheses may be used to form groupings
 Expressions within parentheses are evaluated first
 Sets of parentheses may be enclosed by other parentheses
 Parentheses cannot be used to indicate multiplication,
multiplication operator (*) must be used.

 Operator Overriding makes it possible to change the predefine behavior of the


operators.
 Parenthesis are used to override the default precedence of operators.
Expression
 Expressions
 Sequence of operators and their operands, that can be use for following reasons:
 Computing a value from the operands.
 Designating objects or functions.
 Generating "side effects."
 Side effects are any actions other than the evaluation of the expression - for example, modifying the
value of an object
 Mixed-mode expression
 Arithmetic expression containing integer and non-integer operands
 Rule for evaluating arithmetic expressions
 Both operands are integers: result is integer
 One operand is floating-point: result is floating-point
Increment / Decrement Operator
 Increment
 Increase the value of Operand by one, also called Postfix Increment
 Right associated Unary operator
 Denoted by ++ e.g. x++ i.e. x = x+1;
Syntax:
Destination = Source++
 Where x  Variable_name Destination = Source--
 ++  increment operator
 Decrement
 Decrease the value of Operand by one , also called Postfix decrement
 Right associated operator
Prefix Increment / Decrement
 Denoted by -- e.g. x i.e. x = x-1;
When operator precedes its operand
 Where x  Variable_name Destination = ++ Source
 --  increment operator Destination = --Source
Prefix / Postfix 1. int main()
2. {
1. # include <iostream>
1.int main() 1. int main() 3. Int x=10;
2. using namespace std;
2.{ 2. { 4. cout << " Prefix Increment / Decrement \n";
3. int main()
3. Int x=10; 3. Int x=10; 5. cout << " ------------------------------- \n";
4. {
4. cout << x << " = x \n"; 4. cout << x<<“ = x \n”; 6. cout << x << " = x \n \n";
5. Int x=10;
5. cout << x++ << " : x++ \n"; 5. ++x; 7. cout << ++x << " : ++x \n \n";
6. cout << x<<“ = x \n”;
6. //print 10 then post-increment 6. cout << x<<“ : ++x \n”; 8. // pre-increment then print 11
7. x++;
7. cout << x-- << " : x-- \n"; 7. --x; 9. cout << --x << " : --x \n \n";
8. cout << x<<“ : x++ \n”;
8. cout << x << " = x \n"; 8. cout << x<<“ : --x \n”; 10. cout << x << " = x \n \n"; return 0;
9. x--;
9.return 0; 9. return 0; 11. }
10. cout << x<<“ : x-- \n”;
10. } 10. } Prefix Increment / Decrement
11. return 0;
-------------------------------------
12. } 10 = x
10 = x 10 = x
10 : x++
Program Output 11 : x++
11 : x—
10 : x-- 11 : x++
10 = x 10 = x
11 : x++
10 : x—
10 : x--
10 = x
Assignment 1 (Submission)
+
QUIZ - I
(Next Class)
THANK YOU !

You might also like