KEMBAR78
C++Object oriented Programming with C++.pptx
Programming with C++
A presentation by Pratibha Pai
Department of PHYSICS
SIES College, Sion(west)
UNIT 4
ELECTRONIC INSTRUMENTATION
SEMESTER 6
T Y B.Sc(2016-2017)
2
Reference books
1. E.Balaguruswamy
2. Tony Gaddis
3. D. Ravichandran
4. Yashwant Kanitkar
Slides by Mrs. Pai for Sem 6 (2016-2017)
Slides by Mrs. Pai for Sem 6 (2016-2017) 3
INTRODUCTION
We need a computer/software to study C++
.
• A computer is an electronic machine.
• It is specifically designed to follow instructions.
• It can be programmed.
• It is able to do the only jobs that programs tell it
to do..
Slides by Mrs. Pai for Sem 6 (2016-2017) 4
What is C++
?
• C++
is an Object-Oriented Programming (OOP)
language.
• It was developed by Bjarne Stroustrup at AT
and T Bell laboratories in Murray Hill, USA in
1985.
• C ++
is a high level language.
• C ++
is studied directly using programs for
better understanding.
Slides by Mrs. Pai for Sem 6 (2016-2017) 5
Data types
• integer(int)
• floating point numbers(float)
• character(char)
• String
• bool
Slides by Mrs. Pai for Sem 6 (2016-2017) 6
Special Names
 < > → opening and closing brackets
 # → pound sign (hash)
 { } → opening and closing braces
 “ ”→ opening & closing quotation marks
 ( ) → opening and closing parentheses
 // → double slash
 ; → semi colon, statement terminator.
Slides by Mrs. Pai for Sem 6 (2016-2017) 7
C++
program :1
1. // A simple program for understanding.
2. #include<iostream.h>
3. #include<conio.h>
4.void main(void)
5. {
6. clrscr();
7. cout<<“Writing program is interesting and fun.” << endl;
8. /*endl means end of line*/
9. cout<<“ Hello, listen here !n”;
10. cout<<“tWe should study hard this semester”;
11. cout<<“n I am just thinking, It is easy yaar!”;
12. getch();
13. }
<< is insertion operator
Slides by Mrs. Pai for Sem 6 (2016-2017) 8
C++ program :2
• // A very simple program with a variable.
• #include<iostream.h>
• #include<conio.h>
• void main (void)
• {
• clrscr( );
• int i; //variable declaration statement
• cout<< “Input value of i”<<endl;
• //endl means end of line
• cin>>i; //input statement
• cout<<“The value of i is ”<< i<< endl;
• getch( );
• }
>> is an extraction operator
Slides by Mrs. Pai for Sem 6 (2016-2017) 9
C++ program :3
/* program to learn cascading of input operator and output operator
finding sum and difference of 2 integers */
void main( )
{
int n1, n2, SUM, Diff;
cout<< “Enter two positive integers”;
cin>>n1>>n2;
//cascading input operator or writing multiple input statement.
SUM = n1 + n2; Diff = n1 - n2;
// assignment statements ..
//Expression is a Combination of constants & variables together with operators.
//look here how to cascade output operator..
cout<<“n The sum of 2 integers ” <<n1<< “and ” <<n2<<“is = ” <<SUM;
cout<<“n The difference is = ” << Diff;
getch( );
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 10
Summary: Comments
• Lines beginning with // indicate that remainder of that line is a
comment. There is no closing.
• Single line comments.
• If the comment goes to the next line, // is used again.
• A comment may start anywhere in the line and in the program.
• Lines beginning with /* and ending with */ are multiple line
comments used in C.
Slides by Mrs. Pai for Sem 6 (2016-2017) 11
Comments…..
• Improves program readability.
• Help other people to read & understand programs.
• Not valid C++ statements, not executed.
• Ignored by the compiler.
• Do not cause any machine language object code to
be generated.
• So, we can write anything: date, name, reference,
meaning of variable introduced etc...
Slides by Mrs. Pai for Sem 6 (2016-2017) 12
#include <iostream.h>
• pre processor directive.
• #include preprocessor command causes contents of named file to be inserted where #include
command appears.
• iostream.h is a header file to be included at the top /head of program.
• Lines beginning with # are processed by the preprocessor before compilation.
• Specific line tells the preprocessor to include contents of input/output stream header file
<iostream.h>
• Any program that outputs data to the screen or inputs data from keyboard must include this file.
• cin & cout are not a part of core language.
• part of input-output stream library.
Slides by Mrs. Pai for Sem 6 (2016-2017) 13
void main()
• Part of every C++ program.
• Parenthesis after main indicates that main is a program building block
called a function.
• C++ program is made up of one or more functions, one of which must be
necessarily main().
• Execution of every C++ program begins at main() , even if main() is not the
first function.
• Keyword void to the left indicates that it does not return any value.
• The function main begins at Left brace { and ends at Right brace }
Slides by Mrs. Pai for Sem 6 (2016-2017) 14
cout << “All is well.” ;
• Print a string of characters contained within double quotation marks.
• Entire line is called a C++ statement.
• Every statement must end with a semi colon (statement terminator)
• On execution , a stream of characters is sent to standard output stream
object normally connected to the screen.
• Operator << is stream insertion operator. (also called ‘put to’ operator)
• Value to right of the operator(operand) is inserted in output stream.
• The cout object sends data to standard output display device.
Slides by Mrs. Pai for Sem 6 (2016-2017) 15
cin>>n1>>n2;
• Operator >>is stream extraction operator.
• Also called ‘get from’ operator.
cin>>n1;
• Takes the value of the variable /identifier n1 at
the time of execution of the program.
cin>>n1>>n2;
• Takes the value of the variables n1 and n2.
Slides by Mrs. Pai for Sem 6 (2016-2017) 16
Complete C++ program
//We are finding area of a rectangle
# include<iostream.h>
# include<conio.h>
void main(void)
{
int len, wid,area; //using CGS system
cout<<“Enter length of the rectangle in cm:n”;
cin>>len;
cout<<“Enter the breadth of the rectangle in cm : n”;
cin>>wid;
area =len * wid; // * is an arithmetic operator
cout<<“area of the given rectangle = ”<<area<<“sq.cm”;
getch();
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 17
Note
(i) There are no line numbers.
(ii) C++ is case-sensitive.
(iii) C++ is space ignorant.
(iv) All key words are in lower case.
(v) Identifiers cannot have spaces in between.
(vi) .cpp files are compiled.
(vii) Header files are included.
(viii) Multiple files need to be put in a project. (.cpp
files)
Slides by Mrs. Pai for Sem 6 (2016-2017) 18
7 phases from Source code…
Object code….. Executable code
• Source code---Edit
• preprocessor
• Modified source code
• compiler
• Object code
• Linker
• Executable code
Slides by Mrs. Pai for Sem 6 (2016-2017) 19
The smallest individual units in a program are known as tokens.
They are
• key words
• identifiers (programmer- defined symbols)
• operators
• constants and
• strings.
TOKENS- Language elements
Slides by Mrs. Pai for Sem 6 (2016-2017) 20
KEY WORDS: written in lower case
• These are also known as reserved words.
• They have a special meaning. They cannot be used for any other purpose than what
they are designed for.
List of key words in alphabetical order ……a quick glance
• asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, extern, export, false, float,
for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid,
typename, union, unsigned, using, virtual, void, volatile, wchar_t, while.
Slides by Mrs. Pai for Sem 6 (2016-2017) 21
Identifiers : Rules
• Series of characters consisting of letters, digits & underscore that does not begin
with digit.
• Case sensitive – uppercase & lowercase letters are different.
• Keywords or reserved words cannot be used as identifiers.
• Blank spaces letters cannot be a part of an identifier.
• Special characters are also not allowed….#, $, &, !, @, , /,
• Allows identifiers of any length.
• System and/or C++ implementation can impose some restrictions on length of
identifier.
Slides by Mrs. Pai for Sem 6 (2016-2017) 22
Identifiers : valid/ invalid
Identifier Valid / Invalid Reason
5axbycz Invalid Cannot start with digit
basic salary invalid Special character (space)
not allowed
#pay Invalid Special character (hash)
not allowed
counter Valid
default invalid C++ key or reserved word.
_perimeter Valid
S.I.E.S invalid Dot not allowed
Slides by Mrs. Pai for Sem 6 (2016-2017) 23
Operators : categories
• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Bitwise operators
• Others
Slides by Mrs. Pai for Sem 6 (2016-2017) 24
operators :operate on one or more operands
• Arithmetic---(+ , - , * , /, %)
• Logical --- AND(&&), OR(||), NOT(!)
• Relational ---(<, <=, >, >=, ==, !=)
o Ternary
o Binary depending on number of operands
o Unary
Slides by Mrs. Pai for Sem 6 (2016-2017) 25
Binary Arithmetic
Operation operator Algebraic expression C++ expression
Addition + m + 7 m + 7
Subtraction - a – c a – c
Multiplication
*
mn m * n
Division / x/y x / y
Remainder % r mod s r % s
Slides by Mrs. Pai for Sem 6 (2016-2017) 26
Binary Arithmetic
• % operator requires that both operands be
integers & second operand be non-zero.
• Result of division operation is truncated
quotient when both operands are integer
quantities.
• Division operator requires second operand
be non-zero.
Slides by Mrs. Pai for Sem 6 (2016-2017) 27
Binary Arithmetic
• The % operator divides the left operand by
the right operand, & the result is the
remainder after integer division.
• / operator denotes integer division if both
arguments are integers & floating point
division otherwise.
Slides by Mrs. Pai for Sem 6 (2016-2017) 28
Binary Arithmetic
• float a = 12.0 , b= 9.0;
a + b = 21.0
a – b = 3.0
a * b = 108.0
a / b = 1.33
a % b : not applicable
as operator requires
integer operands
For modulo operation the
sign of the result is always
the sign of the first operand.
e.g.
-14 % 3 = -2
-14 % -3 = -2
14 % -3 = 2
Slides by Mrs. Pai for Sem 6 (2016-2017) 29
Examples : unary, binary, ternary
• -x, -m….
• A+b, n* m;
• expression ? expression : expression;
x=10 ? y=3 : y=0;
Slides by Mrs. Pai for Sem 6 (2016-2017) 30
Examples
• (7 == 5) // evaluates to false.
• (5 > 4) // evaluates to true.
• (3 != 2) // evaluates to true.
• (6 >= 6) // evaluates to true.
• (5 < 5) // evaluates to false.
Slides by Mrs. Pai for Sem 6 (2016-2017) 31
Logical operators :&&, ||, !
Syntax: expression1 && expression2
•expression1 is evaluated.(left operand)
• If expression1 is false , expression2 is not evaluated.
• If expression1 is true , the value of the second expression is the final value.
Syntax: exp1 || exp2
• exp1 is evaluated.
• If exp1 is true , exp2 is not evaluated.
• If exp1 is false , the value of the second expression is the final value.
Syntax: ! exp
•unary operator
•exp is evaluated.
• If exp is true , ! exp is false and If exp is false, ! exp is true
Slides by Mrs. Pai for Sem 6 (2016-2017) 32
Operator --hierarchy
Arithmetic Relational Logical
unary negation <, <=, >, >= ! NOT
*, /, % = =, != && AND
+, - || OR
left to right
Operators ---continued
• increment and decrement operators
++ and  
 post fix mode e.g a++, a--
 pre fix mode e.g ++x, --x
a=5; a=5;
X= a++; x=++a;
o/p : X=5 o/p: x=6
• Prefix does the addition/subtraction first.
• Postfix evaluates to the old value of the variable first
Slides by Mrs. Pai for Sem 6 (2016-2017) 33
Slides by Mrs. Pai for Sem 6 (2016-2017) 34
Assignment 1
What is the o/p?
1. int a = 2 , b = 5 ;
int c = a * b++ ; //postfix
cout << a << “ “ << b << “ “ << c ;
Output : 2 6 10
2.int c = a * ++ b ; //prefix
cout << a << “ “ << b << “ “ << c ;
Output : 2 6 12
Slides by Mrs. Pai for Sem 6 (2016-2017) 35
Assignment 2
• What is the output of the following program?
#include<iostream.h>
int main() {
int a = 5 ; o/p
cout << “ ” << a << endl ; 5
cout << “ ” << (a++) << endl ; 5
cout << “ ” << (++a) << endl ; 7
return 0 ; }
Slides by Mrs. Pai for Sem 6 (2016-2017) 36
Bitwise operators
&, |, ^, ~, <<, >>
operator asm equivalent description
& AND Bitwise AND
| OR Bitwise Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT
Unary complement
(bit inversion)
<< SHL Shift Left
>> SHR Shift Right
Slides by Mrs. Pai for Sem 6 (2016-2017) 37
Escape sequence
• They give us the ability to exercise greater control
over the way information is output by the program.
• An escape sequence always starts with a back slash
() and is followed by one or more control characters.
Note: There is no space between the back slash
and the control character.
Slides by Mrs. Pai for Sem 6 (2016-2017) 38
Escape sequence: examples
• n
• t
• a
• b
• 
• ’
• ”
• r
• cursor to go to next line for printing.
• cursor to go to the next tab stop.
• the computer to beep.
• cursor to move left by one position.
• backslash to be printed.
• single quotation mark to be printed.
• double quotation mark to be printed.
• cursor to go to the beginning of the current
line.
Slides by Mrs. Pai for Sem 6 (2016-2017) 39
Expressions
• Combination of constants & variables together
with operators.
• Balanced parenthesis may be used in
combining constants & variables with
operators.
• Constants & variables by themselves are also
considered expressions.
Slides by Mrs. Pai for Sem 6 (2016-2017) 40
Expressions: Constant and algebraic
• An expression that involves only constants is
called constant expression.
5 + 2 = 7
Operands
operator
Value of result
Slides by Mrs. Pai for Sem 6 (2016-2017) 41
No exponentiation operator
• Raising a number to power requires use of
library function pow
area = pow(4,2) ; //o/p area= 16
• raises first argument to the power of second
argument.
• Need to include math.h header file
Slides by Mrs. Pai for Sem 6 (2016-2017) 42
Assignment statement(operator)
Syntax: variable = expression
• Assign a value to a variable.
• Expression may be a single constant or
complex combination of variables , operators
& constants.
e.g: x=5; p=q; m=n+4; a= (5+7)* 3/4 ;
Slides by Mrs. Pai for Sem 6 (2016-2017) 43
Compound assignment operators
• There are Five compound arithmetic
assignment operators.
Operator Example Meaning/equivalence
+= a +=5; a = a + 5;
-= b -=8; b = b – 8;
*= c *= 7; c = c * 7;
/= d /=10; d= d /10;
%= e %= 100; e= e % 100;
Slides by Mrs. Pai for Sem 6 (2016-2017) 44
Other operators
• Ternary…. ? : (if-then-else type)
• Increment/decrement …. ++ /--
• memory allocation & deallocat ion new
delete
• Scope resolution …. ::
• size of the variable in bytes… sizeof(variable)
• Comma operator…… , (separator in declaration)
; ( separator in loops)
• Type cast … see next slide please
Slides by Mrs. Pai for Sem 6 (2016-2017) 45
Type cast opeartor
• What is type casting?
It is a technique to forcefully convert one data
type of variable to another data type.
• Syntax: ( cast type) variable or expression
OR
cast type(variable or expression )
e.g: (float)month or float(month)
Slides by Mrs. Pai for Sem 6 (2016-2017) 46
#define pi 3.14 OR
const float pi=3.14
//to find area of a circle
#define PI 3.14
#include<iomanip.h>
void main (void)
{ float r, area; // r is radius
cout<<“Problem: To print Area of the circlen";
cout<<"Enter the radiusn";
cin>>r;
area= PI * r * r;
cout<<"n The area of the circle of radius "<< r<<" is = " <<
setprecision(2)<< area;
getch( );
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 47
What is the program for?
{ int a, b, t; // t is temporary variable.
cout<<” input 2 integers one after another n”<<endl;
cin>>a>>b;
cout<< “ n The numbers are a= “<< a<<” and b= “<< b;
cout<< endl;
cout<< endl;
t = a;
a = b;
b = t;
cout<<“a= “<< a << “ “b= “<<b;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 48
Control – flow statements
and their need
• A program is usually not limited to a linear sequence of
instructions.
• It may bifurcate, repeat code or take decisions during its
process.
• So, C++
provides control structures.
Let us study STRUCTURED PROGRAMMING.
Slides by Mrs. Pai for Sem 6 (2016-2017) 49
All program processing can be coded by using only
3 logic structures.
THEY ARE:
•Sequence structure(straight line)
•Selection structure(branching)
•Loop structure(iteration or repetition)
These structures are implemented using one-entry,
one -exit concept. The approach of using one or
more of the above structures is known as
structured programming.
Slides by Mrs. Pai for Sem 6 (2016-2017) 50
Control statements & Loops
• if
• if – else
• if – else if
• for
• while
• do – while
• switch - case
• break
• continue
Slides by Mrs. Pai for Sem 6 (2016-2017) 51
1. The if statement
• This is used to execute an instruction or a
block of instructions only if a certain condition
is fulfilled.
• The general format is
if (condition)
statement ; //action
Slides by Mrs. Pai for Sem 6 (2016-2017) 52
Program with if
//to check if a no. is even
#include<iostream.h>
void main()
{ int n;
cout<<“Enter the number to be checked”;
cin>>n;
if(n %2 = = 0)
cout<<“n The entered number “<<n<<“ is even”;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 53
Execution of a C++
Program
• Enter the program
• Save the program as .cpp extension
• Manually go through and edit, save again(F2)
• Compile ( either from menu or Alt + F9)
• Errors are shown, understand, edit and save.
• Once you debugged, success message is seen.
• Execute or run the program ( either from menu
or Ctrl + F9)
• View the o/p.
Slides by Mrs. Pai for Sem 6 (2016-2017) 54
Formatting output … this is an art
---- using----
• n printing in new line
• endl printing in new line
• t printing after one tab space
• “ ” printing with space shown
• ; printing without space
#include<iomanip.h>
• setprecision(n)  printing upto n places after the decimal point
• setbase( base)  printing the value in the base shown 10/16/2/8
• setw(n)  to keep n character places on the o/p for a
variable to consume
Slides by Mrs. Pai for Sem 6 (2016-2017) 55
Understanding
• setprecision(n)
float a,b,c;
a=5,b=3; c=a/b;
cout<<setprecision(1)<<c; 1.7
cout<<setprecision(2)<<c; 1.67
cout<<setprecision(3)<<c; 1.667
• setbase( base)
int value = 10;
cout<< “value in decimal=”<<setbase(10)<<value; 10
cout<< “value in hex=”<<setbase(16)<<value; a
cout<< “value in octal=”<<setbase(8)<<value; 12
• setw(n)
int x=100,y=500;
cout << setw(5) << x << setw(5) << y;
1 0 0 5 0 0
Slides by Mrs. Pai for Sem 6 (2016-2017) 56
2. The if – else statement
• The general format is
if (condition)
{
statement 1 ; //action1
}
else
{
statement 2 ; //action2
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 57
Program 1 with if -else
//to check if a no. is even or odd
void main()
{ int num;
cout<<“Enter the number to be checked”;
cin>>num;
if(num %2 = = 0)
cout<<“n The entered number “<<num<<“ is even”;
else
cout<<“n The entered number “<<num<<“ is odd”;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 58
Program 2 with if -else
//to check which number is bigger
void main()
{ int num1, num2;
cout<<“Enter the 2 numbers to be checked”;
cin>>num1>> num2;
if(num1 > num2)
cout<<“n ”<< num1<< “ is bigger than ”<<num2;
else
cout<<“n”<< num2 <<“ is bigger than ” <<num1;
}
3. The if – else if statement
if (expression)
statement 1 ;
else if (expression)
statement 2 ;
else if
(expression)
statement 3 ;
else
statement 4;
if (total>75)
cout<<“distinction”;
else
{ if (total>60)
cout<<“First”;
else
{ if (total>40)
cout<<“Second”;
else
cout<<“Pass”;
}
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 59
Slides by Mrs. Pai for Sem 6 (2016-2017) 60
4. The for loop
The stepwise working is as follows:
for (n=1; n<6 ; n++ )
{
statement1 ;
}
statement2;
Slides by Mrs. Pai for Sem 6 (2016-2017) 61
Program1 with for
//sum of integers 5 to 20
{ clrscr();
int Sum=0;
//Declaration of variable at the place of use.
for( int m =5 ; m<= 20 ; m ++)
Sum += m ; // Sum = Sum + m;
cout<< “Sum of the numbers = “ << Sum ;
getch();
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 62
Program2 with for
// To write the multiplication table of an integer.
{
int t ; // t is the number whose table is required
int count;
cout<<" Table of which integer do you wish to try?n";
cin>>t ;
for(count=1; count<= t ;count++)
cout<<“t”<<t<<“ * ”<<count<<“ =”<<t *count <<“n”;
getch( );
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 63
5. The while loop
• The general format is as follows.
while( condition or expression)
{ ------------
----------statements;
} True
False
Slides by Mrs. Pai for Sem 6 (2016-2017) 64
Program with while
//sum of integers 5 to 20
{ clrscr();
int m =5, Sum=0;
while (m<= 20)
{ Sum += m ; // Sum = Sum + m;
m ++;
}
cout<< “Sum of integers 5 to 20 = “ << Sum ;
getch();
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 65
6. The do –while loop
The general format is
do
{----------
----------
---------- statements;
}
while(expression);
this ; is important.
Slides by Mrs. Pai for Sem 6 (2016-2017) 66
Program with do -while
//The program should repeat as many times as the user requires.
void main( )
{ int a1, a2, a3, tot, n ; // n for Roll No., a1, a2, a3 for attendance
char choice; // choice is any letter from A to Z or a to z
n = 0;
do
{
n++ ;
cout<<"Enter the attendance in 3 months:n";
cin>>a1>>a2>>a3;
tot = a1+ a2 + a3 ;
cout<<"n The total attendance for roll number " << n<< " : "<< tot;
cout<<"n Do you wish to repeat this for another student? Say Y or Nn";
cin>> choice;
}
while(choice = ='y' || choice = ='Y '); // single quotes for character constant
getch( );
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 67
7. The switch-case statement
switch(variable / expression)
{case constant 1: // case ‘x’ :
block of instructions 1
break;
case constant 2:
block of instructions 2
break;
:
:
default:
block of instructions
}
• First, the expression is evaluated.
• it is checked for constant1.
• If it is, then block of instructions 1
is executed until the ‘break’ word
is encountered
• Finally it jumps to the end of
switch selective structure.
• If not constant 1, it is checked for
constant 2 and same procedure
as above.
Slides by Mrs. Pai for Sem 6 (2016-2017) 68
8. break
• int i=0;
• while(i++<20)
• {
• cout<<i<<endl;
• if(i = = 5)
• // program stops after 5th iteration
• break;
• }
• continue: This causes the loop to stop its current
iteration and begin the next one.
Slides by Mrs. Pai for Sem 6 (2016-2017) 69
Enumerated data type- keyword enum
An enumerated data type is a user-defined data type.
• It provides a way for attaching names to numbers.
• It automatically enumerates a list of words by
assigning them values 0,1,2,3 … .
Format/syntax :
enum shape{circle, square, rectangle};
enum position{right, left};
enum colour{red,green,blue,white};
C++ permits the creation of enums without tag names.
e.g enum {right, left};
Slides by Mrs. Pai for Sem 6 (2016-2017) 70
More on enum
• enum resistor_code { black,
brown,red,orange,yellow,green,blue,violet,grey,white};
By defining a set of integer constants using ‘enum’
keyword.
• e.g: enum { R1, R2, R3 }; const R1 = 0, const R2 = 1,
const R3 = 2.
Always start value with 0
End with terminator;
Slides by Mrs. Pai for Sem 6 (2016-2017) 71
Programs
Initialising : beginning
{
clrscr( );
enum colour { red =1, blue,
black};
cout<<red+black;
//u will get o/p as 4
getch();
}
Initialising : in between
{
clrscr( );
enum colour { red, blue=2,
black};
cout<<red+black;
//red =0,black=3,u will get o/p
as 3
getch();
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 72
Introduction to functions
• A complex program can be decomposed
into small or easily manageable parts.
Each small module is called a
subprogram or a subroutine. A
subprogram performs a specific task.
Slides by Mrs. Pai for Sem 6 (2016-2017) 73
What are the advantages of subprograms ?
• Very simple to write correctly
• Very easy to read, write, debug
• Easy to modify and use in the main program.
• May be recalled any number of times in any place,
but stored in memory just once.
• A subprogram cannot execute by itself , it is called
either by main program or by other subprograms
.
Slides by Mrs. Pai for Sem 6 (2016-2017) 74
Functions
• A function is a collection of statements that
performs a specific task.
• A function breaks a program into small
manageable units.
• Functions simplify the programs and reduce
the program size.
• Functions are building blocks of C++ programs.
Slides by Mrs. Pai for Sem 6 (2016-2017) 75
Parts of functions
• All function definitions have the following
parts

Return type.

Name.

Parameter list and

body.
Slides by Mrs. Pai for Sem 6 (2016-2017) 76
Parts contd….
void main (void)
return data type { body parameter list
} Name
=========================
int main ( )
{ --------;
getch();
return 0; }
functions that have a return value should use the
‘return’ statement for termination.
Slides by Mrs. Pai for Sem 6 (2016-2017) 77
A function is executed when it is called.
Calling a function
• ‘main’ is called automatically when a program
starts.
• All other functions must be executed by
‘function call’ statements.
• When a function is called, the computer
temporarily puts the main function on hold
and starts the execution of that function.
Slides by Mrs. Pai for Sem 6 (2016-2017) 78
Function header, function call & function prototype
•How to identify?
void main ()
void showCal()
int getResult()
float Area()
int message()
void counter()
void showCal(int);
int getResult(float);
float Area() ;
int message();
void counter() ;
showCal();
getResult();
Area();
message() ;
counter() ;
Slides by Mrs. Pai for Sem 6 (2016-2017) 79
A complete program(type 1)
#include<iostream.h>
#include <conio.h>
void orange (void) // function definition or function header, so no semicolon
{ cout<< “ I am in TYBSc, Semester 6n”;
cout<< “ ------ --------- ----nn”;
}
void pink (void) // function header
{ cout<< “Today I am attending the lectures.n”;
}
int main(void)
{ cout<< “ I am in the beginning of function main.n”;
orange ( ); //call function orange . Notice the semicolon
pink ( ); // call function pink
cout<<” Well, I have come back to mainn”;
getch( );
return 0;
} *No data communication between functions as it is
declared void pink/orange
Slides by Mrs. Pai for Sem 6 (2016-2017) 80
A function within another function
// There are 3 functions main, college and dept
#include<iostream.h>
#include<conio.h>
void dept (void) // function header
{ cout<<” This is second branchn”;
}
void college (void) // function header
{ cout<<”This is first branchn”;
dept ( ); //call function dept
cout<<”Back to function college n”;
}
// function dept is within function college
void main (void)
{ cout<< “Gate opens. Here is the entry. This is SIES college in function mainn”;
college ( ); //call function college
cout<<”Back to main…..SIES collegen”;
getch();
} *No data communication between functions
Call, definition, prototype
 By using function
header at the beginning
of the Program.
•By declaring the
function with a
function prototype
 Function call is the mechanism that transfers control to a function.
 Before a function is being called, the compiler should know the
function’s return type, number of parameters it uses and the type
of each parameter.
 There are 2 ways of doing this.
Slides by Mrs. Pai for Sem 6 (2016-2017) 81
Slides by Mrs. Pai for Sem 6 (2016-2017) 82
Prototypes: The prototype describes the function interface to the compiler
by giving the number and type of arguments and the type of return values.
Format: type function-name (argument-list);
 void one (void);
 float area(float x, float y);
 float volume(float x, int y, float z);
 float volume(float , int , float );
 If you do not use function header or function
prototype ahead of all calls to the function, the
program will not compile.
 It is necessary to declare independently all
variable arguments inside the parantheses.
Slides by Mrs. Pai for Sem 6 (2016-2017) 83
Program using function prototype
.
// add and subtract are 2 functions.
#include<iostream.h>
void add ( ); // function prototyping
void subtract ( );
int main (void)
{
cout<< “Calling function add ( ).”<<endl;
add ( ); // a call to function add
subtract ( ); // a call to function subtract
cout<< “ a return from both functions”<<endl;
getch( );
return 0;
}
void add ( ) //this is function header
{ int i , j, sum;
cout<< “n Input 2 integers :”<<endl;
cin>>i>>j;
sum = i + j;
cout<< “The sum of 2 integers=”<<sum<<endl;
}
void subtract ( ) // function header
{ cout<< “ The prototyping is understood.”<<endl;
}
o/p
Calling function add ( ).
Input 2 integers :4
5
The sum of 2 integers=9
The prototyping is understood.
a return from both functions
Slides by Mrs. Pai for Sem 6 (2016-2017) 84
A complete program(type 2)
#include<iostream.h>
#define pi 3.14159
void circle(float);
void main()
{ cout<< “finding area of circle”<<endl;
float r;
cout<<“Enter the radius”;
cin>>r;
circle();
cout<<“ Job well done”;
getch();
}
void circle(float r)
{ double Area;
Area=pi*r*r;
cout<<“area of circle=“<<Area;
} *No return type data as it is declared void
circle but has a list of parameters(one way
data communication)
Slides by Mrs. Pai for Sem 6 (2016-2017) 85
A complete program(type 3)
Returning a value from a function
main program
#include<iostream.h>
#include<conio.h>
int sum(int,int);
int diff(int,int);
int mul(int,int);
void main()
{ clrscr();
int a=10,b=4;
sum(a,b);
diff(a,b);
mul(a,b);
cout<< (a+b) + (a-b)+(a*b);
getch();
}
o/p 60
Function definition
int sum(int x, int y)
{ return (x+y);
}
int diff(int x,int y)
{ return (x-y);
}
int mul(int x,int y)
{ return x*y;
}
*Two way data communication
Slides by Mrs. Pai for Sem 6 (2016-2017) 86
Assignment
• Classify the following into function call,
function header and function prototype
Output(); void square ();
int add() store(); float display_2()
int Value(int, int, int); void funct ()
college(); float color(float x, int y);
inputData();
Slides by Mrs. Pai for Sem 6 (2016-2017) 87
function with multiple parameters.
#include <iostream.h>
#include<conio.h>
void showSum(int, int, int); //prototype , note only data type
int main(void)
{ int A1, A2, A3;
cout<<”Enter 3 integers & find sum”;
cin>>A1>>A2>>A3;
showSum(A1,A2,A3); // function call
//call to function showSum with 3 arguments
// see data type ‘int’ should not written in a call
getch();
return 0;
}
void showSum(int num1,int num2, int num3) // here int to be written –a must
{
cout<< “n”<<num1+num2+num3<<endl;
}
o/p
Enter 3 integers & find sum
3
4
5
12
Slides by Mrs. Pai for Sem 6 (2016-2017) 88
Program to draw a rectangle
#include<iostream.h>
#include<conio.h>
void draw_box(void);
void main(void)
{ cout<< “ I am drawing a box”<<endl;
draw_box();
cout<<am happy, have done it beautifully..doing one more”;
draw_box();
getch();
}
void draw_box(void)
{ cout<< “****************”<<endl;
cout<< “****************”<<endl;
cout<< “****************”<<endl;
cout<< “****************”<<endl;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 89
Function overloading
• ‘Overloading‘ refers to the use of the same thing for
different purposes.
• Meaning: we can use the same function-
name to create functions that
perform a variety of different
tasks.
This is also known as polymorphism.
SO…..
Slides by Mrs. Pai for Sem 6 (2016-2017) 90
‘return’ statement Syntax : return;
• When the last statement in a function has finished executing, the
function terminates and the program returns to the statement following
the function call.
• However, it is possible to force a function to return before the execution
of the last statement. This is done by using a return statement.
• When this statement is encountered, the function immediately
terminates and the program returns.
Slides by Mrs. Pai for Sem 6 (2016-2017) 91
More…..
• Values that are sent into a function are called arguments.
e.g: float area(float ℓ, float b );
• Reference variable
e.g: void doubleNum(int &refVar)
Slides by Mrs. Pai for Sem 6 (2016-2017) 92
Call by reference and Return by reference
• A reference variable provides an alternative name (alias )for a previously defined
variable. In C++, provision of this reference variable is useful in passing parameters
to the functions by reference. When we pass arguments by reference, the ‘formal’
arguments in the called function become aliases to the ‘actual’ arguments in the
calling function. This means that when the function is working with its own
arguments, it is actually working on the original data.
( Any changes made to the reference variable are actually performed on the
variable for which it is an alias.)
Slides by Mrs. Pai for Sem 6 (2016-2017) 93
A program
// use of ref. variable as a function parameter.
//call by reference
#include<iostream.h>
void doubleNum(int &); //prototype
void main(void)
{
int value =3;
cout<< “In main, the value is ”<<value<<endl;
cout<< “calling doubleNum ”<<endl;
doubleNum(value); //function call
cout<< “Back into main, the value is”<<value<<endl;
}
void doubleNum(int &refVar)
{
refVar* =2;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 94
Passing a value or values
→ Values that are sent into a function are called arguments.
e.g shop(10);
→ Parameters in the function header are also called as formal arguments.
e.g void calArea(int count)
// passing a value? how? Pay attention
void passVal (int); //prototype
void main( )
{ passVal(65); //call … pass 65
passVal(20); //call … pass 20
passVal(16); //call … pass 16
cout<<“ I know how to pass a value.”; getch(); }
void passVal (int x)
{ cout<<“ the value is = ” << x; }
Slides by Mrs. Pai for Sem 6 (2016-2017) 95
Returning a value from a function, another e.g
main program
#include<iostream.h>
#include<conio.h>
int square(int);
void main()
{
int N, Result;
cout<<“Enter an integern”;
cout<< N;
Result = square(N);
cout<< “o/p=”<< Result<<endl;
getch();
}
Function definition
int square(int number)
{ return (number * number);
}
o/p
Enter an integer
8
o/p=64
Slides by Mrs. Pai for Sem 6 (2016-2017) 96
Default arguments
• A function can be called without specifying all the arguments. In such
cases, the function
• assigns a default value to the parameter which does not have a matching argument in the
function call.
• Default values are specified when the function is declared.
• Default values are specified similar to variable initialization.
• Only trailing arguments can have default values and they are added from right to left.
• They are useful when an argument has the same value throughout the program.
• The complier looks at the prototype to see how many arguments the function uses and if found
less, then default values are assigned to that argument.
• Even after mentioning the default value in the prototype, when the call to the function is made,
the value to that variable may be passed explicitly.
Slides by Mrs. Pai for Sem 6 (2016-2017) 97
Examples
 int total( int exam_theory , float prac, int assign=10);
 int total( int exam_theory , float prac =4 );
 int total( int exam_theory , float prac =4, int assign);
× int total( int exam_theory=6 , float prac , int assign);
float product( int a, int b, int c=6, float d= 3.14);
 product(4, 3, 5,); // call with c=5 & one argument missing
float amount( int principal, int time, float rate=4);
 amount(2000,5,3) // No argument missing.
Slides by Mrs. Pai for Sem 6 (2016-2017) 98
Some More programming…..
:
//program with default value
#include<iostream.h>
#include<conio.h>
float amount( int , int , float r=0.5);
int main(void)
{ amount(100,2);
getch( );
return 0;
}
float amount( int p, int n, float r)
{ float amount;
amount = p*n*r; // p =100,n=2
cout<<"total amt="<< amount;
}
// default value can be changed
#include<iostream.h>
#include<conio.h>
float amount( int , int , float r=0.5);
int main(void)
{ amount(100,2,0.8);
getch( );
return 0;
}
float amount( int p, int n, float r)
{ float amount;
amount = p*n*r; // p =100,n=2
cout<<"total amt="<< amount;
}
Slides by Mrs. Pai for Sem 6 (2016-2017) 99
Assignment…find the errors..True/F
1. void Sum(int n1, n2, n3)
{return n1+n2+n3; }
2. float average (int x, int y, int z)
{ float average;
average= x + y + z /3; }
3. void area_rect ( int length=4, int breadth)
{ return length* breadth;}
4. void getValue( int read&)
{ cout<<“Enter a number”<< endl;
cin>>read&; }
5. Function should be given the name that reflects the purpose.(T/F)
6. Function prototypes end with semicolon . ( T/ F)
7.When only a copy of an argument is passed to a function, it is said to be passed
by ___________.
8. The __________ statement causes a function to end.
:answer in next slide
Slides by Mrs. Pai for Sem 6 (2016-2017) 100
answers
1. Function declared is void, but returning a value, int must be
for all variables
2. average=( x + y + z)/3.0;
3. Function declared is void, but returning a value, default
value for breadth too.
4. Should be &read and not read&.
5. True
6. True
7. Value
8. return;
Slides by Mrs. Pai for Sem 6 (2016-2017) 101
Slides by Mrs. Pai for Sem 6 (2016-2017) 102
Procedure Oriented Programming (POP)
• Procedural languages:
BASIC :Beginner’s All-purpose Symbolic Instruction Code
FORTRAN: Formula Translation
COBOL : Common Business oriented language
Pascal , C …..
•Problem viewed as sequence of things.
•Each statement in the language tells the computer
to do something.
•List of instructions.
Slides by Mrs. Pai for Sem 6 (2016-2017) 103
Object oriented Programming(OOP)
• Emphasis is on doing things (algorithms)
• Large programs are divided into small programs known as functions.
• Most of the functions share global data.
• Combine both data & functions that operate on data into a single unit called
object.
• Functions ( methods ) provide the only way to access data
• C++ programs consists of number of Objects which communicate with each
other through member functions .
• Data is hidden & safe from accidental modification.
Slides by Mrs. Pai for Sem 6 (2016-2017) 104
Basic concepts of object oriented
programming
 Object - An object is a software bundle of variable & related methods.
 Class - Fundamental building block of an object oriented program.
- It is a collection of similar objects
 Encapsulation -Wrapping up of data & functions into a single unit
(called class) is known as encapsulation.
-Data is not accessible to the outside world & only those
functions, which are wrapped in the class, can access it.
-This insulation of data from direct access by the program is
called data hiding.
 Inheritance - classes to be defined in terms of other classes.
 Polymorphism -Ability to take more than one form.
 Message passing -Software objects interact and communicate with each
other by sending messages to each other.
Referring, writing, checking, discussing &
achieving perfection
 Tony Gaddis
 E. Balaguruswamy
 Yashwant Kanitkar
 D.Ravichandran
#include<>
void main()
{clrscr(); int I, j;
cout>>”.”;
cin<<i;
Slides by Mrs. Pai for Sem 6 (2016-2017) 105

C++Object oriented Programming with C++.pptx

  • 1.
    Programming with C++ Apresentation by Pratibha Pai Department of PHYSICS SIES College, Sion(west) UNIT 4 ELECTRONIC INSTRUMENTATION SEMESTER 6 T Y B.Sc(2016-2017)
  • 2.
    2 Reference books 1. E.Balaguruswamy 2.Tony Gaddis 3. D. Ravichandran 4. Yashwant Kanitkar Slides by Mrs. Pai for Sem 6 (2016-2017)
  • 3.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 3 INTRODUCTION We need a computer/software to study C++ . • A computer is an electronic machine. • It is specifically designed to follow instructions. • It can be programmed. • It is able to do the only jobs that programs tell it to do..
  • 4.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 4 What is C++ ? • C++ is an Object-Oriented Programming (OOP) language. • It was developed by Bjarne Stroustrup at AT and T Bell laboratories in Murray Hill, USA in 1985. • C ++ is a high level language. • C ++ is studied directly using programs for better understanding.
  • 5.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 5 Data types • integer(int) • floating point numbers(float) • character(char) • String • bool
  • 6.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 6 Special Names  < > → opening and closing brackets  # → pound sign (hash)  { } → opening and closing braces  “ ”→ opening & closing quotation marks  ( ) → opening and closing parentheses  // → double slash  ; → semi colon, statement terminator.
  • 7.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 7 C++ program :1 1. // A simple program for understanding. 2. #include<iostream.h> 3. #include<conio.h> 4.void main(void) 5. { 6. clrscr(); 7. cout<<“Writing program is interesting and fun.” << endl; 8. /*endl means end of line*/ 9. cout<<“ Hello, listen here !n”; 10. cout<<“tWe should study hard this semester”; 11. cout<<“n I am just thinking, It is easy yaar!”; 12. getch(); 13. } << is insertion operator
  • 8.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 8 C++ program :2 • // A very simple program with a variable. • #include<iostream.h> • #include<conio.h> • void main (void) • { • clrscr( ); • int i; //variable declaration statement • cout<< “Input value of i”<<endl; • //endl means end of line • cin>>i; //input statement • cout<<“The value of i is ”<< i<< endl; • getch( ); • } >> is an extraction operator
  • 9.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 9 C++ program :3 /* program to learn cascading of input operator and output operator finding sum and difference of 2 integers */ void main( ) { int n1, n2, SUM, Diff; cout<< “Enter two positive integers”; cin>>n1>>n2; //cascading input operator or writing multiple input statement. SUM = n1 + n2; Diff = n1 - n2; // assignment statements .. //Expression is a Combination of constants & variables together with operators. //look here how to cascade output operator.. cout<<“n The sum of 2 integers ” <<n1<< “and ” <<n2<<“is = ” <<SUM; cout<<“n The difference is = ” << Diff; getch( ); }
  • 10.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 10 Summary: Comments • Lines beginning with // indicate that remainder of that line is a comment. There is no closing. • Single line comments. • If the comment goes to the next line, // is used again. • A comment may start anywhere in the line and in the program. • Lines beginning with /* and ending with */ are multiple line comments used in C.
  • 11.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 11 Comments….. • Improves program readability. • Help other people to read & understand programs. • Not valid C++ statements, not executed. • Ignored by the compiler. • Do not cause any machine language object code to be generated. • So, we can write anything: date, name, reference, meaning of variable introduced etc...
  • 12.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 12 #include <iostream.h> • pre processor directive. • #include preprocessor command causes contents of named file to be inserted where #include command appears. • iostream.h is a header file to be included at the top /head of program. • Lines beginning with # are processed by the preprocessor before compilation. • Specific line tells the preprocessor to include contents of input/output stream header file <iostream.h> • Any program that outputs data to the screen or inputs data from keyboard must include this file. • cin & cout are not a part of core language. • part of input-output stream library.
  • 13.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 13 void main() • Part of every C++ program. • Parenthesis after main indicates that main is a program building block called a function. • C++ program is made up of one or more functions, one of which must be necessarily main(). • Execution of every C++ program begins at main() , even if main() is not the first function. • Keyword void to the left indicates that it does not return any value. • The function main begins at Left brace { and ends at Right brace }
  • 14.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 14 cout << “All is well.” ; • Print a string of characters contained within double quotation marks. • Entire line is called a C++ statement. • Every statement must end with a semi colon (statement terminator) • On execution , a stream of characters is sent to standard output stream object normally connected to the screen. • Operator << is stream insertion operator. (also called ‘put to’ operator) • Value to right of the operator(operand) is inserted in output stream. • The cout object sends data to standard output display device.
  • 15.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 15 cin>>n1>>n2; • Operator >>is stream extraction operator. • Also called ‘get from’ operator. cin>>n1; • Takes the value of the variable /identifier n1 at the time of execution of the program. cin>>n1>>n2; • Takes the value of the variables n1 and n2.
  • 16.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 16 Complete C++ program //We are finding area of a rectangle # include<iostream.h> # include<conio.h> void main(void) { int len, wid,area; //using CGS system cout<<“Enter length of the rectangle in cm:n”; cin>>len; cout<<“Enter the breadth of the rectangle in cm : n”; cin>>wid; area =len * wid; // * is an arithmetic operator cout<<“area of the given rectangle = ”<<area<<“sq.cm”; getch(); }
  • 17.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 17 Note (i) There are no line numbers. (ii) C++ is case-sensitive. (iii) C++ is space ignorant. (iv) All key words are in lower case. (v) Identifiers cannot have spaces in between. (vi) .cpp files are compiled. (vii) Header files are included. (viii) Multiple files need to be put in a project. (.cpp files)
  • 18.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 18 7 phases from Source code… Object code….. Executable code • Source code---Edit • preprocessor • Modified source code • compiler • Object code • Linker • Executable code
  • 19.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 19 The smallest individual units in a program are known as tokens. They are • key words • identifiers (programmer- defined symbols) • operators • constants and • strings. TOKENS- Language elements
  • 20.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 20 KEY WORDS: written in lower case • These are also known as reserved words. • They have a special meaning. They cannot be used for any other purpose than what they are designed for. List of key words in alphabetical order ……a quick glance • asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, extern, export, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while.
  • 21.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 21 Identifiers : Rules • Series of characters consisting of letters, digits & underscore that does not begin with digit. • Case sensitive – uppercase & lowercase letters are different. • Keywords or reserved words cannot be used as identifiers. • Blank spaces letters cannot be a part of an identifier. • Special characters are also not allowed….#, $, &, !, @, , /, • Allows identifiers of any length. • System and/or C++ implementation can impose some restrictions on length of identifier.
  • 22.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 22 Identifiers : valid/ invalid Identifier Valid / Invalid Reason 5axbycz Invalid Cannot start with digit basic salary invalid Special character (space) not allowed #pay Invalid Special character (hash) not allowed counter Valid default invalid C++ key or reserved word. _perimeter Valid S.I.E.S invalid Dot not allowed
  • 23.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 23 Operators : categories • Arithmetic operators • Relational operators • Logical operators • Assignment operators • Bitwise operators • Others
  • 24.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 24 operators :operate on one or more operands • Arithmetic---(+ , - , * , /, %) • Logical --- AND(&&), OR(||), NOT(!) • Relational ---(<, <=, >, >=, ==, !=) o Ternary o Binary depending on number of operands o Unary
  • 25.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 25 Binary Arithmetic Operation operator Algebraic expression C++ expression Addition + m + 7 m + 7 Subtraction - a – c a – c Multiplication * mn m * n Division / x/y x / y Remainder % r mod s r % s
  • 26.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 26 Binary Arithmetic • % operator requires that both operands be integers & second operand be non-zero. • Result of division operation is truncated quotient when both operands are integer quantities. • Division operator requires second operand be non-zero.
  • 27.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 27 Binary Arithmetic • The % operator divides the left operand by the right operand, & the result is the remainder after integer division. • / operator denotes integer division if both arguments are integers & floating point division otherwise.
  • 28.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 28 Binary Arithmetic • float a = 12.0 , b= 9.0; a + b = 21.0 a – b = 3.0 a * b = 108.0 a / b = 1.33 a % b : not applicable as operator requires integer operands For modulo operation the sign of the result is always the sign of the first operand. e.g. -14 % 3 = -2 -14 % -3 = -2 14 % -3 = 2
  • 29.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 29 Examples : unary, binary, ternary • -x, -m…. • A+b, n* m; • expression ? expression : expression; x=10 ? y=3 : y=0;
  • 30.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 30 Examples • (7 == 5) // evaluates to false. • (5 > 4) // evaluates to true. • (3 != 2) // evaluates to true. • (6 >= 6) // evaluates to true. • (5 < 5) // evaluates to false.
  • 31.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 31 Logical operators :&&, ||, ! Syntax: expression1 && expression2 •expression1 is evaluated.(left operand) • If expression1 is false , expression2 is not evaluated. • If expression1 is true , the value of the second expression is the final value. Syntax: exp1 || exp2 • exp1 is evaluated. • If exp1 is true , exp2 is not evaluated. • If exp1 is false , the value of the second expression is the final value. Syntax: ! exp •unary operator •exp is evaluated. • If exp is true , ! exp is false and If exp is false, ! exp is true
  • 32.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 32 Operator --hierarchy Arithmetic Relational Logical unary negation <, <=, >, >= ! NOT *, /, % = =, != && AND +, - || OR left to right
  • 33.
    Operators ---continued • incrementand decrement operators ++ and    post fix mode e.g a++, a--  pre fix mode e.g ++x, --x a=5; a=5; X= a++; x=++a; o/p : X=5 o/p: x=6 • Prefix does the addition/subtraction first. • Postfix evaluates to the old value of the variable first Slides by Mrs. Pai for Sem 6 (2016-2017) 33
  • 34.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 34 Assignment 1 What is the o/p? 1. int a = 2 , b = 5 ; int c = a * b++ ; //postfix cout << a << “ “ << b << “ “ << c ; Output : 2 6 10 2.int c = a * ++ b ; //prefix cout << a << “ “ << b << “ “ << c ; Output : 2 6 12
  • 35.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 35 Assignment 2 • What is the output of the following program? #include<iostream.h> int main() { int a = 5 ; o/p cout << “ ” << a << endl ; 5 cout << “ ” << (a++) << endl ; 5 cout << “ ” << (++a) << endl ; 7 return 0 ; }
  • 36.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 36 Bitwise operators &, |, ^, ~, <<, >> operator asm equivalent description & AND Bitwise AND | OR Bitwise Inclusive OR ^ XOR Bitwise Exclusive OR ~ NOT Unary complement (bit inversion) << SHL Shift Left >> SHR Shift Right
  • 37.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 37 Escape sequence • They give us the ability to exercise greater control over the way information is output by the program. • An escape sequence always starts with a back slash () and is followed by one or more control characters. Note: There is no space between the back slash and the control character.
  • 38.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 38 Escape sequence: examples • n • t • a • b • • ’ • ” • r • cursor to go to next line for printing. • cursor to go to the next tab stop. • the computer to beep. • cursor to move left by one position. • backslash to be printed. • single quotation mark to be printed. • double quotation mark to be printed. • cursor to go to the beginning of the current line.
  • 39.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 39 Expressions • Combination of constants & variables together with operators. • Balanced parenthesis may be used in combining constants & variables with operators. • Constants & variables by themselves are also considered expressions.
  • 40.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 40 Expressions: Constant and algebraic • An expression that involves only constants is called constant expression. 5 + 2 = 7 Operands operator Value of result
  • 41.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 41 No exponentiation operator • Raising a number to power requires use of library function pow area = pow(4,2) ; //o/p area= 16 • raises first argument to the power of second argument. • Need to include math.h header file
  • 42.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 42 Assignment statement(operator) Syntax: variable = expression • Assign a value to a variable. • Expression may be a single constant or complex combination of variables , operators & constants. e.g: x=5; p=q; m=n+4; a= (5+7)* 3/4 ;
  • 43.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 43 Compound assignment operators • There are Five compound arithmetic assignment operators. Operator Example Meaning/equivalence += a +=5; a = a + 5; -= b -=8; b = b – 8; *= c *= 7; c = c * 7; /= d /=10; d= d /10; %= e %= 100; e= e % 100;
  • 44.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 44 Other operators • Ternary…. ? : (if-then-else type) • Increment/decrement …. ++ /-- • memory allocation & deallocat ion new delete • Scope resolution …. :: • size of the variable in bytes… sizeof(variable) • Comma operator…… , (separator in declaration) ; ( separator in loops) • Type cast … see next slide please
  • 45.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 45 Type cast opeartor • What is type casting? It is a technique to forcefully convert one data type of variable to another data type. • Syntax: ( cast type) variable or expression OR cast type(variable or expression ) e.g: (float)month or float(month)
  • 46.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 46 #define pi 3.14 OR const float pi=3.14 //to find area of a circle #define PI 3.14 #include<iomanip.h> void main (void) { float r, area; // r is radius cout<<“Problem: To print Area of the circlen"; cout<<"Enter the radiusn"; cin>>r; area= PI * r * r; cout<<"n The area of the circle of radius "<< r<<" is = " << setprecision(2)<< area; getch( ); }
  • 47.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 47 What is the program for? { int a, b, t; // t is temporary variable. cout<<” input 2 integers one after another n”<<endl; cin>>a>>b; cout<< “ n The numbers are a= “<< a<<” and b= “<< b; cout<< endl; cout<< endl; t = a; a = b; b = t; cout<<“a= “<< a << “ “b= “<<b; }
  • 48.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 48 Control – flow statements and their need • A program is usually not limited to a linear sequence of instructions. • It may bifurcate, repeat code or take decisions during its process. • So, C++ provides control structures. Let us study STRUCTURED PROGRAMMING.
  • 49.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 49 All program processing can be coded by using only 3 logic structures. THEY ARE: •Sequence structure(straight line) •Selection structure(branching) •Loop structure(iteration or repetition) These structures are implemented using one-entry, one -exit concept. The approach of using one or more of the above structures is known as structured programming.
  • 50.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 50 Control statements & Loops • if • if – else • if – else if • for • while • do – while • switch - case • break • continue
  • 51.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 51 1. The if statement • This is used to execute an instruction or a block of instructions only if a certain condition is fulfilled. • The general format is if (condition) statement ; //action
  • 52.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 52 Program with if //to check if a no. is even #include<iostream.h> void main() { int n; cout<<“Enter the number to be checked”; cin>>n; if(n %2 = = 0) cout<<“n The entered number “<<n<<“ is even”; }
  • 53.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 53 Execution of a C++ Program • Enter the program • Save the program as .cpp extension • Manually go through and edit, save again(F2) • Compile ( either from menu or Alt + F9) • Errors are shown, understand, edit and save. • Once you debugged, success message is seen. • Execute or run the program ( either from menu or Ctrl + F9) • View the o/p.
  • 54.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 54 Formatting output … this is an art ---- using---- • n printing in new line • endl printing in new line • t printing after one tab space • “ ” printing with space shown • ; printing without space #include<iomanip.h> • setprecision(n)  printing upto n places after the decimal point • setbase( base)  printing the value in the base shown 10/16/2/8 • setw(n)  to keep n character places on the o/p for a variable to consume
  • 55.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 55 Understanding • setprecision(n) float a,b,c; a=5,b=3; c=a/b; cout<<setprecision(1)<<c; 1.7 cout<<setprecision(2)<<c; 1.67 cout<<setprecision(3)<<c; 1.667 • setbase( base) int value = 10; cout<< “value in decimal=”<<setbase(10)<<value; 10 cout<< “value in hex=”<<setbase(16)<<value; a cout<< “value in octal=”<<setbase(8)<<value; 12 • setw(n) int x=100,y=500; cout << setw(5) << x << setw(5) << y; 1 0 0 5 0 0
  • 56.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 56 2. The if – else statement • The general format is if (condition) { statement 1 ; //action1 } else { statement 2 ; //action2 }
  • 57.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 57 Program 1 with if -else //to check if a no. is even or odd void main() { int num; cout<<“Enter the number to be checked”; cin>>num; if(num %2 = = 0) cout<<“n The entered number “<<num<<“ is even”; else cout<<“n The entered number “<<num<<“ is odd”; }
  • 58.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 58 Program 2 with if -else //to check which number is bigger void main() { int num1, num2; cout<<“Enter the 2 numbers to be checked”; cin>>num1>> num2; if(num1 > num2) cout<<“n ”<< num1<< “ is bigger than ”<<num2; else cout<<“n”<< num2 <<“ is bigger than ” <<num1; }
  • 59.
    3. The if– else if statement if (expression) statement 1 ; else if (expression) statement 2 ; else if (expression) statement 3 ; else statement 4; if (total>75) cout<<“distinction”; else { if (total>60) cout<<“First”; else { if (total>40) cout<<“Second”; else cout<<“Pass”; } } Slides by Mrs. Pai for Sem 6 (2016-2017) 59
  • 60.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 60 4. The for loop The stepwise working is as follows: for (n=1; n<6 ; n++ ) { statement1 ; } statement2;
  • 61.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 61 Program1 with for //sum of integers 5 to 20 { clrscr(); int Sum=0; //Declaration of variable at the place of use. for( int m =5 ; m<= 20 ; m ++) Sum += m ; // Sum = Sum + m; cout<< “Sum of the numbers = “ << Sum ; getch(); }
  • 62.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 62 Program2 with for // To write the multiplication table of an integer. { int t ; // t is the number whose table is required int count; cout<<" Table of which integer do you wish to try?n"; cin>>t ; for(count=1; count<= t ;count++) cout<<“t”<<t<<“ * ”<<count<<“ =”<<t *count <<“n”; getch( ); }
  • 63.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 63 5. The while loop • The general format is as follows. while( condition or expression) { ------------ ----------statements; } True False
  • 64.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 64 Program with while //sum of integers 5 to 20 { clrscr(); int m =5, Sum=0; while (m<= 20) { Sum += m ; // Sum = Sum + m; m ++; } cout<< “Sum of integers 5 to 20 = “ << Sum ; getch(); }
  • 65.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 65 6. The do –while loop The general format is do {---------- ---------- ---------- statements; } while(expression); this ; is important.
  • 66.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 66 Program with do -while //The program should repeat as many times as the user requires. void main( ) { int a1, a2, a3, tot, n ; // n for Roll No., a1, a2, a3 for attendance char choice; // choice is any letter from A to Z or a to z n = 0; do { n++ ; cout<<"Enter the attendance in 3 months:n"; cin>>a1>>a2>>a3; tot = a1+ a2 + a3 ; cout<<"n The total attendance for roll number " << n<< " : "<< tot; cout<<"n Do you wish to repeat this for another student? Say Y or Nn"; cin>> choice; } while(choice = ='y' || choice = ='Y '); // single quotes for character constant getch( ); }
  • 67.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 67 7. The switch-case statement switch(variable / expression) {case constant 1: // case ‘x’ : block of instructions 1 break; case constant 2: block of instructions 2 break; : : default: block of instructions } • First, the expression is evaluated. • it is checked for constant1. • If it is, then block of instructions 1 is executed until the ‘break’ word is encountered • Finally it jumps to the end of switch selective structure. • If not constant 1, it is checked for constant 2 and same procedure as above.
  • 68.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 68 8. break • int i=0; • while(i++<20) • { • cout<<i<<endl; • if(i = = 5) • // program stops after 5th iteration • break; • } • continue: This causes the loop to stop its current iteration and begin the next one.
  • 69.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 69 Enumerated data type- keyword enum An enumerated data type is a user-defined data type. • It provides a way for attaching names to numbers. • It automatically enumerates a list of words by assigning them values 0,1,2,3 … . Format/syntax : enum shape{circle, square, rectangle}; enum position{right, left}; enum colour{red,green,blue,white}; C++ permits the creation of enums without tag names. e.g enum {right, left};
  • 70.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 70 More on enum • enum resistor_code { black, brown,red,orange,yellow,green,blue,violet,grey,white}; By defining a set of integer constants using ‘enum’ keyword. • e.g: enum { R1, R2, R3 }; const R1 = 0, const R2 = 1, const R3 = 2. Always start value with 0 End with terminator;
  • 71.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 71 Programs Initialising : beginning { clrscr( ); enum colour { red =1, blue, black}; cout<<red+black; //u will get o/p as 4 getch(); } Initialising : in between { clrscr( ); enum colour { red, blue=2, black}; cout<<red+black; //red =0,black=3,u will get o/p as 3 getch(); }
  • 72.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 72 Introduction to functions • A complex program can be decomposed into small or easily manageable parts. Each small module is called a subprogram or a subroutine. A subprogram performs a specific task.
  • 73.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 73 What are the advantages of subprograms ? • Very simple to write correctly • Very easy to read, write, debug • Easy to modify and use in the main program. • May be recalled any number of times in any place, but stored in memory just once. • A subprogram cannot execute by itself , it is called either by main program or by other subprograms .
  • 74.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 74 Functions • A function is a collection of statements that performs a specific task. • A function breaks a program into small manageable units. • Functions simplify the programs and reduce the program size. • Functions are building blocks of C++ programs.
  • 75.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 75 Parts of functions • All function definitions have the following parts  Return type.  Name.  Parameter list and  body.
  • 76.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 76 Parts contd…. void main (void) return data type { body parameter list } Name ========================= int main ( ) { --------; getch(); return 0; } functions that have a return value should use the ‘return’ statement for termination.
  • 77.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 77 A function is executed when it is called. Calling a function • ‘main’ is called automatically when a program starts. • All other functions must be executed by ‘function call’ statements. • When a function is called, the computer temporarily puts the main function on hold and starts the execution of that function.
  • 78.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 78 Function header, function call & function prototype •How to identify? void main () void showCal() int getResult() float Area() int message() void counter() void showCal(int); int getResult(float); float Area() ; int message(); void counter() ; showCal(); getResult(); Area(); message() ; counter() ;
  • 79.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 79 A complete program(type 1) #include<iostream.h> #include <conio.h> void orange (void) // function definition or function header, so no semicolon { cout<< “ I am in TYBSc, Semester 6n”; cout<< “ ------ --------- ----nn”; } void pink (void) // function header { cout<< “Today I am attending the lectures.n”; } int main(void) { cout<< “ I am in the beginning of function main.n”; orange ( ); //call function orange . Notice the semicolon pink ( ); // call function pink cout<<” Well, I have come back to mainn”; getch( ); return 0; } *No data communication between functions as it is declared void pink/orange
  • 80.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 80 A function within another function // There are 3 functions main, college and dept #include<iostream.h> #include<conio.h> void dept (void) // function header { cout<<” This is second branchn”; } void college (void) // function header { cout<<”This is first branchn”; dept ( ); //call function dept cout<<”Back to function college n”; } // function dept is within function college void main (void) { cout<< “Gate opens. Here is the entry. This is SIES college in function mainn”; college ( ); //call function college cout<<”Back to main…..SIES collegen”; getch(); } *No data communication between functions
  • 81.
    Call, definition, prototype By using function header at the beginning of the Program. •By declaring the function with a function prototype  Function call is the mechanism that transfers control to a function.  Before a function is being called, the compiler should know the function’s return type, number of parameters it uses and the type of each parameter.  There are 2 ways of doing this. Slides by Mrs. Pai for Sem 6 (2016-2017) 81
  • 82.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 82 Prototypes: The prototype describes the function interface to the compiler by giving the number and type of arguments and the type of return values. Format: type function-name (argument-list);  void one (void);  float area(float x, float y);  float volume(float x, int y, float z);  float volume(float , int , float );  If you do not use function header or function prototype ahead of all calls to the function, the program will not compile.  It is necessary to declare independently all variable arguments inside the parantheses.
  • 83.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 83 Program using function prototype . // add and subtract are 2 functions. #include<iostream.h> void add ( ); // function prototyping void subtract ( ); int main (void) { cout<< “Calling function add ( ).”<<endl; add ( ); // a call to function add subtract ( ); // a call to function subtract cout<< “ a return from both functions”<<endl; getch( ); return 0; } void add ( ) //this is function header { int i , j, sum; cout<< “n Input 2 integers :”<<endl; cin>>i>>j; sum = i + j; cout<< “The sum of 2 integers=”<<sum<<endl; } void subtract ( ) // function header { cout<< “ The prototyping is understood.”<<endl; } o/p Calling function add ( ). Input 2 integers :4 5 The sum of 2 integers=9 The prototyping is understood. a return from both functions
  • 84.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 84 A complete program(type 2) #include<iostream.h> #define pi 3.14159 void circle(float); void main() { cout<< “finding area of circle”<<endl; float r; cout<<“Enter the radius”; cin>>r; circle(); cout<<“ Job well done”; getch(); } void circle(float r) { double Area; Area=pi*r*r; cout<<“area of circle=“<<Area; } *No return type data as it is declared void circle but has a list of parameters(one way data communication)
  • 85.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 85 A complete program(type 3) Returning a value from a function main program #include<iostream.h> #include<conio.h> int sum(int,int); int diff(int,int); int mul(int,int); void main() { clrscr(); int a=10,b=4; sum(a,b); diff(a,b); mul(a,b); cout<< (a+b) + (a-b)+(a*b); getch(); } o/p 60 Function definition int sum(int x, int y) { return (x+y); } int diff(int x,int y) { return (x-y); } int mul(int x,int y) { return x*y; } *Two way data communication
  • 86.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 86 Assignment • Classify the following into function call, function header and function prototype Output(); void square (); int add() store(); float display_2() int Value(int, int, int); void funct () college(); float color(float x, int y); inputData();
  • 87.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 87 function with multiple parameters. #include <iostream.h> #include<conio.h> void showSum(int, int, int); //prototype , note only data type int main(void) { int A1, A2, A3; cout<<”Enter 3 integers & find sum”; cin>>A1>>A2>>A3; showSum(A1,A2,A3); // function call //call to function showSum with 3 arguments // see data type ‘int’ should not written in a call getch(); return 0; } void showSum(int num1,int num2, int num3) // here int to be written –a must { cout<< “n”<<num1+num2+num3<<endl; } o/p Enter 3 integers & find sum 3 4 5 12
  • 88.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 88 Program to draw a rectangle #include<iostream.h> #include<conio.h> void draw_box(void); void main(void) { cout<< “ I am drawing a box”<<endl; draw_box(); cout<<am happy, have done it beautifully..doing one more”; draw_box(); getch(); } void draw_box(void) { cout<< “****************”<<endl; cout<< “****************”<<endl; cout<< “****************”<<endl; cout<< “****************”<<endl; }
  • 89.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 89 Function overloading • ‘Overloading‘ refers to the use of the same thing for different purposes. • Meaning: we can use the same function- name to create functions that perform a variety of different tasks. This is also known as polymorphism. SO…..
  • 90.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 90 ‘return’ statement Syntax : return; • When the last statement in a function has finished executing, the function terminates and the program returns to the statement following the function call. • However, it is possible to force a function to return before the execution of the last statement. This is done by using a return statement. • When this statement is encountered, the function immediately terminates and the program returns.
  • 91.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 91 More….. • Values that are sent into a function are called arguments. e.g: float area(float ℓ, float b ); • Reference variable e.g: void doubleNum(int &refVar)
  • 92.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 92 Call by reference and Return by reference • A reference variable provides an alternative name (alias )for a previously defined variable. In C++, provision of this reference variable is useful in passing parameters to the functions by reference. When we pass arguments by reference, the ‘formal’ arguments in the called function become aliases to the ‘actual’ arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data. ( Any changes made to the reference variable are actually performed on the variable for which it is an alias.)
  • 93.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 93 A program // use of ref. variable as a function parameter. //call by reference #include<iostream.h> void doubleNum(int &); //prototype void main(void) { int value =3; cout<< “In main, the value is ”<<value<<endl; cout<< “calling doubleNum ”<<endl; doubleNum(value); //function call cout<< “Back into main, the value is”<<value<<endl; } void doubleNum(int &refVar) { refVar* =2; }
  • 94.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 94 Passing a value or values → Values that are sent into a function are called arguments. e.g shop(10); → Parameters in the function header are also called as formal arguments. e.g void calArea(int count) // passing a value? how? Pay attention void passVal (int); //prototype void main( ) { passVal(65); //call … pass 65 passVal(20); //call … pass 20 passVal(16); //call … pass 16 cout<<“ I know how to pass a value.”; getch(); } void passVal (int x) { cout<<“ the value is = ” << x; }
  • 95.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 95 Returning a value from a function, another e.g main program #include<iostream.h> #include<conio.h> int square(int); void main() { int N, Result; cout<<“Enter an integern”; cout<< N; Result = square(N); cout<< “o/p=”<< Result<<endl; getch(); } Function definition int square(int number) { return (number * number); } o/p Enter an integer 8 o/p=64
  • 96.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 96 Default arguments • A function can be called without specifying all the arguments. In such cases, the function • assigns a default value to the parameter which does not have a matching argument in the function call. • Default values are specified when the function is declared. • Default values are specified similar to variable initialization. • Only trailing arguments can have default values and they are added from right to left. • They are useful when an argument has the same value throughout the program. • The complier looks at the prototype to see how many arguments the function uses and if found less, then default values are assigned to that argument. • Even after mentioning the default value in the prototype, when the call to the function is made, the value to that variable may be passed explicitly.
  • 97.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 97 Examples  int total( int exam_theory , float prac, int assign=10);  int total( int exam_theory , float prac =4 );  int total( int exam_theory , float prac =4, int assign); × int total( int exam_theory=6 , float prac , int assign); float product( int a, int b, int c=6, float d= 3.14);  product(4, 3, 5,); // call with c=5 & one argument missing float amount( int principal, int time, float rate=4);  amount(2000,5,3) // No argument missing.
  • 98.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 98 Some More programming….. : //program with default value #include<iostream.h> #include<conio.h> float amount( int , int , float r=0.5); int main(void) { amount(100,2); getch( ); return 0; } float amount( int p, int n, float r) { float amount; amount = p*n*r; // p =100,n=2 cout<<"total amt="<< amount; } // default value can be changed #include<iostream.h> #include<conio.h> float amount( int , int , float r=0.5); int main(void) { amount(100,2,0.8); getch( ); return 0; } float amount( int p, int n, float r) { float amount; amount = p*n*r; // p =100,n=2 cout<<"total amt="<< amount; }
  • 99.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 99 Assignment…find the errors..True/F 1. void Sum(int n1, n2, n3) {return n1+n2+n3; } 2. float average (int x, int y, int z) { float average; average= x + y + z /3; } 3. void area_rect ( int length=4, int breadth) { return length* breadth;} 4. void getValue( int read&) { cout<<“Enter a number”<< endl; cin>>read&; } 5. Function should be given the name that reflects the purpose.(T/F) 6. Function prototypes end with semicolon . ( T/ F) 7.When only a copy of an argument is passed to a function, it is said to be passed by ___________. 8. The __________ statement causes a function to end. :answer in next slide
  • 100.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 100 answers 1. Function declared is void, but returning a value, int must be for all variables 2. average=( x + y + z)/3.0; 3. Function declared is void, but returning a value, default value for breadth too. 4. Should be &read and not read&. 5. True 6. True 7. Value 8. return;
  • 101.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 101
  • 102.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 102 Procedure Oriented Programming (POP) • Procedural languages: BASIC :Beginner’s All-purpose Symbolic Instruction Code FORTRAN: Formula Translation COBOL : Common Business oriented language Pascal , C ….. •Problem viewed as sequence of things. •Each statement in the language tells the computer to do something. •List of instructions.
  • 103.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 103 Object oriented Programming(OOP) • Emphasis is on doing things (algorithms) • Large programs are divided into small programs known as functions. • Most of the functions share global data. • Combine both data & functions that operate on data into a single unit called object. • Functions ( methods ) provide the only way to access data • C++ programs consists of number of Objects which communicate with each other through member functions . • Data is hidden & safe from accidental modification.
  • 104.
    Slides by Mrs.Pai for Sem 6 (2016-2017) 104 Basic concepts of object oriented programming  Object - An object is a software bundle of variable & related methods.  Class - Fundamental building block of an object oriented program. - It is a collection of similar objects  Encapsulation -Wrapping up of data & functions into a single unit (called class) is known as encapsulation. -Data is not accessible to the outside world & only those functions, which are wrapped in the class, can access it. -This insulation of data from direct access by the program is called data hiding.  Inheritance - classes to be defined in terms of other classes.  Polymorphism -Ability to take more than one form.  Message passing -Software objects interact and communicate with each other by sending messages to each other.
  • 105.
    Referring, writing, checking,discussing & achieving perfection  Tony Gaddis  E. Balaguruswamy  Yashwant Kanitkar  D.Ravichandran #include<> void main() {clrscr(); int I, j; cout>>”.”; cin<<i; Slides by Mrs. Pai for Sem 6 (2016-2017) 105