0% found this document useful (0 votes)
35 views75 pages

Chapter 2 Computer Programming Fresh Man

Computer programming Chapter 2 ppt

Uploaded by

Reshid Jewar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
35 views75 pages

Chapter 2 Computer Programming Fresh Man

Computer programming Chapter 2 ppt

Uploaded by

Reshid Jewar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 75

Department of Computer Science

Computer programming
Chapter Two

C++ Basics
Structure of C++ Program
A C++ program has the following structure
Comments:- single line and multiple line comment
Preprocessor directives:- All the preprocessor directives in C++ start
with the # (hash) symbol
Global variable declarations:-A global variable can be accessed from
anywhere in the entire program. It is usually declared at the top or
start of the program outside of all blocks and functions of the
program.
Prototypes of functions:-A function prototype begins with the
keyword function, then lists the function name, its parameters (if
any), and return value (if any).
Definitions of functions:-A function is a block of code which only runs
when it is called.
C++ Integrated Development
Environment(IDE)
 An Integrated Development Environment (IDE) is a software suite that
combines tools needed for software development, such as a code editor,
debugger, and build automation tools, into one user-friendly interface.
 It often includes features like code completion and version control
integration.
 The complete development cycle in C++ is: Write the program, compile the
source code, link the program, and run it.
•Writing: Using a text editor to create C++ source files (.cpp).
•Compiling: Using a C++ compiler to translate source code into object files.
•Linking: Combining object files into an executable program.
•Running: Executing the program to see its output or behavior.
Cont.…
Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you
may be using a commercial text editor or word processor that can produce text
files.
The important thing is that whatever you write your program in, it must save
simple, plain-text files, with no word processing commands embedded in the text.
Simple editors like Notepad (on Windows) or TextEdit (on macOS).
Specialized editors like Visual Studio Code, Code::Blocks, Dev C++,
NetBeans, Quincy, Sublime Text, or Atom.
The files you create with your editor are called source files, and for C++ they
typically are named with the extension .CPP.
For example, you might create a file named hello.cpp.
Cont.…
Compiling
Your source code file can't be executed, or run, as a program can.
 To turn your source code into a program, you use a compiler.
 How you invoke your compiler, and how you tell it where to find your
source code, will vary from compiler to compiler.
 In Borland's Turbo C++ you pick the RUN menu command or type tc
<filename>
from the command line, where <filename> is the name of your source
code file (for example, test.cpp).
 Other compilers may do things slightly differently.
After your source code is compiled, an object file is produced.
This file is often named with the extension .OBJ.
This is still not an executable program, however,to turn this into an
executable program, you must run your linker.
Cont.…
• Linking
• C++ programs are typically created by linking together one or more
OBJ files with one or more libraries.
• A library is a collection of linkable files that were supplied with your
compiler, that you purchased separately, or that you created and
compiled.
• All C++ compilers come with a library of useful functions (or
procedures) and classes that you can include in your program.
• A function is a block of code that performs a service, such as adding
two numbers or printing to the screen.
• A class is a collection of data and related functions.
Cont.…
Summary
The steps to create an executable file are
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an executable program.

Showing Sample program


Any meaningful program written in C++ has to contain a number of
components:
the main function;
some variable declarations; and
some executable statements.
Cont.…
For example, the following is a very basic C++ program:
#include <iostream.h>
int main()
{
cout << "Hello World!\n";
return 0;
}
 The first character is the (#) pound symbol, which is a signal to the
preprocessor.
 Each time you start your compiler, the preprocessor is run.
 include is a preprocessor instruction that says, "What follows is a
filename. Find that file and read it in right here.“
 Every C++ program has a main() function.
 cout is used in C++ to print strings and values to the screen.
Cont.…
• The preprocessor reads through your source code, looking for lines that
begin with the pound symbol (#), and acts on those lines before the
compiler runs.
• The angle brackets around the filename tell the preprocessor to look in all
the usual places for this file.
• If your compiler is set up correctly, the angle brackets will cause the
preprocessor to look for the file iostream.h in the directory that holds all the
H files for your compiler.
• The file iostream.h (Input-Output-Stream) is used by cout, which assists
with writing to the screen.
• The effect of line 1 is to include the file iostream.h into this program as if
you had typed it in yourself.
Cont.…
• The preprocessor runs before your compiler each time the compiler is invoked.
• The preprocessor translates any line that begins with a pound symbol (#) into a special
command, getting your code file ready for the compiler.
• Line 2 begins the actual program with a function named main().
• In general, a function is a block of code that performs one or more actions.
• Usually functions are invoked or called by other functions, but main() is special.
• When your program starts, main() is called automatically.
• main(), like all functions, must state what kind of value it will return.
• The return value type for main() in HELLO.CPP is int, which means that this function will
return an integer value.
Cont.…
• All functions begin with an opening brace ({) and end with a
closing brace (}).
• The braces for the main() function are on lines 3 and 6.
• Everything between the opening and closing braces is
considered a part of the function.
• The meat and potatoes of this program is on line 4.
• The object cout is used to print a message to the screen.
• A string is just a set of characters.
Cont.…
• Here's how cout is used: type the word cout, followed by the output
redirection operator (<<).
• Whatever follows the output redirection operator is written to the screen.
• If you want a string of characters written, be sure to enclose them in
double quotes ("), as shown on line 4.
• A text string is a series of printable characters.
• The final two characters, \n, tell cout to put a new line after the words
Hello World! All ANSI-compliant programs declare main() to return an int.
• This value is "returned" to the operating system when your program
completes.
• Some programmers signal an error by returning the value 1.
• The main() function ends on line 6 with the closing brace.
Basic Elements
Keywords (reserved words)
• Reserved/Key words have a unique meaning within a C++ program.
• These symbols, the reserved words, must not be used for any other
purposes.
• All reserved words are in lower-case letters.
• The following are some of the reserved words of C++.
asm auto bool break case catch
const_cast class const char continue default
dynamic_cast do double delete else enum
explicit extern false float for friend
goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this

throw true try typedef typeid typename


union unsigned using virtual void volatile
wchar_t
Cont.…
 Notice that main is not a reserved word.

 However, this is a fairly technical distinction, and for practical purposes you are advised
to treat main, cin, and cout as if they were reserved as well.

Syntax of an identifier

Identifiers
 An identifier is name associated with a function or data object and used to refer to that
function or data object. Letter
 An identifier must: Letter
 Start with a letter or underscore - Digit
 Consist only of letters, the digits 0-9, or the underscore symbol _ -

 Not be a reserved word


Cont.…
• For the purposes of C++ identifiers, the underscore symbol, _, is
considered to be a letter.
• Its use as the first character in an identifier is not recommended
though, because many library functions in C++ use such identifiers.
• Similarly, the use of two consecutive underscore symbols, _ _, is
forbidden.
• The following are valid identifiers • The following are invalid:
Length days_in_ye DataSet1 Profit95 days-in- 1data int first.val
ar year
Int _Pressure first_one first_1 throw my__best No## bestWish!

 Although using _Pressure is not recommended.


Cont.…
• Although it may be easier to type a program consisting of single
character identifiers, modifying or correcting the program becomes
more and more difficult.
• The minor typing effort of using meaningful identifiers will repay itself
many fold in the avoidance of simple programming errors when the
program is modified.
• At this stage it is worth noting that C++ is case-sensitive.
• That is lower-case letters are treated as distinct from upper-case
letters.
• Thus the word NUM different from the word num or the word Num.
• Identifiers can be used to identify variable or constants or functions.
• Function identifier is an identifier that is used to name a function.
Cont.…
• Literals are constant values which can be a number, a character of a
string.
• For example the number 129.005, the character ‘A’ and the string
“hello world” are all literals.
• There is no identifier that identifies them.
• A comment is a piece of descriptive text which explains some aspect
of a program.
• Program comments are totally ignored by the compiler and are only
intended for human readers.
• C++ provides two types of comment delimiters:
• Anything after // (until the end of the line on which it appears) is
considered a comment.
• Anything enclosed by the pair /* and */ is considered a comment.
Data Types, Variables, and
Constants
• A variable is a symbolic name for a memory location in which data can
be stored and subsequently recalled.
• Variables are used for holding data values so that they can be utilized
in various computations in a program.
• All variables have two important attributes:
• A type, which is, established when the variable is defined (e.g., integer,
float, character).
• Once defined, the type of a C++ variable cannot be changed.
• A value, which can be changed by assigning a new value to the
variable.
• The kind of values a variable can assume depends on its type.
• For example, an integer variable can only take integer values (e.g., 2,
100, -12) not real numbers like 0.123.
Cont.…
Variable Declaration
• Declaring a variable means defining (creating) a variable.
• You create or define a variable by stating its type, followed by one or more
spaces, followed by the variable name and a semicolon.
• The variable name can be virtually any combination of letters, but cannot contain
spaces and the first character must be a letter or an underscore.
• Variable names cannot also be the same as keywords used by C++.
• Legal variable names include x, J23qrsnf, and myAge.
• Good variable names tell you what the variables are for; using good names
makes it easier to understand the flow of your program.
• The following statement defines an integer variable called myAge:
 int myAge;
• IMPORTANT- Variables must be declared before used!
Cont.…
• As a general programming practice, avoid such horrific names
as J23qrsnf, and restrict single-letter variable names (such as x
or i) to variables that are used only very briefly.
• Try to use expressive names such as myAge or howMany.
• A point worth mentioning again here is that C++ is case-
sensitive.
• In other words, uppercase and lowercase letters are
considered to be different.
• A variable named age is different from Age, which is different
from AGE.
Cont.…
• Creating More Than One Variable at a Time
• You can create more than one variable of the same type in one
statement by writing the type and then the variable names,
separated by commas. For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
• As you can see, myAge and myWeight are each declared as
integer variables.
• The second line declares three individual long variables named
area, width, and length.
• However keep in mind that you cannot mix types in one
definition statement.
Cont.…
Assigning Values to Your Variables
 You assign a value to a variable by using the assignment operator (=).
 Thus, you would assign 5 to Width by writing
 int Width;
 Width = 5;
 You can combine these steps and initialize Width when you define it by
writing
 int Width = 5;
 Initialization looks very much like assignment, and with integer variables,
the difference is minor.
 The essential difference is that initialization takes place at the moment
you create the variable.
Cont.…
• Just as you can define more than one variable at a time, you
can initialize more than one variable at creation. For example:
• // create two int variables and initialize them
 int width = 5, length = 7;
• This example initializes the integer variable width to the value 5
and the length variable to the value 7.
• It is possible to even mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
• This example creates three type int variables, and it initializes
the first and third.
Cont.…
What is Cin and Cout in C++?
cin and cout are standard input and output streams in C++.
cin: Read input from the user.
cout: Write output to the screen.
in C++ we use 'cin' and 'cout'. 'Cin' takes the input and helps the computer
understand what you want to tell it.
'Cout' helps the computer tell you something by generating the output.
syntax
int x;
cout <<"Hey there, its me";
Cout<<“enter the value of the x”;
cin >>x;
Cont.…
#include <iostream.h>
int main() {
int first_number, second_number, sum;
cout << "Enter two integers: ";
cin >> first_number >> second_number; // sum of two
numbers in stored in variable sumOfTwoNumbers
sum = first_number + second_number; // prints sum
cout << first_number << " + " << second_number << "
= " << sum;
return 0;
}
Cont.…
#include
}
<iostream.h>;
int main()
{
int age;
string name;
cout << "What is your name? ";
cin >> name;
cout << "What is your age? ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << "
years young." << endl;
return 0;
}
Basic Data Types
• When you define a variable in C++, you must tell the compiler
what kind of variable it is: an integer, a character, and so
forth.
• This information tells the compiler how much room to set aside
and what kind of value you want to store in your variable.
• Several data types are built into C++.
• The varieties of data types allow programmers to select the type
appropriate to the needs of the applications being developed.
• The data types supported by C++ can be classified as basic
(fundamental) data types, user defined data types, derived
data types and empty data types.
Cont.…
• Basic (fundamental) data types in C++ can be conveniently
divided into numeric and character types.
• Numeric variables can further be divided into integer
variables and floating-point variables.
• Integer variables will hold only integers whereas floating
number variables can accommodate real numbers.
• Both the numeric data types offer modifiers that are used to
vary the nature of the data to be stored.
• The modifiers used can be short, long, signed and unsigned.
Cont.…
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to
2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
char 1 byte 256 character values
float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
 This table shows the variable type, how much room it takes in memory,
and what kinds of values can be stored in these variables.
 The values that can be stored are determined by the size of the variable
types.
Cont.…
Signed and Unsigned
• Integers (short and long) without the word "unsigned" are assumed to
be signed.
• signed integers are either negative or positive.
• Unsigned integers are always positive.
• Because you have the same number of bytes for both signed and
unsigned integers, the largest number you can store in an unsigned
integer is twice as big as the largest positive number you can store in
a signed integer.
• An unsigned short integer can handle numbers from 0 to 65,535.
• Half the numbers represented by a signed short are negative, thus a
signed short can only represent numbers from -32,768 to 32,767.
Cont.… Line 1 includes the required include
Example: A demonstration of the use of variables. statement for the iostream's library
#include <iostream.h> so that cout will work.
int main() Line 2 begins the program.
{ On line 4, Width is defined as an
unsigned short integer, and its value
unsigned short int Width = 5, Length;
is initialized to 5.
Length = 10; Another unsigned short integer,
// create an unsigned short and initialize Length, is also defined, but it is not
with result initialized.
// of multiplying Width by Length On line 5, the value 10 is assigned to
unsigned short int Area = Width * Length; Length.
cout << "Width:" << Width << "\n"; On line 8, an unsigned short integer,
cout << "Length: " << Length << endl; Area, is defined, and it is initialized
cout << "Area: " << Area << endl; with the value obtained by
multiplying Width times Length. On
return 0;
lines 9-11, the values of the variables
} are printed to the screen.
Output: Width:5 Note that the special word endl
Length: 10 creates a new line.
Area: 50
Cont.…
• Wrapping around integer values Example: A demonstration of putting too
• The fact that unsigned long integers have large a value in a variable
a limit to the values they can hold is only #include <iostream.h>
int main() {
rarely a problem, but what happens if you unsigned short int smallNumber;
do run out of room? smallNumber = 65535;
• When an unsigned integer reaches its cout << "small number:" << smallNumber
<< endl;
maximum value, it wraps around and smallNumber++;
starts over, much as a car odometer cout << "small number:" << smallNumber
might. << endl;
smallNumber++;
• The following example shows what cout << "small number:" << smallNumber
happens if you try to put too large a value << endl;
into a short integer. return 0;
}
Output:
small number:65535
small number:0
small number:1
Cont.…
• A signed integer is different from an unsigned Example: A demonstration of adding too
large a number to a signed integer.
integer, in that half of the values you can
#include <iostream.h>
represent are negative.
int main() {
• Instead of picturing a traditional car odometer, short int smallNumber;
you might picture one that rotates up for positive smallNumber = 32767;
numbers and down for negative numbers. cout << "small number:" << smallNumber
• One mile from 0 is either 1 or -1. When you run << endl;
out of positive numbers, you run right into the smallNumber++;
largest negative numbers and then count back cout << "small number:" << smallNumber
down to 0. << endl;
smallNumber++;
• The whole idea here is putting a number that is cout << "small number:" << smallNumber
above the range of the variable can create << endl;
unpredictable problem. return 0;
IMPORTANT – To any variable, do not assign a value that }
is beyond its range! Output: small number:32767
small number:-32768
small number:-32767
Cont.…
Characters
• Character variables (type char) are typically 1 byte, enough to hold 256
values.
• A char can be interpreted as a small number (0-255) or as a member of the
ASCII set.
• ASCII stands for the American Standard Code for Information Interchange.
• The ASCII character set and its ISO (International Standards Organization)
equivalent are a way to encode all the letters, numerals, and punctuation
marks.
• In the ASCII code, the lowercase letter "a" is assigned the value 97.
• All the lower- and uppercase letters, all the numerals, and all the
punctuation marks are assigned values between 1 and 128.
• Another 128 marks and symbols are reserved for use by the computer
maker, although the IBM extended character set has become something of a
standard.
Cont.…
Characters and Numbers
• When you put a character, for example, `a', into a char variable, what is really
there is just a number between 0 and 255.
• The compiler knows, however, how to translate back and forth between
characters (represented by a single quotation mark and then a letter, numeral, or
punctuation mark, followed by a closing single quotation mark) and one of the
ASCII values.
• The value/letter relationship is arbitrary; there is no particular reason that the
lowercase "a" is assigned the value 97.
• As long as everyone (your keyboard, compiler, and screen) agrees, there is no
problem.
• It is important to realize, however, that there is a big difference between the
value 5 and the character `5'.
• The latter is actually valued at 53, much as the letter `a' is valued at 97.
Cont.…
Operators
• C++ provides operators for composing arithmetic, relational, logical, bitwise, and
conditional expressions.
• It also provides operators which produce useful side-effects, such as assignment,
increment, and decrement.
Assignment Operators
• The assignment operator is used for storing a value at some memory location
(typically denoted by a variable).
• Its left operand should be an lvalue, and its right operand may be an arbitrary
expression.
• The latter is evaluated and the outcome is stored in the location denoted by the
lvalue.
• An lvalue (standing for left value) is anything that denotes a memory location in which
a value may be stored.
Cont.…
• The only kind of lvalue we have seen so far is a variable.
• Other kinds of lvalues (based on pointers and references) will be
described later.
• The assignment operator has a number of variants, obtained by
combining it with the arithmetic and bitwise operators.
Operator Example Equivalent To

= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
&= n &= 0xF2F2 n = n & 0xF2F2
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
Cont.…
• An assignment operation is itself an expression whose value is the value
stored in its left operand.
• An assignment operation can therefore be used as the right operand of
another assignment operation.
• Any number of assignments can be concatenated in this fashion to form
one expression. For example:
 int m, n, p;
 m = n = p = 100; // means: n = (m = (p = 100));
 m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
• This is equally applicable to other forms of assignment. For example:
 m = 100;
 m += n = p = 10; // means: m = m + (n = p = 10);
Cont.…
Arithmetic Operators
• C++ provides five basic arithmetic operators.
• Except for remainder (%) all other arithmetic operators can accept a mix of integer and
real operands.
• Generally, if both operands are integers then the result will be an integer.
• However, if one or both of the operands are reals then the result will be a real (or double
to be exact).
• When both operands of the division operator (/)
are integers then the division is performed as an
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9 integer division and not the normal division we
- Subtraction 3.98 - 4 // gives -0.02 are used to.
Multiplicatio
* n 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5 • Integer division always results in an integer
13 % 3 //gives 1
% Remainder // gives 1 outcome (i.e., the result is always rounded down).
Arithmetic operators.
For example: 9/2 // gives 4, not 4.5!

-9 / 2 // gives -5, not -4!


Cont.…
• Unintended integer divisions are a common source of programming
errors.
• To obtain a real division when both operands are integers, you should
cast one of the operands to be real:
int cost = 100;
int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25
• The remainder operator (%) expects integers for both of its operands.
• It returns the remainder of integer-dividing the operands.
• For example 13%3 is calculated by integer dividing 13 by 3 to give an
outcome of 4 and a remainder of 1; the result is therefore 1.
Cont.…
• It is possible for the outcome of an arithmetic operation to be too large for
storing in a designated variable. This situation is called an overflow.
• The outcome of an overflow is machine-dependent and therefore undefined. For
example:
• unsigned char k = 10 * 92; // overflow: 920 > 255
• It is illegal to divide a number by zero.
• This results in a run-time division-by-zero failure, which typically causes the
program to terminate.
• There are also a number of predefined library functions, which perform
arithmetic operations.
• As with input & output statements, if you want to use these you must put a
#include statement at the start of your program.
• Some of the more common library functions are summarised below.
Cont.…
Parameter Result
Header File Function Type(s) Type Result
<stdlib.h> abs(i) int int Absolute value of i
<math.h> cos(x) float float Cosine of x (x is in radians)
<math.h> fabs(x) float float Absolute value of x
<math.h> pow(x, y) float float x raised to the power of y
<math.h> sin(x) float float Sine of x (x is in radians)
<math.h> sqrt(x) float float Square root of x
<math.h> tan(x) float float Tangent of x

Relational Operators Operator Name Example


• C++ provides six relational operators == Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
for comparing numeric quantities. < Less Than 5 < 5.5 // gives 1
• Relational operators evaluate to 1 <= Less Than or Equal 5 <= 5 // gives 1

(representing the true outcome) or 0 > Greater Than 5 > 5.5 // gives 0

(representing the false outcome). >=


Greater
Equal
Than or
6.3 >= 5 // gives 1
Relational operators
Cont.…
• Note that the <= and >= operators are only supported in the form shown.
• In particular, =< and => are both invalid and do not mean anything.
• The operands of a relational operator must evaluate to a number.
• Characters are valid operands since they are represented by numeric values.
• For example (assuming ASCII coding):
• 'A' < 'F' // gives 1 (is like 65 < 70)
• The relational operators should not be used for comparing strings, because this will
result in the string addresses being compared, not the string contents.
• For example, the expression "HELLO" < "BYE" causes the address of "HELLO" to be
compared to the address of "BYE".
• As these addresses are determined by the compiler (in a machine-dependent
manner), the outcome may be 0 or 1, and is therefore undefined.
• C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
Cont.…
Logical Operators
• C++ provides three logical operators for combining logical expression.
• Like the relational operators, logical operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 1
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical operators

• Logical negation is a unary operator, which negates the logical value of its single
operand. If its operand is nonzero it produces 0, and if it is 0 it produces 1.
• Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it
produces 1.
• Logical or produces 0 if both of its operands evaluate to 0. Otherwise, it
produces 1.
Cont.…
• Note that here we talk of zero and nonzero operands (not zero and 1).
• In general, any nonzero value can be used to represent the logical
true, whereas only zero represents the logical false.
• The following are, therefore, all valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
• C++ does not have a built-in boolean type.
• It is customary to use the type int for this purpose instead. For example:
int sorted = 0; // false
int balanced = 1; // true
Cont.…
Bitwise Operators
C++ provides six bitwise operators for manipulating the individual bits in an integer quantity.
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in both
& operands. (A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is set in one operand but
^ not both. (A ^ B) will give 49 which is 0011 0001
Binary Ones Complement Operator is unary and has the effect of (~A ) will give -61 which is 1100 0011 in 2's
~ 'flipping' bits. complement form due to a signed binary number.

Binary Left Shift Operator. The left operands value is moved left by
<< the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000

Binary Right Shift Operator. The left operands value is moved right
>> by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111
Cont.…
• Bitwise operators expect their operands to be integer quantities and
treat them as bit sequences.
• Bitwise negation is a unary operator which reverses the bits in its
operands.
• Bitwise and compares the corresponding bits of its operands and
produces a 1 when both bits are 1, and 0 otherwise.
• Bitwise or compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise.
• Bitwise exclusive or compares the corresponding bits of its operands
and produces a 0 when both bits are 1 or both bits are 0, and 1
otherwise.
Cont.…
• Bitwise left shift operator and bitwise right shift operator both take
a bit sequence as their left operand and a positive integer quantity n
as their right operand.
• The former produces a bit sequence equal to the left operand but
which has been shifted n bit positions to the left.
• The latter produces a bit sequence equal to the left operand but
which has been shifted n bit positions to the right. Vacated bits at
either end are set to 0.
Cont.…
• To avoid worrying about the sign bit (which is machine dependent), it is common to
declare a bit sequence as an unsigned quantity:
 unsigned char x = '\011';
 unsigned char y = '\027';
• Table below illustrates how the bits are calculated.
• To calculate the bit sequence for the given values of
unsigned char, we need to understand the values in
both octal and binary notation.
Example Octal Value Bit Sequence
x 011 0 0 0 0 1 0 0 1 Step-by-Step Conversion
y 027 0 0 0 1 0 1 1 1 1.Values in Octal:
~x 366 1 1 1 1 0 1 1 0 •\011 in octal
x&y 001 0 0 0 0 0 0 0 1 •\027 in octal
x|y 037 0 0 0 1 1 1 1 1 2.Convert Octal to Decimal:
x^y 036 0 0 0 1 1 1 1 0 •\011 (octal) = 1*8^1 + 1*8^0 = 8 + 1 = 9
x << 2 044 0 0 1 0 0 1 0 0
x >> 2 002 0 0 0 0 0 0 1 0 (decimal)
•\027 (octal) = 2*8^1 + 7*8^0 = 16 + 7 =
23 (decimal)
3.Convert Decimal to Binary:
•9 (decimal) = 00001001 (binary) (8-bit
representation)
•23 (decimal) = 00010111 (binary) (8-bit
representation)
Cont.…
Increment/decrement Operators
• The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable.
• These are summarized in the following table. The examples assume the following
variable definition: int k = 5;
Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators

• Both operators can be used in prefix and postfix form. The difference is significant.

• When used in prefix form, the operator is first applied and the outcome is then used in the
expression.

• When used in the postfix form, the expression is evaluated first and then the operator applied.

• Both operators may be applied to integer as well as real variables, although in practice real
Cont.…
#include <iostream.h>
int main() {
int num1 = 10, num2 = 5;
float decimal1 = 3.5, decimal2 = 2.0;
// Arithmetic Operators
cout << "Arithmetic Operations:" << endl;
cout << "num1 + num2 = " << num1 + num2 << endl;
cout << "num1 - num2 = " << num1 - num2 << endl;
cout << "num1 * num2 = " << num1 * num2 << endl;
cout << "num1 / num2 = " << num1 / num2 << endl;
cout << "num1 % num2 = " << num1 % num2 << endl; // Modulo
(remainder)
// Logical Operators
cout << "nLogical Operations:" << endl;
cout << "(num1 > 10) && (num2 < 10): " << ((num1 > 10) && (num2 < 10))
<< endl;
cout << "(num1 > 10) || (num2 < 10): " << ((num1 > 10) || (num2 < 10)) <<
endl;
cout << "!(num1 > 10): " << (!(num1 > 10)) << endl;
Cont.…
// Relational Operators
cout << "nRelational Operations:" << endl;
cout << "num1 == num2: " << (num1 == num2) << endl; cout << "num1 !=
num2: " << (num1 != num2) << endl; cout << "num1 > num2: " << (num1 >
num2) << endl;
cout << "num1 < num2: " << (num1 < num2) << endl;
cout << "num1 >= num2: " << (num1 >= num2) << endl; cout << "num1 <=
num2: " <<Operators
// Bitwise (num1 <=(assuming
num2) << endl;
integers)
cout << "nBitwise Operations (integers):" << endl;
cout << "num1 & num2: " << (num1 & num2) << endl; // Bitwise AND
cout << "num1 | num2: " << (num1 | num2) << endl; // Bitwise OR
cout << "num1 ^ num2: " << (num1 ^ num2) << endl; // Bitwise XOR
cout << "~num1: " << (~num1) << endl; // Bitwise NOT
cout << "num1 << 2: " << (num1 << 2) << endl; // Left shift
cout << "num2 >> 1: " << (num2 >> 1) << endl; // Right shift
Cont.…
// Assignment Operators
cout << "nAssignment Operations:" << endl;
int result = num1; cout << "result = num1: " << result << endl;
result += num2; // result = result + num2
cout << "result += num2: " << result << endl; result -= num2; // result = result - num2
cout << "result -= num2: " << result << endl; result *= num2; // result = result *
num2
cout << "result *= num2: " << result << endl; result /= num2; // result = result /
num2
cout << "result /= num2: " << result << endl; result %= num2; // result = result %
num2
cout << "result %= num2: " << result << endl;
Cont.…
// Increment/Decrement Operators
cout << "nIncrement/Decrement Operations:" << endl;
int counter = 5;
cout << "counter (before): " << counter << endl;
cout << "counter++ (post-increment): " << counter++ << endl;
cout << "counter (after): " << counter << endl;
cout << "++counter (pre-increment): " << ++counter << endl; cout << "counter
(after): " << counter << endl;
cout << "counter-- (post-decrement): " << counter-- << endl;
cout << "counter (after): " << counter << endl;
cout << "--counter (pre-decrement): " << --counter << endl;
cout << "counter (after): " << counter << endl;
return 0; }
Cont.…
• **Output:**
Logical Operations: Assignment Operations:
Arithmetic Operations:
(num1 > 10) && (num2 < 10): 0 result = num1: 10
num1 + num2 = 15 (num1 > 10) || (num2 < 10): 1 result += num2: 15
num1 - num2 = 5 !(num1 > 10): 1 result -= num2: 10
num1 * num2 = 50 Relational Operations: result *= num2: 50
num1 == num2: 0 result /= num2: 10
num1 / num2 = 2 num1 != num2: 1 result %= num2: 0
num1 % num2 = 0 num1 > num2: 1
num1 < num2: 0
Bitwise Operations (integers): num1 >= num2: 1 Increment/Decrement Operations:
num1 & num2: 0 num1 <= num2: 0 counter (before): 5
num1 | num2: 15 counter++ (post-increment): 5
num1 ^ num2: 15 counter (after): 6 ++counter (pre-increment): 7
~num1: -11 counter (after): 7
num1 << 2: 40 counter-- (post-decrement): 7
num2 >> 1: 2 counter (after): 6
--counter (pre-decrement): 5 counter (after): 5
Cont.…
Precedence of Operators
 The order in which operators are evaluated in an expression is
significant and is determined by precedence rules.
 These rules divide the C++ operators into a number of precedence
levels.
 Operators in higher levels take precedence over operators in lower
levels.
Cont.…
• For example, in a == b + c * d
• c * d is evaluated first because * has a higher precedence than + and ==.
• The result is then added to b because + has a higher precedence than ==,
and then == is evaluated.
• Precedence rules can be overridden using brackets. For example, rewriting
the above expression as a == (b + c) * d causes + to be evaluated before *.
• Operators with the same precedence level are evaluated in the order
specified by the last column of Table 2.7.
• For example, in a = b += c the evaluation order is right to left, so first b +=
c is evaluated, followed by a = b.
Level Operator Kind Order

Highest :: Unary Both

() [] -> . Binary Left to Right

*
+ ++ ! new
- -- ~ & delete sizeof() Unary Right to Left

->* .* Binary Left to Right

* / % Binary Left to Right

+ - Binary Left to Right

<< >> Binary Left to Right

< <= > >= Binary Left to Right

== != Binary Left to Right

& Binary Left to Right

^ Binary Left to Right

| Binary Left to Right

&& Binary Left to Right

|| Binary Left to Right

?: Ternary Left to Right

^=
= += *= &= <<=
-= /= %= |= >>= Binary Right to Left

Lowest , Binary Left to Right


Cont.…
#include <iostream>
using namespace std;
int main() {
// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;
// equivalent expression to num1
int num2 = 5 - (17 * 6);
// forcing compiler to evaluate 5 - 17 first
int num3 = (5 - 17) * 6;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
cout << "num3 = " << num3 << endl;
return 0;
}
Cont.…
• C++ Type Conversion
• C++ allows us to convert data of one type to that of another. This is
known as type conversion.
• There are two types of type conversion in C++:
• Implicit Conversion
• Explicit Conversion (also known as Type Casting)
 Implicit Type Conversion
• The type conversion that is automatically done by the compiler is known
as implicit type conversion. This type of conversion is also known as
automatic conversion.
Cont.…
Simple Type Conversion
• A value in any of the built-in types we have see so far can be converted (type-
cast) to any of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short
• As shown by these examples, the built-in type identifiers can be used as type
operators. Type operators are unary (i.e., take one operand) and appear inside
brackets to the left of their operand. This is called explicit type conversion.
• When the type name is just one word, an alternate notation may be used in
which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
Cont.…
• In some cases, C++ also performs implicit type conversion. This happens
when values of different types are mixed in an expression. For example:
double d = 1; // d receives 1.0
Int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
• In the last example, i + d involves mismatching types, so i is first converted
to double (promoted) and then added to d.
• The result is a double which does not match the type of i on the left side of
the assignment, so it is converted to int (demoted) before being assigned
to i.
• The above rules represent some simple but common cases for type
conversion.
Cont.…
//Type Casting
#include <iostream>
using namespace std;
int main()
{
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;
// C-style conversion from double to int
int num_int1 = (int)num_double;
cout << "num_int1 = " << num_int1 << endl;
// function-style conversion from double to int
int num_int2 = int(num_double);
cout << "num_int2 = " << num_int2 << endl;
return 0;
Cont.…
// Working of implicit type-conversion
#include <iostream>
using namespace std;
int main() {
// assigning an int value to num_int
int num_int = 9;
// declaring a double type variable
double num_double;
// implicit conversion // assigning int value to a double variable
num_double = num_int;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
return 0;
}
Cont.…
#include <iostream>
using namespace std;
int main()
{
int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
return 0;
}
Statements
• Statements represent the lowest-level building blocks of a program.
• Roughly speaking, each statement represents a computational step which has a
certain side-effect.
• (A side-effect can be thought of as a change in the program state, such as the value
of a variable changing because of an assignment.)
• Statements are useful because of the side-effects they cause, the combination of
which enables the program to serve a specific purpose (e.g., sort a list of names).
• A running program spends all of its time executing statements.
• The order in which statements are executed is called flow control (or control flow).
This term reflect the fact that the currently executing statement has the control of the
CPU, which when completed will be handed over (flow) to another statement.
• Flow control in a program is typically sequential, from one statement to the next, but
may be diverted to other paths by branch statements.
• Flow control is an important consideration because it determines what is executed
during a run and what is not, therefore affecting the overall outcome of the program.
Cont.…
• Like many other procedural languages, C++ provides different forms of
statements for different purposes.
• Declaration statements are used for defining variables.
• Assignment-like statements are used for simple, algebraic computations.
• Branching statements are used for specifying alternate paths of
execution, depending on the outcome of a logical condition.
• Loop statements are used for specifying computations which need to be
repeated until a certain logical condition is satisfied.
• Flow control statements are used to divert the execution path to another
part of the program.
Cont.…
Input/Output Statements
• The most common way in which a program communicates with the outside
world is through simple, character-oriented Input/Output (IO) operations.
• C++ provides two useful operators for this purpose: >> for input and << for
output.
Example
#include <iostream.h>
int main (void){int workDays = 5;
float workHours = 7.5;
float payRate, weeklyPay;
cout << "What is the hourly pay rate? ";
cin >> payRate;
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';}
Cont.…
Analysis
• This line outputs the prompt ‘What is the hourly pay rate? ’ to seek user
input.
• This line reads the input value typed by the user and copies it to payRate.
• The input operator >> takes an input stream as its left operand (cin is the
standard C++ input stream which corresponds to data entered via the
keyboard) and a variable (to which the input data is copied) as its right
operand.
• When run, the program will produce the following output (user input
appears in bold):
• What is the hourly pay rate? 33.55
• Weekly Pay = 1258.125
Cont.…
• Both << and >> return their left operand as their result, enabling multiple
input or multiple output operations to be combined into one statement.
• This is illustrated by example below which now allows the input of both
the daily work hours and the hourly pay rate.
Example
#include <iostream.h>
int main (void)
{
Int workDays = 5;
float workHours, payRate, weeklyPay;
cout << "What are the work hours and the hourly pay rate? ";
cin >> workHours >> payRate;
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = " << weeklyPay << '\n';
}
Cont.…
Analysis
• This line reads two input values typed by the user and copies them to workHours and payRate, respectively.
• The two values should be separated by white space (i.e., one or more space or tab characters).
• This statement is equivalent to: (cin >> workHours) >> payRate;
• Because the result of >> is its left operand, (cin >> workHours) evaluates to cin which is then used as the left
operand of the next >> operator.
• This line is the result of combining lines 10-12 from example 2.1.
• It outputs "Weekly Pay = ", followed by the value of weeklyPay, followed by a newline character. This
statement is equivalent to: ((cout << "Weekly Pay = ") << weeklyPay) << '\n';
• Because the result of << is its left operand, (cout << "Weekly Pay = ") evaluates to cout which is then used as
the left operand of the next << operator, etc.
• When run, the program will produce the following output:
• What are the work hours and the hourly pay rate? 7.5 33.55
• Weekly Pay = 1258.125
Cont.…
Null statement
Syntax:
;
Description: Do nothing
The block statement
Syntax:
{
[<Declarations>].
<List of statements/statement block>.
}
• Any place you can put a single statement, you can put a compound statement, also called a block.
• A block begins with an opening brace ( {) and ends with a closing brace (}).
• Although every statement in the block must end with a semicolon, the block itself does not end with a semicolon. For
example
{
temp = a;
a = b;
b = temp;
}
• This block of code acts as one statement and swaps the values in the variables a and b.
Cont.…
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10, temp;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Cont.…
The Assignment statement
Syntax:
<Variable Identifier> = < expression>;
• Description:
• The <expression> is evaluated and the resulting value is stored in the
memory space reserved for <variable identifier>.
Eg: - int x,y ;
x=5;
y=x+3;
x=y*y;

You might also like