0% found this document useful (0 votes)
119 views83 pages

Oops C++ Notes

The document provides an introduction to object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also compares C and C++, reviewing features of C like algorithms and flowcharts. Input/output operations in C++ using cin and cout streams are described. The use of new and delete operators for dynamic memory allocation in C++ is explained.

Uploaded by

frogtail03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views83 pages

Oops C++ Notes

The document provides an introduction to object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also compares C and C++, reviewing features of C like algorithms and flowcharts. Input/output operations in C++ using cin and cout streams are described. The use of new and delete operators for dynamic memory allocation in C++ is explained.

Uploaded by

frogtail03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

UNIT-1

1
INTRODUCTION TO C++

UNIT-1 OOPs

Introduction
2

 Entity refers to anything that exists and is distinguishable from one another. E.g.
table, chair, pen, fan , light, book, student, ball etc.
 All these entities / objects have some features/attributes/ characteristics of their own.
E.g. ball has attributes like it is round, it is white in colour, its diameter etc.
 The need is to model the real world entities or objects in order to solve a
problem.
 These entities are nothing else but the objects around us.
 Thus, many object-oriented languages were developed like C++, JAVA,
SMALLTALK, PYTHON, SCALA, JULIA, LISP, OBJECTIVE-C, SIMULA and so
on.

UNIT-1 OOPs-

 C++ was designed and developed by Bjarne Stroustrup at AT and T BELL


3

 Reusability of the code is the central core concept of these OOP languages.
 Here, you divide the problem into different objects rather than functions as in
structured programming languages like C.
 Several OOPs languages support AI tasks also like Python, LISP, SCALA, JULIA.
 Several compilers also exists for C++ like TC++, Borland C++ , GCC is free
C++ compiler etc.

LABS. in 1980s.

UNIT-1 OOPs-

Functional and Data Decomposition


4

 I. Functional Decomposition
 It is used to visualize the data flow between different processes in a business.
 It is based on classical DFD.
 It is used to specify the global functions that operate on the objects.
 By performing functional decomposition we can develop a functional model.
 Functional model = DFDs + constraints = Data Flow Diagrams  The need is to
verify, iterate and refine these models.

UNIT-1 OOPs-

 II. Data Decomposition


 OOP technique focuses on modeling of the real world problems in terms of objects.
This is known as data decomposition.
 The constructs of OOP, modeled out of these data types are called as classes.
 Putting data and functions together into a single unit is the central theme of OOP.
UNIT-1 OOPs-

Objects
6

 An object is a logical entity containing data and code that manipulates that data.
 It is an instance of a class.
 It is a run-time entity.
 Objects may be-
 A) logical objects like a library software.
 B) physical objects like a person, a chair, a table etc.
The state of an object changes according to the methods applied to it. Objects communicate
with other objects through functions.
An object is a variable only that represents data as well as functions required for
operating data.

UNIT-1 OOPs-

Classes
7

 A class is an entity that specifies what data and functions will be included in object
of this class.
 Collection of an object that has the common attributes and methods.  A blueprint for
creating objects.
 E.g. objects representing different types of employees in an organization may
be represented by a class employee.
 It’s objects may be declared as employee obj1, obj2, obj3;
 Where employee is the class name and obj1, obj2, obj3 are the objects of class
employee.

UNIT-1 OOPs-

 2. Encapsulation- wrapping up of data and functions into a single unit.  3. Abstraction- a


paradigm that concentrates on the essential parts of the  4. Polymorphism- poly=many;
morphs=forms of a function.
 5. Data Hiding- some part of data may be public, some private and some

Features of OOPs
8

 1. Reusability of the code—use of inbuilt libraries/ functions.


problem and excludes finer details.

may be protected.
 6. Inheritance-The process of creating new classes (derived classes/ subclasses/ child
classes)from the existing classes (base classes/ super classes/ parent classes). The child classes
inherits the properties of its parent classes.

UNIT-1 OOPs-

C LANGUAGE C++ LANGUAGE polymorphism etc are supported.


4. Focus is on how to do? 4. Focus is on what to do?

Comparisons of C AND C++ 9


5. Functions communicate by 1. Focus is on real world items i.e.
1. Focus is on algorithmic approach objects.
i.esequence of steps.
2. Objects communicate. 3. Data
2. Functions communicate.
hiding, encapsulation,
3. Data hiding, polymorphism etc. are
not supported.

5. Messages communicate through


parameter passing.
objects.
UNIT-1 OOPs-

 Developed by Dennis Ritchie at AT & T Bell labs. In 1970s.

Review of C
10

 UNIX OS is itself written in C.


 Algorithm: refers to a step-by-step approach of problem solving. Each algorithm should have
only one entry and one exit point.
 Flowchart: Pictorial representation of an algorithm.
 Flowcharts are of two types:-
 A) Program Flowchart: detailed processing steps within one computer program.
 B) System Flowchart: show the procedures involved in converting data on input media to data in
output form.

UNIT-1 OOPs-

c
Init. , calc. Module
11
Notations of a flowchart

Start/stop decis
ions
I/O

call

UNIT-1 OOPs
term assembly language.(covertes machine language to assembly language)
 Q3. define the following terms with examples:-
12
 A) Interpreter  an interpreter is a computer program that directly executes instructions written in a
programming or scripting language, without requiring them previously to have been compiled into a machine
language program.
 B) compilerIn computing, a compiler is a computer program that translates computer code written in one
programming language into another language. The name "compiler" is primarily used for programs that translate
source code from a high-level programming language to a lower level language to create an executable
program.
 C) assemblerAn assembler is a program that takes basic computer instructions and converts them into a
pattern of bits that the computer's processor can use to perform its basic operations. Some people call these
instructions assembler language and others use the

 D) linker.a linker or link editor is a computer system program that takes one or more object files (generated
by a compiler or an assembler) and combines them into a single executable file, library file, or another "object"
file.
 E) loader In computer systems a loader is the part of an operating system that is responsible for loading
programs and libraries. It is one of the essential stages in the process of starting a program, as it places
programs into memory and prepares them for execution.
 https://www.geeksforgeeks.org/difference-between-linker-and-loader/

Unit-1-lect-2 13
….continued

unit-1; lect-2; -

 I (read)/O(write) operations in C++ are done using cin and cout  cin is pre-defined that
represents a standard input stream; it passes data  The file iostream.h header file defines cin
object.  The cin object uses >> operator that moves data from input device to the
14
Input /Output in C++

statements.

into the program (say from keyboard).

variable.
 >> is a redirection operator in C++ and is also called as stream extract operator as it
extracts data values from the input stream (stream means sequence of bytes).
unit-1; lect-2; -
 cin >> u;
 cin >> v;
15

 For e.g.

 cin >> w;
Or we can combine it also as follows:
cin>> u >> v >> w;
This is also called as cascading.
So, we can cascade this redirection operator without any limits. unit-1; lect-2; -

 Similarly, cout object is a standard output stream that passes data out of  cout<<“\nEnter the
values of u and v: “;
This insertion operator inserts data which is on the rhs into output stream on its lhs.
Even cout allows cascading
of the output operator, <<.
16

the program.
 For e.g.
 int u,v;
 int u,v;
 cout<< u << v;
<< is the output operator / insertion operator.

unit-1; lect-2; -
 Int *p1 = (int *) malloc(sizeof(int));
int *p1 = new int;

New and Delete operators in C++


17

 In C, we have already used malloc() and calloc() functions for memory


allocation. But malloc() returns a void pointer. So, we need to typecast it
explicitly into appropriate type of pointer. This is not required with new operator of C++.
 E.g.
 In C, we used to write,

But in C++ we can write it in a simpler way as:-

Also new operator automatically call the constructor while malloc() doesn’t. furthermore,
new operator can be overloaded also. (to study a bit later).

unit-1; lect-2; -

18

 Similarly, delete operator is used to free the memory used by the object. 
Remember, C has free() to deallocate memory.
 Just as new automatically calls the constructor, similarly delete calls the
destructor of the class whose object is being destroyed.
 E.g.
 delete a;
This statement will delete the complete array.

unit-1; lect-2; -

Basic structure of a C++ Program


19

 In general, a C++ program is divided into following sub-sections:-  Documentation/


comments section.
 Preprocessor directives/ compiler directives/C++ preprocessor.  Definition
section.
 Global declaration section.
 main() function.
 Beginning of program (‘{‘) and with local variables and executable statements.
 End of the main program (‘}’)
 User-defined functions.

unit-1; lect-2; -

20

 1. Documentation/ comments do not generate any executable statement but increases


program readability. Both // and /*….*/ can be used for comments.
 2. Preprocessor directives- #include is used as a preprocessor directive.  E.g.
 #include<iostream.h> means search for file in 1 or more std. directories.
 #include “iostream.h” means look in programmer’s own directory; if not found then
search in standard directories too.
 #define PI 3.1417 will initialize a variable PI with a value of 3.1417
 These directives cannot be placed anywhere in a program; only at the start of the
program. No spaces between # and define. Do not use = sign with #define
preprocessor directive.

unit-1; lect-2; -

 void main() means no return value whereas int main() means value is being
21

 3. Global declaration section- sometimes we need same variables in both the functions
and in the main program. In such cases we use global variables. Such variables are
declared at the start of the program, before main() program.
 Whenever there is a fight between a local and a global variable then it is the
local variable that gets the priority first.
 4. main() function- the program execution starts from the main function.
returned and thus we must have return (0); at the last.
 It is user-defined section only.

unit-1; lect-2; -
 C) special characters-- , ; & * ^ : ! + - / [ ] {} () % / \ _ and so on.

C++ character set


22

 In C++, characters are grouped as follows:-


 A) letters—from A…Z and a…z
 B) digits---from 0 to 9.

 D) White spaces– blank spaces, vertical tab, new line etc.


Tokens:
5 types of tokens in C++ are as follows:-
 Identifiers.
 Keywords
 Constants.
 Strings
 Operators and special characters.

unit-1; lect-2; -

Are reserved keywords of


 E.g. area_of_square, goto t1; where t1 is an indetifier of the type label.

C++ language like char, catch, const, private, int,


float, else, if, for, if, goto , void, private, public,

switch, this, throw, try, void,


23

 Identifiers are the names that we specify for the variables, types, functions, classes and labels in
our program.
 Identifiers includes everything like variables, labels (used with goto) etc.  It may be upto 32
characters but may vary from compiler to compiler.

Keywords:

virtual, while and so on.


Note: don’t use these keywords as a variable name.

unit-1; lect-2; -

Constants
24

 A constant is a fixed value that cannot be changed during the execution of a


program.
 E.g. integer constants, floating point constants, character constants, escape
sequences like
 \n = newline
 \t = 8 col. Position right.
 \’ = single quote.
 \” = double quote.
 \0 = null character.
 \b = backspace.
 \v = vertical tab.

unit-1; lect-2; -

 string constants- a sequence of zero or more set of characters surrounded


25

by double quotes (“ “).


 E.g.
 “this is a string”
 “ Enter the number”
 The compiler automatically places a NULL character ‘\0’ at the end of each
string so that we can easily detect the end of the string.
 Character constants- a single character may be enclosed within a single quotation marks. It is a character
constant.
 E.g. ‘9’ is a valid character constant.

unit-1; lect-2; -

Variables
 E.g. t, area, length_of_side, radius, rad etc are valid variables while area 2, len.a,
for, int are invalid variables.
26
 A variable is a storage location that contains a data value.
 All variables must be declared before using them.
 Rules for forming variable names:-
 Each variable name begins with a letter or an underscore (_).
 Variable name can have 8 characters (C++ version dependent).
 They are case sensitive. It means that uppercase and lowercase letters are treated as different.
 They cannot be reserved words.
 It cannot have a blank space, period, comma, slash or a semicolon.

unit-1; lect-2; -

Data Types in C++


27
 2 types of data types-
 A) basic data types: like int, char, float, double.
 B) derived data types: array, functions, pointers.
 C) signed and unsigned data types.
 Short, long, unsigned and signed----are type qualifiers; can be used with basic
datatypes.
 Qualifiers signed and unsigned, long and short can be used with character and
integer basic data types.
 Qualifier long is used only with double.
 void data type has no qualifier.

unit-1; lect-2; -

Size (bytes) Range 1 -128 to 127 2 -32,768 to 32,767


2 -32,768 to 32,76728 4
-2,147,483,648 to

I. Signed data type (TURBO C++ SIGNED data


types)
Type 2 48 2,147,483.647
10
signed char
-3.4E-38 to 3.4E+38
enum
short -1.7E-308 to 1.7E+308
int -3.4E-4932 to
long 3.4E+4932-32,768 to
32,767
float
double
long double

unit-1; lect-2; -

29
 A bit is the lowest unit in memory.
 A bit can be 0 or 1.
 A byte consists of 8 bits.
 It represents 1 character in the ASCII code.
 From table, we see that both short and int take 2 bytes.
 long takes twice the memory reserved for an int.
 double takes twice the float / long data type.
 long double requires higher memory than the double data type. unit-1; lect-2; -

 E.g. an unsigned int can be twice as large as the signed int. (see table). Type Size (bytes)
Range
unsigned char 1 0 to 255 unsigned short 2 0 to 65,535 unsigned long 4 0 to 4,294,967,295

II. Unsigned data types (TURBO C++


30
bool 1 bit 0 or 1

UNSIGNED data types) and BOOL type


 The range of unsigned data type is higher as these data types are all positive.
 Unsigned data types have more requirements as the leftmost bit (MSB) is
reserved for the sign.
unit-1; lect-2; -
 x = true;
 int sum = true + 2*6 –false = 12;
 wchar_t type: we know that char type variable takes 1 byte=8 bits. But some
require more than 8 bits. wchar_t data type is typically 16-bits wide.
 Standard C++ iostream class library defines wout object.
31

 E.g.
 bool x, y;

 y = false;

foreign language character sets have more than 256 chars. To solve this problem, C++ provides wchar_t type to
accommodate character sets that

unit-1; lect-2; -
These assignment statements work from right to left i.e. the value of rhs is assigned and

Expressions and Assignment statements32

 An expression is a combination of constants, variables, function calls and


operators that when evaluated returns a value.
 E.g.
 count + 5;
 numb * 10;
 An assignment statement is used to assign a value.
 E.g. count = count + sum;
 numb = numb * 10;

stored in lhs variable.

unit-1; lect-2; -

UNIT-1, LECTURE-4,5 33
Continued….
unit-1, lect4,5-

 E.g. in an expression (a+b) we say ‘+’ is an operator while a and ‘b’ are

Operators
34
 An operator is a symbol that causes the compiler to take action.

operands.
 Operators inherited from C lang. are as follows:-
 Arithmetic operators.
 Unary operators.
 Assignment operators.
 Bit operators.
 Relational operators.
 Logical operators.
 Boolean operators.
 Conditional operators.

unit-1, lect4,5-

 << stream output operator.


 >> stream input operator.
 endl just like newline
 :: scope resolution operator
 new memory allocation operator
 delete memory release operator

Operators introduced by C++ 35


 setw field width operator

unit-1, lect4,5-

Unary operators Meaning Unary plus Indirection


Unary minus/ arithmetic negation36
operator
Size of operator

Arithmetic operators-Unary and Binary operators


+ Mod (remainder) Complement
- operators Adess operator

* Logical NOT

sizeof
%
~
&
!

unit-1, lect4,5-
 e.g. int x = 2, y=4;
Eg2. – (arithmetic negation/unary minus): this operator turns positive no. into a int x = 10;

37

 Unary operators take one operand and are associated from right to left.
 E.g1 ! (logical NOT)

 if(!(x < y))


here, expression inside innermost parenthesis is true(1). But !(logical NOT)
makes it false (0).

negative no.

x = -x;
Here, the value of x becomes -10.
unit-1, lect4,5-
 Eg. a + (b – c);
 & (adess operator): gives adess of an operand. E.g. m = &n[10]; It assigns the adess of pointer. E.g. int *point, x;
 x = *point; // assigns int value being pointed by *point to a variable, x.
38
 + (unary plus) : used to group the enclosed operations when it precedes the
operation.

 ~ (complement operator): it performs bitwise operations, changes 0s to 1s and vice


versa.
 Eg. X = 10101010 then ~x = 01010101

the 11th element to variable, m.

 * (indirection operator): it accesses the value of an operand indirectly through a unit-1, lect4,5-

 In C, sizeof(‘c’) is same as sizeof(int). In C++, ‘c’ is not promoted to int and  Like C, in C++ also we have ++
(increment) and decrement (- -) operators that
inre/decre variable’s value by 1. i.e ++count and - - count; (called as pre-increment)
while count++ and count- - (called as
post-increment).
 E.g. count = count++; //assign value of count to count variable on left and then
39

 sizeof() operator: gives storage in bytes.

sizeof(‘c’) will be treated as sizeof(char).


 Increment and decrement unary operators:

//incre.
 count = ++count; //first increment value of count and then assign it.
unit-1, lect4,5-

Meaning
Addition assignment
40 Subtraction assignment Multiplication assignment

Division assignment
Modulus assignment

Arithmetic assignment operators

 E.g. counter = counter + 50; can be written as counter += 50;


Symbol
+=
-=
*=
/=
%=

unit-1, lect4,5-

Meaning
Greater than
41 Less than Equal to

Not equal to
Less than equal to

Relational operators
 Are used to compare two expressions.
Symbol Greater than equal to
>
<
==
!=
<=
>=

unit-1, lect4,5-
Meaning
Logical operators Logical AND

Logical OR42
Symbol
&& Logical Not
||
!=

unit-1, lect4,5-

on expressions.
Meaning
Bitwise &
Bitwise exclusive OR (XOR)
Bitwise right shift
Bitwise left shift

Bitwise operators
43
 These operators perform operations on bit level while logical operators work

Symbol 1s complement
& Bitwise OR

|
^
>>
<<
~
unit-1, lect4,5-

BA&B
00
44 1 0 0 0

11

Bitwise AND operator (&)


A
0
0
1
1

unit-1, lect4,5-

BA^B
00
1 145 1 0

Bitwise XOR operator (^)


A 0
0 1
0
1
1

unit-1, lect4,5-

A ~A 0 1
10

Ones (1s) complement operator 46

unit-1, lect4,5-
Right shift operator (>>) and Left shift
47

operator (<<)
 E.g. if numb1 = 154 then numb1 >> 4 yields 5 (in decimals) or (00000101) in
binary.
 E.g.2 if numb1 = 154 then numb1 << 4 yields 224 (in decimals) or (11100000) in
binary.
 During shifting, zeros are inserted while during rotations these zeros are not
inserted.

unit-1, lect4,5-
 z = (x++, y--, x+y);
 cout << z; }
 Here, firstly x++ is evaluated then y- - and finally x+y. As x+y is the rightmost expression, so result of x+y is
assigned to z. Final output is 40.

Comma operator
48

 #include<iostream.h>
 void main()
{
 int x, y, z;
 x=y=20;
unit-1, lect4,5-

The sizeof operator


 E.g. sizeof(int); // gives size of the data type (int) as 2 bytes  sizeof () is used to find out the length
of secondary data types like arrays, structures, classes etc when their sizes are unknown to the programmer.

49
 sizeof(long); // gives size of the data type (long) as 4 bytes  sizeof(char); // gives size of the
data type (char) as 1 byte.
 sizeof(char); // gives size of the data type (char) as 1 byte.
 Application:

unit-1, lect4,5-
Multiplication x * y 60 Division x / y 2 Modulus x % y 2 Addition x + y 17 Binary
Operators
50 Subtraction x – y 7
 They take two operands and are associated from left to right.  They may be
arithmetic operators as follows:-  Say, x = 12, y=5;

Operator Meaning Example Result


*
/
%
+
-
unit-1, lect4,5-
 w = (u > v ? u : v);
 cout << w; //gives 30

Ternary operator/ conditional


51

operators
 It takes three operands, hence is named as ternary.
 Syntax:
 expression1? expression2 : expression3;
 It means that if expression1 is true then the expression2 is evaluated else expression3 is
evaluated.
 E.g. u = 20;
 v= 30;

unit-1, lect4,5-
 type_name (expression);
 Pay = (float) total; //C type
 Pay = float (total); // C++ type

The Cast Operator in C++ 52

 Also called as coercion i.e. to type cast/ coerce the data to another type of data.
This is done with the help of cast operator.
 The case operator casts the data to any type given in parentheses preceding the
original data type.
 Syntax:

 E.g.

unit-1, lect4,5-

 Q1. Write a C++ program to find the roots of a given quaatic equation.

Programs for lab.


53
 Q2. write a C++ program to find the GCD of two numbers.

unit-1, lect4,5-
Unit-1, lect-6,7 Oops using C++ by
 int main( )
 cha = 97 a  cha + 1= 98 b
 cout<<“cha+1= “<<int (cha)<<“ “<<cha<<endl;
 cout<<“uppercase shift(cha-32)= “<<int (cha)<<“
 cha + 24 = 122 z
 cout<<“lowercase shift(cha+32)= “<<int (cha)<<“
 cout<<“cha + 24= “ <<int (cha)<<“ “ <<cha <<endl;

Example to show working of ASCII codes in C++55


 #include<iostream.h>

 {  char cha = ‘a’;

 OUTPUTs:
 cout<<“cha = “ <<(int)cha<<“ “ <<cha <<endl;
 cha++;
 uppercase shift(cha-32)= 66 B
 cha = cha – 32;  cha = cha – 32;
 cha = cha + 24;

“<<cha<<endl;
 return 0; }
 cha = cha + 32;
 uppercase shift(cha-32)= 66 B  lowercase shift(cha+32)= 98b
“<<cha<<endl;
 The character ‘a’ is stored in variable cha.
 The value of cha is unary incremented which increases its ASCII code from
97 to 98. The no. 98

 Subtraction of 32 from cha reduces the ASCII code to


is the ASCII code for ‘b’. So, it displays it.

66 andtheno. 66is  This shows that lowercase character can be


the ASCII code for uppercase ‘B’.

converted into uppercasecharacter by subtracting 32 from the value of character and

uppercase
character into lowercase character by adding 32 to the value of character. The
difference between the two types of characters is constant 32.

Explanation of outputs…
56

 Subtraction of 32 from cha reduces the ASCII code to 66 andtheno. 66is

Control structures in C++ 57

 1. if…..else statement
 If (test-condition)
{
 statement(s);
}
 else
{
 Statement(s);

}
58Default: str = “many”;
The switch statement

 Switch(x) {
 Case 0: str=“none”; break;
 Case 1:
 Str = “single”; break;

}
 Switch cannot handle ranges like if can.

 It cannot have float constant, a variable, an expression, a string or any other object in case
statement.

 Character constant may be used.

Loops in C++ 59

 1. while loop:
 Syntax:
 while (condition)
{
 statements;
}
 Eg.1 while (!false) { …..stmts}
 E.g.2 while (number < 5) {…}
e.g. do
60 } while (b <=3);
 2. do while loop:  Syntax:  do  { 
statements; } while (test-condition);

{
b = 1;
}
e.g. for(int i=2; i< n; i++,j--) //compound statement in for-loops can be used.

61
 3. for-loop:  Syntax:  for (expr1; boolexpre; expr2)
 {  Statements;

….

}
 1. break statement: when a break statement is executed inside a loop, itskips the remaining
statements of that loop and the control is immediately
transferred outside the loop.  E.g. when a

break statement appears inside a loop or in a switchcontrol to the statement immediately following

that loop or switch So, it does an early exit from the loop or a switch statement, wherever it is

When multiple statements are nested then the control transfers to its
immediate outer level (it

bypasses the inner loop’s logic).

Other statements
62
statement, it terminates the execution at that point andtransfersthestatement, it terminates the

execution at that point andtransfersthe

statement.

used.
 ; //null statement

63
 2. continue statement- it is used within the loops to end the execution of the current
iteration and proceed to the next iteration.
 3. empty statement- also known as a null statement that do nothing. E.g. (for
int i=0; i<100; i++)
 (for int i=0; i<100; i++)
{

These statements are used to introduce some delays in the program.

The sentinel value


64

 A value that is chosen to test for some conditions.


 E.g.
 while (result != -1)
{
 result = result + 20;
}
Here, the value of -1 is chosen for sentinel as it is not possible to have a negative result
now.
 int price;
 for(int width = 11; width <=20; width++) {

Exercise Questions
65

 Q1. give the output of the following program:

 for(int length =5; length <=25; length +=5) {


 for(int length =5; length <=25; length +=5) {
 price = width * length * 19;
 cout<<“ “ <<price;

cout<< “ “;

}
 Width length
 11 5
12 5
66

 10
 15
 20
 25 (this completes the printing of first row)

10
15
20
25 (this completes the printing of first row)
Similarly, for width = 13, 14….till 20.

67C = 5/9 (F – 32).


 D) reverse a number and also check whether it is a palinome or not.

Some programs for practice…

 Write C++ programs to-


 A) add each digit of a number.
 B) find factorial of a number.
 C) convert Fahrenheit temperature to its centigrade using formula:-  E) generate
Fibonacci series till n.

 Soln 1: while (num > 0)


 r = num % 10;
 num = num /10;
 n! = n * (n-1)! = n * (n-1)! = n * (n-1) * (n – 2) !
68

{

 sum = sum + r;

}

 cout<<sum;
 B) 0! = 1, 1! = 1, 2! = 2 *1, 3! = 3 *2 *1, 4! = 4 * 3 * 2 * 1. so,
c- -;
69r = num % 10;
num = num /10;
fact = 1;
while (c > 0)
{
fact = fact * c;

}
d) b = num;
while (num > 0) { s = (s * 10) + r;

}
if (b == s) cout<<“It is a palinome”; else
cout<<“It is not a palinome”; }
Unit1-lect-8 Oops using C++ by

Functions in C++
71

 Functions are small modules that are written to accomplish some task.  They help us
in achieving modularity.
 But under-modularity and over-modularity should not be done.  The
encapsulations of code are called as functions.
 We have used several in-built functions like sqrt( ), abs( ) etc.
 Also programmers can write their own programs that are called as user
defined functions.
unit-1-functions-

Advantages of functions
72

 1. As they are smaller in size, so they are easy to understand.


 2. They are easy to debug during testing.
 3. They save memory as they are stored in one place only even though they may be executed
many a times in program.
 4. They help in achieving modularity too.
unit-1-functions-

Function definition
73

 A function definition has a function header and a function body.  The function
header has three parts:-
 A function name.
 A parameter list.
 A return type.
Each function is represented by its name. the function operates on its
parameters/arguments, if given. Parameters are separated by commas and are enclosed
within braces. The result of a function is reflected back through its return value, also
called as function return types.

unit-1-functions-

Working of functions 74
 f1 ( );//function called by main( )
 return;

 …….  }
 void main( )  {  …………. 
………….
 f1( )  {  …………… ……………
}

unit-1-functions-
 return_type function_name(list_of_parameters)
int add(int u, int v);

Function declaration/ Function


75

prototype
 Syntax:

Examples:
void get_data(void);

double test_marks(double u, double v, double w);


unit-1-functions-
int area(int r, int p);

Function call
76

 Syntax:
 function_name(list_of_arguments);
e.g.
display( );
unit-1-functions-

 2. functions with arguments and no return value. E. g. void power (int , int);
 3. functions with no arguments but return value. E.g. int add (void);

Types of Functions
77

 1. functions with no arguments and no returns. E.g. message( );


 4. functions with arguments and return value. E.g. int swap(int x, int y);  4. functions with
arguments and return value. E.g. int swap(int x, int y);

unit-1-functions-

b) Sending adesses of the arguments.

Parameter passing methods in C++78


 I. Pass by Value/ call by value.
 II. Pass by Reference / call by reference.
Ultimate aim is to pass data to other functions. There are 2 approaches :-a)
Sending values of the arguments.

Let us study these methods now.

unit-1-functions-

 int a = 10; swapv (int x, int y)


 int b = 20;  swapv (a, b); 79
a = 10 b = 20 // change not reflected
 int t;  x = y;  y = t; x = 20 y = 10 //swapped in swapv( ) //back in main ( )

I. Pass by Value/ call by Value  void main( )

{ {

 t = x;  t = x;

 cout<<a << b;  }
 cout<<x << y;  }

unit-1-functions-

 int b = 20; swapr (int *x, int *y)


 int a = 10;  swapr (&a, &b);
 int t;

II. Pass by Reference/ call by reference80

 void main( )
 *y = t;  cout<<x << y;  } x = 20 y = 10
{
{ //swapped in swapv( )
a = 20 b = 10 // change is reflected
 t = *x;  *x = *y;
//back in main ( )
 *x = *y;
 cout<<a << b;  }

unit-1-functions-

You might also like