2nd Year Computer Chapter 03 Notes
CHAPTER 3
OBJECT ORIENTED PROGRAMMING
IN C++
1
LE Boi Soe eA GEa dere WY. Ig aePILy wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
After completing this lesson, you will be able to:
* Define program
* Define header file and reserved words
* Describe the structure of C++ program
Know the use of statement terminator
+ Explain the purpose of comments and their syntax
+ Explain the difference between constant and variable
Explain the rules for specifying variable names
* Know data types used in C++
* Define constant qualifier ~const <
Explain the process of declaring and initializing variables
© Use type casting
‘+ Explain the use of cout statement
«Explain the use of cin statement
« Define getchQ, gets() and puts() functions
* Define escape sequence
* Use of escape sequence in programs
* Use I/O handling functions
Use manipulators endl and setw
* Define operators and know thei use in programs
Use unary binary and ternary operators in programs —
+ Define expression
* Define and explain the order of precedence of operators (
* Define and explain compound expression
1.1 INTRODUCTION
Q1. Give a brief introduction to C++
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Answer
C++
C++ isa general purpose programming language that supports various computer
programming models such as Object Oriented Programming (OOP) and generic
programming. Bjrance Stroustrup created it in early in 1980s at Bell Laboratories
Purpose of C++
Main purpose of C++ was to make writing good programs easier and more pleasant for
the individual programmer
Use of C++
C++ supports modern programming techniques. It is commonly used for developing
high performance commercial software, games and graphic related programs.
1.1.1 COMPUTER PROGRAM
Q2. What is meant by a computer program? Explain.
Answer
Computer Program
Acomputer program is a set of instructions that performs a specific task when I
executed by a computer. It tells the Computer what to do.
Explanation
Everything a computer does is controlled by computer program
Examples
Microsoft Word is a program that allows computer users to create documents. Skype is
a program used to make cell free of charge to other people who are on Skype.
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Q3, Define development of program, machine language, source code and object
code
Answer
Development of Programs
Generally programs are written in English oriented high level languages such as Visual
Basic, Pascal, Java C++ ete
Machine Language
Acomputer can only understand instruction in machine language, which consists of Os
and 1s. Therefore, a program written in a high level language must be translated into
machine language before execution. This task is achieved by software known as
compiler
Source Code & Object Code
A program written in high language is called source code and its equivalent program
in machine language is called object code
1.1.2 HEADER FILE AND RESERVED WORDS
Q4. What are header files? Give some examples
Answer
Header Files
The C++ contains many header files. Header files contain information that is required by
the program in which these are used. It has .h extension.
Examples of Header files
Some examples of header files are iostream.h conio.h and math h, These files are
included in the standard library of C++ compiler
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Q5, What are pre-processor directives? State its syntax & give some examples
Answer
Pre-processor directive
Pre-processor directive is used to include a header file at the beginning of program.
Pre-processor directive is not a normal program instruction to be executed by the CPU.
Itis a code for the compiler to include a header fle
Syntax of Pre-processor Directive
The syntax of pre-processor directive to include a header file in a program is =~
# include
It begins with a #sign followed by the world include and then name of header file is
written angled brackets <>
Example 1
To include the header file iostream.h in a program, the code is =
#include
The effect of this line is to copy all the contents of iostream.h header file into the
program and make them available for use. Almost all the C++ programs perform
input/output operations. Therefore, generally this header file is included in the
programs.
Example 2
The following is another example for including math.h header file in a program
#include
The math.h header file contains code for performing mathematical functions such as
finding the square root of a number.
Q6. Define reserved words. Make a list of reserved words
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Answer
Reserved Words
Reserved words are special words which are reserved by a programming language for
specific purpose in program. These cannot be used as a variable names. Alll the
reserved words are written in lower case letters. There are about 80 reserved words in
C++ but this may vary depending on the version being used.
Example
Some examples of reserved words of C++ are if, void, break, while, case and char
List of Reserved Words
The reserved words of C++ are
And |And_|Asm | Auto Bitand | Bitor Bool Break
eq VU:
Case |Cate |Char | Class Const | Const_c |Continue —_| Default
h ast
Delet |Do | Doub! | Dynamic_ | Else Enum | Explicit Export
e e cast
Extem | False | Float | For Friend |Goto |if Inline
Int |Long |Mutab|Namespac |New — | Not Not_eq Operat
le e or
Or Ore |Privat |Protected | Public | Register | Reinterpret_ | Return
q e cast
Short | Signe | Sizeof | Static Statice |Struct | Switch Templa
d ast te
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
This |Thro |tue | Try Typedef |Typeid |Typename | Union
w
Using |Virtu | Void | Volatile — | Unsigne | Wehar_t | While Xor_eq
al d
Xor
1.1.3 STRUCTURE OF C++ PROGRAM
Q7. Describe the structure of a C++ program
Answer
Structure
AC++ program has the following structure
Pre-processor directives
Void main()
{
Body of main () function
}
Explanation
A C++ program starts with pre-processor directives, followed by the line void main()
function and then the body of the main() function is written within curly brackets and }
Body of main( function
Body of main() function consists of executable statements. These statements perform a
specific task when the program is executed by the CPU. There is no restriction on the
number of statement that can be written in the body of main() function
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Program
To understand the structure of program, consider the following program
#include
Void main()
{
Cout<< “Information Technology;
}
Explanation
#include
This is the first ine of the program and it is a pre-processor directive. This program prints
a message on the screen. Therefore, iostream h header file is included which contains
the code for performing input/output operations
Void maind
This line identifies the main function of the C++ program. All C++ programs must have
main() function. If a program consists of more than one function, the location of main()
does not matter. In C++ program the main() function is always executed first
Cout << Information Technology
This is a C++ statement. The meaning of this statement is to print the message
Information Technology on the screen. This statement is written within the curly brackets
and is called body of the main () function.
1.1.4 STATEMENT TERMINATOR (;)
Q8. Give a brief introduction to statement terminator.
Answer
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Statement Terminator
In C++, semicolon is a statement terminator. It marks the end of a statement. All the
C++ statement must end with a semicolon. The following statement was used in the
following code notice that it ends with a semicolon
Cout<<*Information Technology”;
If," Is missing the compiler will give syntax error number and also the message that ",”
is missing. The error number and message may vary depending on the compiler used.
1.1.5 COMMENTS IN C++ PROGRAM .
Q9. State the purpose of comments in C++ program? How many types of comments are.
used in C++? Explain
Answer
Comments
All the programming languages allow comments in programs. Comments are
explanatory statements that help the reader in understanding source code. Comments
can be entered at any location in the program. Comments are ignored during
program execution. Which means they are not executable statements.
Types of Comments UW
There are two types of comments in C++. These are given below C)
i. Single line Comments 7
ji, Multiple ine Comments
i. The Single Line Comments (/)
The single line comments start with // (double slash) and continue until the end of
the line
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Program
The following program demonstrates the use of single line comments
// thisis a very simple C++ program
# include
Void main 0)
{
‘Cout << ‘Information Technology’
//it prints a message on the screen. <
)
li, The Multiple Line Comments (/* and */)
This type of comments is used for entering multiple line comments in a ;
program. The /* is used at the beginning of comments and */ ends it =
Program
The following program demonstrates the use of multiple line comments
/* this is my fiist C++ program
It demonstrates the
Structure of C++ program
v W
# include
Void main ()
Cout <<" Information Technology”,
a:
The /* and */ type comments can also be used to enter comments on a single
line as shown below
/* this is my first C++ program */
10
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Q10. State the purpose of constants and variables in programs
Answer
Constants and variables are used in programs to perform calculation of various types.
Therefore, it is important to understand how they are used in computer programs
1.2.1 CONSTANTS AND VARIABLES
Q11. Define constants and its types. Give examples
Answer
Constant
In computer programming a constantis a value that does not change during
execution of program
Types of Constants
A constant can be a number, a character or a character string. A character string is a
sequence of any number of characters.
Q12. Define variable
Answer
Example of Constants
Some examples of constants are 42, 7.25, ‘s’ and ‘computer’ respectively. In C++ a
single character constant is written single quotes and a string constant within double
quotes,
u
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Q12. Define variable
Answer
Variable
Avariable is a name of memory location where data is stored. Variables are used in
computer programs to store values of different data types, The data stored ina
variable may change during program execution.
1.2.2. RULES FOR SPECIFYING VARIABLE NAMES
Q12. Write down the rules for naming a variable
Answer
The following are the rules for naming a variable pe
1. The first character of a variable name must be alphabet or underscore
2. The characters allowed in a variable name are
i. Underscore (_)
li, Digits (0 to 9)
li, Upper case letters (A to 2)
iv. Lower case letters (a to z)
Uppercase Letter
An upper case letter is considered different from a lower case letter
Example
The variable SUM is different from Sum or sum
Underscore
The underscore (_) is generally used to improve readability
Example
12
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
The variable overtime may also be written as over-time
3. Special symbols such as $, @, %, # are not allowed
4, Blank space or comma |s not allowed
5. Reserved words of C++ are not allowed to be used asa variable name
1.2.3 C++ DATA TYPRS
Q14. Explain the data types in C++
Answer
Data Types
Data types are declarations of variables for storing various types of data. Data types
have different storage capacities. In C++ programs data types of a variable must be
defined before assigning it a value
Data types in C++
The data types used in C++ programming are as follows
i. Integer
li, Floating point
iil, Double precision
iv. Character r -
W
1. Integer
Itis a data type that is used to define numeric variables to store whole numbers”)
such as -3, 0, 367, +2081etc. Integers represent values that are counted such as ;
number of students in a class. The short form of integer is int Numbers that have
fractional part such as 3.84 cannot be stored in an integer variable
Types of Integer
The following table shows the integer types, the number of bytes it takes in memory to
store the value and the range of numbers it can store.
13
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Floating type Number of Bytes Range of Numbers
Int 4 bytes -2147482648 to 21474483647
Unsigned int 4 bytes 0 to 4294967295
Short int 2 bytes -32768 to 32767
Unsigned short int 2 bytes 0 to 655535
Long int 4 bytes -2147483648 to 2147483647
Unsigned long int 4 bytes 0 to 4294967295
2. Floating point
Itis a data type that is used to define variables that can store numbers that have
fractional part such as 3.75, 2.1, 388.80 etc. these numbers are also known as real
numbers. The short form of floating point is float
Types of Floating Point
The following table shows the floating point types. The number of bytes it takes in
memory to store the value and the range of real numbers it can store.
The float type variable might occupy different numbers of bytes and their range
might also different depending on the computer and the compiler being used [
3. Character
Itis a data type that is used to define variables that can store only a single
character. One byte memory is set aside in memory to store a single character.
The short form of character is char. A variable of type char can store lower case
letter an upper case letter, a digit or a special character
Examples
14
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Some examples of characters that can be stored in a variable of type char are
.'*" '%' and ‘5’, Note that characters are written within single quotation marks
C1)
3.2.4 THE CONSTIANT QUALIFIER (const)
Q15. Give a brief introduction to CONST qualifier in C++
Answer
Constant Qualifier
In C++ programming language, const defines a variable whose value cannot be
changed throughout the program. When the const qualifier is used with a variable, it
no longer remains a variable because its value will not be changed. A variable defined
with the const qualifier must be assigned some value —
Syntax
Const has the following syntax
Const data_type variable = constant
Examples
Const int AGE= 34
Const float LENGTH = 7.5
The variables of type const are generally written in upper case letters
3.2.5 VARIABLE DECLARATION AND INITILIZATION
Q16. Describe the variable declaration and variable initialization with examples
Answer
15
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Variable Declaration
In C++ all the variables that are going to be used in a program must be declared
before use. Declaring a variable means specifying the data types of a variable. It
allows the compiler to decide how many bytes should be set aside in memory for
storage of value that is going to be assigned to the variable in the program
Examples of variable Declarations
The following are some examples of declaring variables
Intx, yz: =
Float length, breadth, sum:
Char ch:
Explanation of Examples
Here the variables xy and z are declared as type of Int, length and breadth as of type
float and ch as of type char. ss
Initialization of variable
A variable may be initialized at the beginning of a program when it is declared
Initialization a variable means assigning it an initial value.
Explanation of Examples
In the first declaration statement, the variable x is initialized to integer constant 4 and y
to 5. The second statement initialized length to 12.5 breadth to 15.25 and sum to 0.0.
The last statement initialized the character variable ch to a
3.2.6 TYPE CASTING
Q17. What is meant by type casting? Explain its types with examples
Answer
16
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Type Casting
Type casting is used in C++ to convert data type fram one types to another
Types of type casting
There are two types of type casting
i. Implicit type casting
li, Explicit type casting
1. Implicit Type Casting
Implicit type casting automatically converts a data type to another
Example
This is explained by the following example
Suppose variable q is declared as of type float and the following calculation is to be
performed
q= 15/6
Explanation
When this integer division is performed, the result will also become an integer value 2
which will be implicitly converted to floating point value 2.0 and assigned to the
variable 1
If one or both of the integer constants are converted to floating point constant (14.0 or
6.0) this will perform division using floating point mathematics. In this case, the result
produced will be 2.5 and it will be assigned to q
2. Explicit Type Casting
In explicit type casting a special operator is used to convert one data type into
another
General form
7
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
The general form for conversion is (type) expression
Here expression can be an arithmetic expression or a variable
Example
This is explained by the following example
Suppose a and b are variables of type int and q is of type float. The integer value 15 is
stored in a and 6 in b and the following division is to be performed
Q = a/b
Explanation
When this division is performed, integer math will be used and the result produced will =
be 2, which will be assigned to the variable q
To obtain correct result, type casting should be used to convert at least one of the
operands to type float as shown below
Q= (float)a/b: —
Now first the value stored in a will be converted to type float and then the division will
be performed. The floating-point math will be used and the correct result 2.5 will be
produced which will be assigned to q
Similarly, the int type can also be used to convert a floating point value stored ina
floating point variable into integer type by truncating the fractional part of the number.
3.3. INPUT/OUTPUT HANDLING (
Q18. Describe input/output handling and functions for handling I/O in C++. Also define
streams
Answer
Input/Output Handling
18
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
In computer programming, providing data into a program from outside source is also
known as input and output means to display some data on screen or save in a file on a
storage device
Functions for Handling 1/0
The functions getch() gets() and puts() are also used for handling input/output
operations
Streams
In C++ input/output is performed by using streams. A stream is a sequence of data that
flows in and out of the program. The cin and cout are the standard statements that use
the iostream.h header file for performing I/O operations. Therefore, it must be included
at the beginning of program.
1.3.1. THE cout STATEMENT
Q19. Describe cout statements in C++
Answer
Cout Statement
The cout statement is used to output text or values on the screen
Syntax
Co)
The following is the syntax of cout statement @)
Cout< / / this header file is used for /O functions
Void main()
{
Inta
Aq12
Cout<<"the value stored in a is”
Cout< >variable:
Explanation
The keyword cin is used with the extraction operator on the right side which is two
greater than signs (>>) followed by a variable. When this input statement is executed, it
causes the program to wait for the user to input data. The data entered by the user is
assigned to the variable
Program
The following program demonstrates the use of cin statement
#include
Void main()
{
Int n.
Coute<‘Enter an integer:";
Cin>>n UW
Cout<<"the number you types is >a>>b;
The values for variables a and b should be input with space between them
1.3.3. THE getch0, getcheO, gets AND puts() FUNCTIONS
Q21. Explain the functions, which are used for handling I/O operations.
Answer
Handling I/O Operations
These three functions are also used for handling I/O operations
i. Getch0 function
li, Getche() function
ii, Gets( and puts() Functions
1, The getchO Function
In some situations in programming it Is required to read a single character the
instant it is types without waiting for Enter key to be pressed.
Example
In a game we might want an object to move each time we press one of the
arrow keys. It would be awkward to press the Enter key each time we pressed an
arrow key
22
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Explanation
The getch( function is used for this purpose. The get means it gets something
from an input device and ch means it gets a character. This function uses the
conio.h header file. Therefore, it must be included in the program.
Program- Demonstrates the use of getch() function
The following program demonstrates the use of getch() function to read a
character from the keyboard and displays it on the screen
#include
#include
{
Char ch
Cout <<'Enter a character’
Ch=getch);
Cout<<'the character you types isi” ,ch:
Getch 0;
)
The execution of the program is shown below with the input character a
Output of the program
Enter a character
The character you types is a
Explanation <4
Note that when this functions is used, the input character a is read and stored in
variable ch but it is not displayed on the screen
2. The getche() Function
If the user wants the typed character to be displayed on the screen then another
similar function getche( is to be used. In this function, the letter is added which
means to echo or display the input character on the screen
Explanation
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
When executing a program, some C++ compilers display the output for a very
short time and immediately returns to the editing window. The user is not able to
see the program output. Therefore, very often getch( functions is used at the
end of the program so that the user is able to see the program output and has to
enter any character to return to the editing window. Since the character entered
is not used in program, there is no need to store in a variable. This is shown below
Program
#include
#include
{
Char ch
Coute<"Enter a character."
Ch=getche()
Cout< header
file
24
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Program-demonstration of gets() function
#include
#include
Using namespace std;
Int main()
{
Char str [100]
Cout << Enter a string’ :
Gets (str)
Cout << “you entered” << str
Retum 0
}
Output of the Program
Happy New Year
Happy Birthday
Program- demonstration of puts() function
#include
Int main()
{
Char stri(] = ‘Happy New Year’
Char str2{] = ‘Happy New Year’
Puts(str1)
/* Printed on new line since '/n’ is added */
Puts (str2)
Retum 0
}
Output of the Program
Happy New Year
Happy Birthday
25
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
3.3.4 THE ESCAPE SEQUENCE
Q22. What is meant by escape sequences? Explain its structure and uses.
Answer
Escape Sequences
Escape Sequences are special characters used to control the output look on output
devices, These characters are not printed. These are used inside the output statement
Structure of Escape Sequences
An escape sequences begins with a backslash (/) followed by a code character. These
are called escape sequences because the backslash causes an escape from the
normal way characters are interpreted in C++ programming language
Uses of Escape Sequence an
Escape sequences are used for special purposes in programming such as to begin
printing on the next line to issue a tab to print special characters etc
3.3.5 COMMONLY USED ESCAPE SEQUENCES
Q23. Which escape sequences are commonly used in C++ programs?
Answer
Commonly Used Escape Sequence
The commonly used escape sequence are \a \b \n \r \\ \' and \\"
Explanation
Suppose we want to print the following message on the screen
Cout<<"There are many versions of*
26
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Cout<<"Windows operating system”:
When the above two statements are executed, the output will appear on a single line
as shown below
There are many versions of Windows operating system
IFit is desired to display the output in two lines then \n escape sequence can be used
in various ways to move cursor to the beginning of next line
Cout<<" \nthere are many versions of*
Cout<<"\nWindows operating system":
The following two statements can also obtain the same output.
Cout<<" Windows operating system”
A single output statement can also be used
Cout<<"\nThere are many versions of \nWindows operating system; =>
Similarly, the \t escape sequence can also be used to tab over eight characters as
shown in the following statement
Cout<<"C+ +\tis\ta\thigh\tlevel\tlanguage”
The output of this statement will be
C++ is a_ high level language
List of Escape Sequence W
A\list of commonly used escape sequences is given in the following table with their (
meanings
Escape Purpose Escape | Purpose =
sequence sequence
\a Produces alert (beep) | \t Moves cursor to the next
sound horizontal tabular positions
27
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
\b Moves cursor backward | \\ Produces a backslash
by one position
An Moves cursor to the at Produces a double quote
beginning of next line
\ Moves cursor to the v Produces a single quote
beginning of current line
The following statement uses the \" escape sequences to print the word ‘Pakistan’ in
double quotation marks
Cout<<" this will print the word \"Pakistan\’ in double quotation marks":
The escape sequence \ and \\ are also used in the same way to print a single quote
or a backslash,
3.3.6 PROGRAMMING WITH I/O HANDLING FUNCTIONS
24. Write a program reads that three integers and prints their sum and product
Answer
Product
#include
#include
Void main()
{
Int x,y.z.sum,prod:
Cout<<"\nEnter first number:”
28
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Cin>>x:
Coute<*\n€nter third number"
Cin>>z:
Sum=x+y+2:
Prod=x*y*z
Coute<"\nsum="<
#include
Void main()
{
Float base, height, area
Cout<<\nEnter the base”
Gin>>height
Area=(base*height)/2
Cout<<"\nthe area of triangle is"<< area’
Getch():
}
Explanation
In this program two separate input statements are used for reading the values for
variable base and height
Output of the Program
The execution of program is shown is below
Enter the base 4:5
Enter the height 6:2
The area of triangle is 13.95
3.3.7 THE MANIPULATORS endl AND setw
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
26. What is meant by manipulators in C++? Explain endl and stw with programs
Answer
Manipulator
A manipulator is a command in C++ that is used for formatted output. It modifies the
output in various ways. There are many manipulators available in C++. The most
commonly used manipulators are endl and setw. The iomanip.h header file should be
included when manipulators are used in a program. Only the endl manipulator can be
used without using ionmanip.h file.
The endl Manipulator
The endl manipulator has the same function as the \n escape sequence. It causes a
linefeed in the cout statement so that the subsequent text is displated on the next line
Program- Demonstrates the use of endl manipulator
The following program demonstrates the use of endl manipulator
#include
#include
#include
Void main()
Cout<<"\nl am a student” <
#include
#include
Void main()
( WO
Int price1=8540, price2=325, price3=27800 co)
Coute< “Product” *<
#include
#include
#include
Void main()
Int price1=8540, price2-325, price 3-27800
Cout<<"Product —“<
Avithmetic operators
Avithmetic assignment operators
Increment/decrement operators
Relational operators
Logical operators
Ternary operators
Assignment Operator
Assignment operator is equal sign (=). Itis used to assign value of an expression to
a variable
General form
It has the general form
Variable= expression
Where expression may be a constant another variable to which a value has
previously been assigned or a formula to be evaluated.
35
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Example
Zex+y:
When this statement is executed, the values stored in variables x and y will be
added and the resulting answer will be stored in variable z
2. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that include
addition, subtraction, multiplicati
Nn, division and to find the remainder of integer
division
Types of Arithmetic Operators
The types of arithmetic operators used in C++ programming are described with
their operations in the given table
Operators ‘Operation
x ‘Addition
e ‘Subtraction
* Multiplication
7 Division
% Modulo operator
The modulo operator (%) gives the remainder after division of one number by another
Example
A=20 %6
Will give the result 2 which will be assigned to the variable a because 6 will divide 20 by
3 with a remainder of 2
Examples of Modulo Operator
Some more examples of modulo operator are given below
36
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
13% 4 Will give the result 1
15 % 4 Will give the result 3
10% 5 Will give the result 0
4 %5 Will give the result 4
3. Arithmetic Assignment Operators
In addition to equal (=) assignment operator, there are a number of assignment
operators unique to C++ which are known as arithmetic assignment operators. ~
/
These include +=, -=, /= and %=
Explanation
Suppose op represents an arithmetic operator. Then, the arithmetic assignment
operator has the following general form to assign value of an expression to a variable
Variable op = expression: —
Example
at=b;
Itis equivalent to
a=a+b
The effect is exactly the same but the expression is more compact (
Arithmetic Assignment Operators with theit Operations co)
The arithmetic assignment operators are described in the following table
Operator Operation Example
ro Operand and assigns the result to the | A+=b
left side
37
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
This equivalent to a=a+b
operand
= Subtracts the right side operand from | K-=n
the left side operand and assigns the | its equivalent to k-k-n
result to the left side operand
ts Multiplies the right side operand with the | Prod*=n
left side operand and assigns the result | i js equivalent to
to the left prod=prod’n side
operand
I Divides the left side operand by the right | n/=m
side operand and assigns the result to
the left side
itis equivalent to n=n/m
operand
%: Takes modules and assigns the result to | x%=y
the left side operand Itis equivalent to x=x%y
Relational Operators
Relational operators are used to compare two values of the same type. These
operators are very helpful in computer programming when a flow of program is based
ona condition. After evaluation of a relational expression, the result produced in True
or False
Types of Relational Operators
Six types of relational operators are available in C++ language. These are described in
the following table
Operator _| Operations Example
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Equal to
te Not equal to Ni-m
< Less than Acb+c
> Greater than ey
<= Less than or equal to Le=(x4y)/2
<= Greater than or equalto | F>=a+12
Examples of Relational Operators
The following are some examples of relational operators
»>y
z>xty
z<=K+y
x!=10
i. Ifx has the value 12 and y has the value 7, then the condition in first line will
become true since 1 Is greater than 7
li, The condition of second expression will become false since 12 is not equal to 7
iii, In the third expression, if z has the value 15, then the condition will become
false since 15 is not greater than the sum of x and y which is 19
iv. In the fourth expression 15 Is less than 19, Therefore, the condition will become
true
v. Inthe last expression, if x is any number other than 10 then the expression will
be true it will only be false when x is equal to 10
NOTE: In C++ language, true is represented by the integer 1 & false is represented by
the integer 0.
Liss A teed i Erde ed Fig aetiL yoo .
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
4. Logical Operators
Logical operators are used in programming when it required to take some action
based on more than one condition
Compound Condition
When two or more conditions are combined, it is called compound condition.
Q30. Explain the types of logical operators
Answer
Types of logical Operators
There are three types of logical operators, These are described below
Operator | Operation
&& AND
" OR
! NOT
i. Logical AND (&&) Operator
It is used to form compound condition in which two relational expressions are
evaluated, One relational expression is to the left and the other to the right of
the operator. If both of the relational expressions (conditions) are true then the
compound condition Is considerable true otherwise it is false
Explanation with examples
1. The following is a Compound condition that uses the && operator
(x>=1) && (K<=10)
When the compound condition is evaluated, it will produce the result true if xis
greater than or equal to 1 and less than or equal to 10. In other words, the result
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
will be true if both conditions are true that is x isin between 1 and 10 otherwise it
will be false
2. The following compound condition will check whether the character stored in
character variable ch is a lowercase letter or not
(che="a’) && (ch<='2’)
Truth table of AND logical Operator
The following truth table shows alll the possible results of AND (&&) logical operator for
two expressions
Expression 1 _| Expression 2 Expression 1 && Expression 2 »
False False False i :
False True False :
True False False =>
True True True ;
i, Logical OR (11) Operator
Logical OR operator is also used to form a compound condition. Just like the logical
AND operator one relational expression is to the left and the other to the right of the
OR operator. The compound condition is true if either of the conditions is true or
both are true. It is considered false only if both of the conditions are false, UW
Explanation C)
The following is an example of compound condition that uses Il operator
(x>y) 11 @==8)
This compound condition will produce the result true. if one of the conditions is true,
that is, ifxis greater than y or z Is equal to 8. The result will only be false when both of
the conditions are false, that is, x is not greater than y and zis not equal to 8
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Truth table of OR logical Operator
The following truth table shows all the possible results of OR (\I) logical operator for two
expressions
Expression 1 Expression-2 Expression-1 I | Expression-2
False False False
False True False
Tue False False
True True true
iii, Logical NOT () Operator
The logical NOT operator is used with a single expression (condition) and
evaluated to true if the expression is false and vice versa. In other words, it pod
reverses the result of a single expression. :
Example
The expression
I(@>=10)
Will be true if zis not less than 10. In other words, the condition will be true if z is
greater than or equal to 10. Some programmers may prefer to write the
above expression as given below which is easy to understand and has the
same effect,
Truth table of NOT logical Operator
The following truth table shows all the possible results of NOT (!) logical
‘operator for one expression
Expression lExpression
False awe
ae False
42
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
Q31. Explain ternary operator OR conditional operator with examples
Answer
Temary Operator (? :) / Conditional Operator
The ?: operator is known as ternary or conditional operator. It returns one of two values
depending on the result of a condition. Therefore, it is also known as conditional
operator. It is very useful in situation where the programmer needs to choose one of
two options depending on a single condition
General Form
The general form of ternary operator is
Condition Expression 1. Expression2
The condition is evaluated if it is true then Expression! is evaluated otherwise
Expression2 is evaluated
Example ss
The following is an example of using ternary operator
(xoy)? x+y: HY
Explanation
When this code is executed, the condition x>y is evaluated. If the result is true then the
value x+y is evaluated otherwise the value x-y is evaluated. It allows to execute
different code based on the result of condition ey
The result of teary operator can be assigned to a variable as shown below
Kz (oy)? x+y: xy:
Program 1
The ternary operator is demonstrated in the following program
#include
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
#include
Void main()
{
Int xy.
X=15;
Y=10:
Kecoy)?x + yi xy
Cout<<"the value of k Is *<y) is true and k will be
assigned the sum of x and y
Output of the Program
The output of the program will be
The value of k is 25
The temary operator also allows to output text as shown below
(x>y)? cout<<"x is greater than y": cout<<"x is smaller than y"
Program 2
This is demonstrated in the following program
#include
#include
Void main()
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
{
Int xy.k
X=3:
Y=10:
(xy) cout<"x is greater than y"<y) is false and
the second output statement will be executed
Output of the Program
The output of the program will be
Xis smaller than y
Q32. Explain increment and decrement operators with examples
Answer
Increment and Decrement operators
The increment operator is ++ and it is used to add one to the value stored in a variable
The decrement operator is - and it subtracts one from the value stored in a variable
The purpose of using these operators is simply to shorten the expression
Examples
sex and x++ Are both equivalent to. | X=x+1
45
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
eT Are both equivalent to. |X =x-1
Prefix & Postfix
When increment or decrement operator is written before the variable, it is known as
prefix and when it is written after the variable, it is known as postfix
In certain situations ++x and x++ have different effect. The is because ++x increments x
before using it value whereas x++ increments x after its value is used
Example
Suppose x has the value 3. The statement
Y= sex;
Will frst increment x and then assigns the value 4 to y, but the statement
Yo xtt:
Will fist assign the value 3 to y and then increments x to 4. In both cases, x is assigned
the value 4 but y is assigned different value. The same rules applies to -x and x—as well
Example of Prefix Increment
#include
#include
Void main()
{
Int xy:
Y=10:
Xetty:
Coute<"x: "<
#include
Void main
0
{
Int xy:
Y=10:
Xayt+
Coute<"x) “="a’) && (ch<="2') Il ((ch>="A’) && (ch<='2'))
Explanation
51
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
The first compound condition ((ch>='a") && (ch<="2') Il ((ch>="A’) && (ch<='Z'))
checks whether the character stored in variable ch is a lower case letter or not and the
second compound condition ((ch>="A’)&& ((ch<="Z') checks whether it is an upper
case letter or not if one of the two compound conditions is true, the compound
expression will be true because the two compound conditions are combined with an Il
(OR) operator
KEY POINTS
* Acomputer program is a set of instructions to perform a specific task
* Header files contain information that is required by the program in which they
are used. It has h extension
* Reserved words are special words which are reserved by a programming
language for specific purpose In program
* In C++ semicolon is a statement terminator. It marks the end of a statement. All
the C++ statements must end with a semi colon
* Comments are explanatory statements that help the reader in understanding
source code
* Aconstant is a value that does not change during execution of program
* Avariable is a name of memory location where data is stored. Variables are
used in computer programs to store values of different data types
+ Escape sequences are special characters used to control printing on the output
device. These characters are not printed. These are used inside the output
statement
NOD ES3MNVASN MMM
* Order of precedence of operators describes the rules according to which
operations are to be performed in an expression
* An operator is a symbol that tells the computer to perform a specific computing
task
Liss A teed i Erde ed Fig aetiL yoo
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
* Assignment operator is equal sign (=). It is used to assign value of an expression to
a variable
Relational operators are used to compare two values of the same type
Logical operators are used in programming when it is required to take some
action based on more than one condition
* An expression is a combination of constants, variables and operators. Constants
and variables are operands and operators tell the computer what types of
action to perform on the operands
* An expression that combines two or more conditions using logical operators &&
or llis called compound expression <
53
LE Boi Soe eA GEa dered Pu ge Be PIL, wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM2nd Year Computer Chapter 03 Notes
All Classes Chapter Wise Notes
Punjab Boards | Sindh Boards | KPK Boards| Balochistan Boards
AJK Boards | Federal Boards
CIF of tetete Fre bE LOU 97 ver ige BS IL BE
LI NSS SIL Dit OMIT HANIF
Oth Class
tse Ids Ge
10th Class
CSE Ee esa
WWW.USMANWEB.COM WWwW.USMANWEB.COM
11th Class fi 12th Class
POC NCS a ans
Ig BP IQ LI BE
nes I be ALES fra
0306-8475285
LE Boi Boe A bEa dered WY. Ig akPILy wee
All Classes Chapter Wise Notes, Past Papers Free Download In PDF
WWW.USMANWEB.COM