SlideShare a Scribd company logo
1 of 16
Download to read offline
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
1 UNIT - 01 INTRUDUCTION
OBJECT ORIENTED PROGRAMMING WITH C++
UNIT – 01
INTRUDUCTION
Overview of C++, Sample C++ program, Different data types, operators, expressions, and
statements, arrays and strings, pointers & user defined types Function Components, argument
passing, inline functions, function overloading, recursive functions.
Overview of C++:
C++ began as an expanded version of C. The C++ extensions were first invented by
Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He
initially called the new language "C with Classes." However, in 1983 the name
was changed to C++. Although C was one of the most liked and widely
used professional programming languages in the world, the invention of C++
was necessitated by one major programming factor: increasing complexity.
Sample C++ program:
// my first program in C++
#include<iostream.h> output:
Using namespace std; Hello World!
I'm a C++ program
int main ()
{
cout <<"Hello World!"<<endl;
cout<< "I'm a C++ program";
return 0;
}
• // my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments
and do not have any effect on the behaviour of the program. The programmer can use them to
include short explanations or observations within the source code itself. In this case, the line
is a brief description of what our program is.
• #include <iostream>
Lines beginning with a hash sign (#) are directives for the pre-processor. They are not regular
code lines with expressions but indications for the compiler's pre-processor. In this case the
directive #include<iostream> tells the pre-processor to include the iostream standard file.
This specific file (iostream) includes the declarations of the basic standard input-output
library in C++, and it is included because its functionality is going to be used later in the
program.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
2 UNIT - 01 INTRUDUCTION
• using namespace std;
All the elements of the standard C++ library are declared within is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this
expression that we will be using these entities. This line is very frequent in C++ programs
that use the standard library.
• int main ()
This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of its
location within the source code. It does not matter whether there are other functions with
other names defined before or after it – the instructions contained within this function's
definition will always be the first ones to be executed in any C++ program. For that same
reason, it is essential that all C++ programs have a main function. The word main is followed
in the code by a pair of parentheses (()). Right after these parentheses we can find the body of
the main function enclosed in braces ({}). What is contained within these braces is what the
function does when it is executed.
• return 0;
The return instruction causes the main() function finish and return the code that the
instruction is followed by, in this case 0. This it is most usual way to terminate a program that
has not found any errors during its execution. As you will see in coming examples, all C++
programs end with a sentence similar to this.
Different data types:
When programming, we store the variables in our computer's memory, but the computer has
to know what kind of data we want to store in them, since it is not going to occupy the same
amount of memory to store a simple number than to store a single letter or a large number,
and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount
of memory that we can manage in C++. A byte can store a relatively small amount of data:
one single character or a small integer (generally an integer between 0 and 255). In addition,
the computer can manipulate more complex data types that come from grouping several
bytes, such as long numbers or non-integer numbers. Next you have a summary of the basic
fundamental data types in C++, as well as the range of values that can be represented with
each one. The values of the columns Size and Range depend on the system the program is
compiled for.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
3 UNIT - 01 INTRUDUCTION
Operators:
• Assignment Operator (=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
The assignation operator serves to assign a value to a variable.
a = 5;
assigns the integer value 5to variable a. The part at the left of the =operator is known as
lvalue(left value) and the right one as rvalue(right value). lvaluemust always be a variable
whereas the right side can be either a constant, a variable, the result of an operation or any
combination of them.
For example, if we take this code
int a, b; // a:? b:?
a = 10; // a:10 b:?
b = 4; // a:10 b:4
a = b; // a:4 b:4
b = 7; // a:4 b:7
will give us the result that the value contained in a is 4and the one contained in b is 7. The
final modification of b has not affected a.
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
price *= units + 1; is equivalent to price = price * (units + 1);
• Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the language are:
+ addition
- subtraction
* multiplication
/ division
% module
• Increment or Decrement Operator (++,--)
characteristic of this operator is that it can be used both as a prefix or as a suffix. That means
it can be written before the variable identifier (++a) or after (a++).
In case that the increase operator is used as a prefix (++a) the value is increased before the
expression is evaluated and therefore the increased value is considered in the expression; in
case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and
therefore the value stored before the increase operation is evaluated in the expression. Notice
the difference:
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A is 4, // A is 3,
B is 4 B is 4
In Example 1, B is increased before its value is copied to A. While in Example 2, the value of
B is copied to A and B is later increased.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
4 UNIT - 01 INTRUDUCTION
• Relational operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the Relational
operators. As specified by the C++ standard, the result of a relational operation is a bool
value that can only be true or false, according to the result of the comparison. We may want
to compare two expressions, for example, to know if they are equal or if one is greater than
the other. Here is a list of the relational operators that can be performed in C++:
== Equal
!= Different
> Greater than
< Less than
>= Greater or equal than
<= Less or equal than
Here you have some examples:
(7 == 5) would return false.
(5 > 4) would return true.
(3 != 2) would return true.
(6 >= 6) would return true.
(5 < 5) would return false.
of course, instead of using only numeric constants, we can use any valid expression,
including variables.
Suppose that a=2, b=3 and c=6,
(a == 5) would return false.
(a*b >= c) would return true since (2*3 >= 6) is it.
(b+4 > a*c) would return false since (3+4 > 2*6) is it.
((b=2) == a) would return true.
• Logic operators ( !, &&, || )
Operator ! is equivalent to boolean operation NOT, it has only one operand, located at its
right, and the only thing that it does is to invert the value of it, producing false if its operand
is true and true if its operand is false. It is like saying that it returns the opposite result of
evaluating its operand. For example:
!(5 == 5) returns false because the expression at its right (5 == 5) would be true.
!(6 <= 4) returns true because (6 <= 4) would be false.
!true returns false.
!false returns true.
Logic operators && and || are used when evaluating two expressions to obtain a single result.
They correspond with Boolean logic operations AND and OR respectively. The result of
them depends on the relation between its two operands:
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
5 UNIT - 01 INTRUDUCTION
For example:
( (5 == 5) && (3 > 6) ) returns false ( true && false ).
( (5 == 5) || (3 > 6)) returns true ( true || false ).
• Conditional operator ( ? :)
The conditional operator evaluates an expression and returns a different value according to
the evaluated expression, depending on whether it is true or false.
Its format is:
condition ? result1 : result2
if condition is true the expression will return result1, if not it will return result2.
7 == 5 ? 4 : 3 returns 3 since 7 is not equal to 5.
7 == 5 + 2 ? 4 : 3 returns 4 since 7 is equal to 5+2.
5 > 3 ? a : b returns a, since 5 is greater than 3.
a > b ? a : b returns the greater one, a or b.
• Bitwise Operators ( &, |, ^, ~, <<, >> )
Bitwise operators modify variables considering the bits that represent the values that they
store, that means, their binary representation.
• sizeof()
This operator accepts one parameter, that can be either a variable type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char);
This will return 1to a because char is a one byte long type. The value returned by sizeof is a
constant, so it is always determined before program execution.
Communication through console:
The console is the basic interface of computers, normally it is the set composed of the
keyboard and the screen. The keyboard is generally the standard input device and the screen
the standard output device.
In the iostream C++ library, standard input and output operations for a program are
supported by two data streams: cin for input and cout for output. Additionally, cerr and clog
have also been implemented - these are two output streams specially designed to show error
messages. They can be redirected to the standard output or to a log file. Therefore cout (the
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
6 UNIT - 01 INTRUDUCTION
standard output stream) is normally directed to the screen and cin (the standard input stream)
is normally assigned to the keyboard.
By handling these two streams you will be able to interact with the user in your
programs since you will be able to show messages on the screen and receive his/her input
from the keyboard.
• Output (cout)
The cout stream is used in conjunction with the overloaded operator << (a pair of "less than"
signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of variable x on screen
The << operator is known as insertion operator since it inserts the data that follows it into the
stream that precedes it. In the examples above it inserted the constant string Output sentence,
the numerical constant 120 and the variable x into the output stream cout. Notice that the first
of the two sentences is enclosed between double quotes (") because it is a string of characters.
Whenever we want to use constant strings of characters we must enclose them between
double quotes (") so that they can be clearly distinguished from variables.
For example, these two sentences are very different:
cout << "Hello"; // prints Hello on screen
cout << Hello; // prints the content of Hello variable on screen
The insertion operator (<<) may be used more than once in a same sentence:
cout << "Hello, " << "I am " << "a C++ sentence";
this last sentence would print the message Hello, I am a C++ sentence on the screen. The
utility of repeating the insertion operator (<<) is demonstrated when we want to print out a
combination of variables and constants or more than one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
If we supose that variable age contains the number 24 and the variable zipcode contains
90064 the output of the previous sentence would be:
Hello, I am 24 years old and my zipcode is 90064
It is important to notice that cout does not add a line break after its output unless we
explicitly indicate it, therefore, the following sentences:
cout << "This is a sentence.";
cout << "This is another sentence.";
will be shown followed in screen:
This is a sentence. This is another sentence.
even if we have written them in two different calls to cout. So, in order to perform a line
break on output we must explicitly order it by inserting a new-line character, that in C++ can
be written as n:
cout << "First sentence.n ";
cout << "Second sentence.nThird sentence.";
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
7 UNIT - 01 INTRUDUCTION
produces the following output:
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator.
For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
would print out:
First sentence.
Second sentence.
The endl manipulator has a special behavior when it is used with buffered streams: they are
flushed. But anyway cout is unbuffered by default.
You may use either the n escape character or the endl manipulator in order to specify a line
jump to cout. Notice the differences of use shown earlier.
• Input (cin)
Handling the standard input in C++ is done by applying the overloaded operator of extraction
(>>) on the cin stream. This must be followed by the variable that will store the data that is
going to be read. For example:
int age;
cin >> age;
declares the variable age as an int and then waits for an input from cin (keyborad) in order to
store it in this integer variable. cin can only process the input from the keyboard once the
RETURN key has been pressed. Therefore, even if you request a single character cin will not
process the input until the user presses RETURN once the character has been introduced.
You must always consider the type of the variable that you are using as a container
with cin extraction. If you request an integer you will get an integer, if you request a
character you will get a character and if you request a string of characters you will get a string
of characters.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
8 UNIT - 01 INTRUDUCTION
You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and another for variable b that
may be separated by any valid blank separator: a space, a tab character or a newline.
Functions:
A function is a block of instructions that is executed when it is called from some other point
of the program.
The following is its format:
type name ( argument1, argument2, ...) statement
where:
· type is the type of data returned by the function.
· name is the name by which it will be possible to call the function.
· arguments (as many as wanted can be specified). Each argument consists of a type of data
followed by its identifier, like in a variable declaration (for example, int x) and which acts
within the function like any other variable. They allow passing parameters to the function
when it is called. The different parameters are separated by commas.
· statement is the function's body. It can be a single instruction or a block of instructions. In
the latter case it must be delimited by curly brackets {}.
program always begins its execution with the main function. So we will begin there.
We can see how the main function begins by declaring the variable z of type int. Right
after that we see a call to addition function. If we pay attention we will be able to see the
similarity between the structure of the call to the function and the declaration of the function
itself in the code lines above:
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
9 UNIT - 01 INTRUDUCTION
The parameters have a clear correspondence. Within the main function we called to
addition passing two values: 5 and 3 that correspond to the int a and int b
parameters declared for the function addition.
At the moment at which the function is called from main, control is lost by main and
passed to function addition. The value of both parameters passed in the call (5 and 3) are
copied to the local variables int a and int b within the function.
Function addition declares a new variable (int r;), and by means of the expression
r=a+b;, it assigns to r the result of a plus b. Because the passed parameters for a and b
are 5 and 3 respectively, the result is 8.
The following line of code:
return (r);
Finalizes function addition, and returns the control back to the function that called it
(main) following the program from the same point at which it was interrupted by the call to
addition. But additionally, return was called with the content of variable r (return
(r);), which at that moment was 8, so this value is said to be returned by the function.
The value returned by a function is the value given to the function when it is evaluated.
Therefore, z will store the value returned by addition (5, 3), that is 8. To explain it
another way, you can imagine that the call to a function (addition (5,3)) is literally
replaced by the value it returns (8).
The following line of code in main is:
cout << "The result is " << z;
Overloaded functions / Function overloading
Two different functions can have the same name if the prototype of their arguments are
different, that means that you can give the same name to more than one function if they have
either a different number of arguments or different types in their arguments. For example,
In this case we have defined two functions with the same name, but one of them accepts two
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
10 UNIT - 01 INTRUDUCTION
arguments of type int and the other accepts them of type float. The compiler knows which
one to call in each case by examining the types when the function is called. If it is called with
two ints as arguments it calls to the function that has two int arguments in the prototype and
if it is called with two floats it will call to the one which has two floats in its prototype.
• Write a C++ program to swap two integers and to swap two floating point number
using function overloading concept.
//Program using pointer variable
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void swap(float *a,float *b)
{
float temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int m=10,n=20;
float x=90,y=9;
cout<<"swapping of integer no's"<<endl;
cout<<"befor swaping"<<endl;
cout<<"m value "<<m<<endl;
cout<<"n value "<<n<<endl;
swap(&m,&n);
cout<<"after swaping"<<endl;
cout<<"a value "<<m<<endl;
cout<<"b value "<<n<<endl; OUTPUT:
cout<<"swapping of floating poin no's"<<endl;
cout<<"befor swaping"<<endl;
cout<<"x value "<<x<<endl;
cout<<"y value "<<y<<endl;
swap(&x,&y);
cout<<"after swaping"<<endl;
cout<<"x value "<<x<<endl;
cout<<"y value "<<y<<endl;
}
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
3 UNIT - 01 INTRUDUCTION
Operators:
• Assignment Operator (=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
The assignation operator serves to assign a value to a variable.
a = 5;
assigns the integer value 5to variable a. The part at the left of the =operator is known as
lvalue(left value) and the right one as rvalue(right value). lvaluemust always be a variable
whereas the right side can be either a constant, a variable, the result of an operation or any
combination of them.
For example, if we take this code
int a, b; // a:? b:?
a = 10; // a:10 b:?
b = 4; // a:10 b:4
a = b; // a:4 b:4
b = 7; // a:4 b:7
will give us the result that the value contained in a is 4and the one contained in b is 7. The
final modification of b has not affected a.
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
price *= units + 1; is equivalent to price = price * (units + 1);
• Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the language are:
+ addition
- subtraction
* multiplication
/ division
% module
• Increment or Decrement Operator (++,--)
characteristic of this operator is that it can be used both as a prefix or as a suffix. That means
it can be written before the variable identifier (++a) or after (a++).
In case that the increase operator is used as a prefix (++a) the value is increased before the
expression is evaluated and therefore the increased value is considered in the expression; in
case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and
therefore the value stored before the increase operation is evaluated in the expression. Notice
the difference:
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A is 4, // A is 3,
B is 4 B is 4
In Example 1, B is increased before its value is copied to A. While in Example 2, the value of
B is copied to A and B is later increased.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
12 UNIT - 01 INTRUDUCTION
int add(int a,int b)
{
int c=a+b;
return (c);
}
int add(int a,int b,int c)
{ OUTPUT:
return (a+b+c);
}
float add(float x,float y)
{
return(x+y);
}
int main()
{
add();
cout<<"sum of 2 integer no's:"<<add(10,20)<<endl;
cout<<"sum of 3 integer no's:"<<add(100,30)<<endl;
float a=2,b=3;
cout<<"sum of 2 floating poin no's:"<<add(a,b);
}
• Write a program to find area of a rectangle, a square, a triangle and circle using
function overloading.
#include<iostream>
using namespace std;
int area(int length,int breadth)
{
return(length*breadth);
}
int area(int side)
{
return(side*side);
}
float area(float base, float height)
{
return(0.5*base*height);
}
float area(float radius)
{
return(3.14*radius*radius);
}
int main()
{
cout<<"area of a rectangle is:"<<area(10,20)<<endl;
cout<<"area of a square is:"<<area(30)<<endl; OUTPUT:
float a=10,b=20;
cout<<"area of a triangle is:"<<area(a,b)<<endl;
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
13 UNIT - 01 INTRUDUCTION
float x=3.5;
cout<<"area of a cirlce is:"<<area(x)<<endl;
}
Passing parameter to functions
• Pass by value (call by value):
In call-by-value, the argument expression is evaluated, and the resulting value is copied into
corresponding variable in the function. If the function is able to assign values to its
parameters, only its local copy is assigned. This means that anything passed into a function
call is unchanged in the caller's scope when the function returns.
#include<iostream>
using namespace std;
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int m=10,n=20;
cout<<"swapping of integer no's"<<endl;
cout<<"befor swaping"<<endl; OUTPUT:
cout<<"m value "<<m<<endl;
cout<<"n value "<<n<<endl;
swap(m,n);
cout<<"after swaping"<<endl;
cout<<"m value "<<m<<endl;
cout<<"n value "<<n<<endl;
}
• Pass-by-reference (call-by-reference):
In the strategy, a function receives a reference to the argument, rather than a copy of its value
The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the parameter affect the
passed argument.
This typically means that the function can modify the argument. Because arguments
do not need to be copied, call-by-reference has the advantage of greater time- and space-
efficiency as well as the potential for greater communication between a function and its caller
since the function can return information using its reference arguments.
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
14 UNIT - 01 INTRUDUCTION
#include<iostream>
using namespace std;
void swap(int &a , int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int m=10,n=20;
cout<<"swapping of integer no's"<<endl;
cout<<"befor swaping"<<endl;
cout<<"m value "<<m<<endl; OUTPUT:
cout<<"n value "<<n<<endl;
swap(m,n);
cout<<"after swaping"<<endl;
cout<<"m value "<<m<<endl;
cout<<"n value "<<n<<endl;
}
• Pass-by- address (call-by-address / call by pointer):
The call by pointer method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the passed argument.
To pass the value by pointer, argument pointers are passed to the functions just like
any other value. So accordingly you need to declare the function parameters as pointer types
as in the following function swap(), which exchanges the values of the two integer variables
pointed to by its arguments.
#include<iostream>
using namespace std;
void swap(int *a , int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int m=10,n=20;
float x=90,y=9;
cout<<"swapping of integer no's using pointers"<<endl;
cout<<"befor swaping"<<endl;
cout<<"m value "<<m<<endl;
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
15 UNIT - 01 INTRUDUCTION
cout<<"n value "<<n<<endl; OUTPUT:
swap(&m, &n);
cout<<"after swaping"<<endl;
cout<<"a value "<<m<<endl;
cout<<"b value "<<n<<endl;
}
Inline functions
There is an important feature in C++, called an inline function that is commonly used
with classes. In C++, you can create short functions that are not actually called;
rather, their code is expanded in line at the point of each invocation. This process
is similar to using a function-like macro. To cause a function to be expanded in
line rather than called, precede its definition with the inline keyword. For
example, in this program, the function max() is expanded in line instead of called:
#include<iostream>
using namespace std;
inline int max(int a,int b)
{
return (a>b?a:b);
}
int main()
{
Cout<<max(20,30);
Cout<<max(100,10);
Return 0;
}
Inline function is expanded whenever it is called,
#include<iostream>
using namespace std;
inline int max(int a,int b)
{
return (a>b?a:b);
}
int main() OUTPUT:
{
cout<<((20>30)?20:30)<<endl;
cout<<((100>10)? 100: 10)<<endl;
return 0;
}
OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE
16 UNIT - 01 INTRUDUCTION
Recursive functions
A Function calls by itself it called as recursive function.
Example for recursion function:
void recursion( )
{
recursion( );
}
int main( )
{
recursion( );
}
• Write a program to find factorial of given number using recursion.
#include<iostream>
using namespace std;
int fact(int n)
{
if(n==0 || n==1) OUTPUTS:
return 1;
else
return (n*fact(n-1));
}
int main()
{
int n;
cout<<"enter a number"<<endl;
cin>>n;
cout<<"factrorial("<<n<<")="<<fact(n);
}

More Related Content

What's hot

What's hot (20)

M C6java7
M C6java7M C6java7
M C6java7
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Chapter 9 python fundamentals
Chapter 9 python fundamentalsChapter 9 python fundamentals
Chapter 9 python fundamentals
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Python second ppt
Python second pptPython second ppt
Python second ppt
 
Data Handling
Data HandlingData Handling
Data Handling
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
M C6java3
M C6java3M C6java3
M C6java3
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
Python-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityPython-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutability
 
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++  Langauage Training in Ambala ! BATRA COMPUTER CENTREC++  Langauage Training in Ambala ! BATRA COMPUTER CENTRE
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTRE
 
C# String
C# StringC# String
C# String
 
Data file handling
Data file handlingData file handling
Data file handling
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
 

Similar to Oop with c++ notes unit 01 introduction

Similar to Oop with c++ notes unit 01 introduction (20)

C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
C program
C programC program
C program
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Basics of c++
Basics of c++ Basics of c++
Basics of c++
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
C Programming
C ProgrammingC Programming
C Programming
 
C++
C++ C++
C++
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
 
Mycasestudy
MycasestudyMycasestudy
Mycasestudy
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 

More from Ananda Kumar HN

VTU Network lab programs
VTU Network lab   programsVTU Network lab   programs
VTU Network lab programsAnanda Kumar HN
 
VTU CN-1important questions
VTU CN-1important questionsVTU CN-1important questions
VTU CN-1important questionsAnanda Kumar HN
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7Ananda Kumar HN
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)Ananda Kumar HN
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceAnanda Kumar HN
 
Microsoft office in kannada for begineers
Microsoft office in kannada for begineersMicrosoft office in kannada for begineers
Microsoft office in kannada for begineersAnanda Kumar HN
 
Microsoft office in KANNADA
Microsoft office in KANNADAMicrosoft office in KANNADA
Microsoft office in KANNADAAnanda Kumar HN
 

More from Ananda Kumar HN (11)

DAA 18CS42 VTU CSE
DAA 18CS42 VTU CSEDAA 18CS42 VTU CSE
DAA 18CS42 VTU CSE
 
CGV 18CS62 VTU CSE
CGV 18CS62 VTU CSECGV 18CS62 VTU CSE
CGV 18CS62 VTU CSE
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
 
VTU Network lab programs
VTU Network lab   programsVTU Network lab   programs
VTU Network lab programs
 
VTU CN-1important questions
VTU CN-1important questionsVTU CN-1important questions
VTU CN-1important questions
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit Inheritance
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 
Microsoft office in kannada for begineers
Microsoft office in kannada for begineersMicrosoft office in kannada for begineers
Microsoft office in kannada for begineers
 
Microsoft office in KANNADA
Microsoft office in KANNADAMicrosoft office in KANNADA
Microsoft office in KANNADA
 

Recently uploaded

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Recently uploaded (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Oop with c++ notes unit 01 introduction

  • 1. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 1 UNIT - 01 INTRUDUCTION OBJECT ORIENTED PROGRAMMING WITH C++ UNIT – 01 INTRUDUCTION Overview of C++, Sample C++ program, Different data types, operators, expressions, and statements, arrays and strings, pointers & user defined types Function Components, argument passing, inline functions, function overloading, recursive functions. Overview of C++: C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with Classes." However, in 1983 the name was changed to C++. Although C was one of the most liked and widely used professional programming languages in the world, the invention of C++ was necessitated by one major programming factor: increasing complexity. Sample C++ program: // my first program in C++ #include<iostream.h> output: Using namespace std; Hello World! I'm a C++ program int main () { cout <<"Hello World!"<<endl; cout<< "I'm a C++ program"; return 0; } • // my first program in C++ This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behaviour of the program. The programmer can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is. • #include <iostream> Lines beginning with a hash sign (#) are directives for the pre-processor. They are not regular code lines with expressions but indications for the compiler's pre-processor. In this case the directive #include<iostream> tells the pre-processor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.
  • 2. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 2 UNIT - 01 INTRUDUCTION • using namespace std; All the elements of the standard C++ library are declared within is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library. • int main () This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it – the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (()). Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is contained within these braces is what the function does when it is executed. • return 0; The return instruction causes the main() function finish and return the code that the instruction is followed by, in this case 0. This it is most usual way to terminate a program that has not found any errors during its execution. As you will see in coming examples, all C++ programs end with a sentence similar to this. Different data types: When programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C++. A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that come from grouping several bytes, such as long numbers or non-integer numbers. Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one. The values of the columns Size and Range depend on the system the program is compiled for.
  • 3. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 3 UNIT - 01 INTRUDUCTION Operators: • Assignment Operator (=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) The assignation operator serves to assign a value to a variable. a = 5; assigns the integer value 5to variable a. The part at the left of the =operator is known as lvalue(left value) and the right one as rvalue(right value). lvaluemust always be a variable whereas the right side can be either a constant, a variable, the result of an operation or any combination of them. For example, if we take this code int a, b; // a:? b:? a = 10; // a:10 b:? b = 4; // a:10 b:4 a = b; // a:4 b:4 b = 7; // a:4 b:7 will give us the result that the value contained in a is 4and the one contained in b is 7. The final modification of b has not affected a. value += increase; is equivalent to value = value + increase; a -= 5; is equivalent to a = a - 5; a /= b; is equivalent to a = a / b; price *= units + 1; is equivalent to price = price * (units + 1); • Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the language are: + addition - subtraction * multiplication / division % module • Increment or Decrement Operator (++,--) characteristic of this operator is that it can be used both as a prefix or as a suffix. That means it can be written before the variable identifier (++a) or after (a++). In case that the increase operator is used as a prefix (++a) the value is increased before the expression is evaluated and therefore the increased value is considered in the expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the expression. Notice the difference: Example 1 Example 2 B=3; B=3; A=++B; A=B++; // A is 4, // A is 3, B is 4 B is 4 In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and B is later increased.
  • 4. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 4 UNIT - 01 INTRUDUCTION • Relational operators ( ==, !=, >, <, >=, <= ) In order to evaluate a comparison between two expressions we can use the Relational operators. As specified by the C++ standard, the result of a relational operation is a bool value that can only be true or false, according to the result of the comparison. We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other. Here is a list of the relational operators that can be performed in C++: == Equal != Different > Greater than < Less than >= Greater or equal than <= Less or equal than Here you have some examples: (7 == 5) would return false. (5 > 4) would return true. (3 != 2) would return true. (6 >= 6) would return true. (5 < 5) would return false. of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6, (a == 5) would return false. (a*b >= c) would return true since (2*3 >= 6) is it. (b+4 > a*c) would return false since (3+4 > 2*6) is it. ((b=2) == a) would return true. • Logic operators ( !, &&, || ) Operator ! is equivalent to boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to invert the value of it, producing false if its operand is true and true if its operand is false. It is like saying that it returns the opposite result of evaluating its operand. For example: !(5 == 5) returns false because the expression at its right (5 == 5) would be true. !(6 <= 4) returns true because (6 <= 4) would be false. !true returns false. !false returns true. Logic operators && and || are used when evaluating two expressions to obtain a single result. They correspond with Boolean logic operations AND and OR respectively. The result of them depends on the relation between its two operands:
  • 5. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 5 UNIT - 01 INTRUDUCTION For example: ( (5 == 5) && (3 > 6) ) returns false ( true && false ). ( (5 == 5) || (3 > 6)) returns true ( true || false ). • Conditional operator ( ? :) The conditional operator evaluates an expression and returns a different value according to the evaluated expression, depending on whether it is true or false. Its format is: condition ? result1 : result2 if condition is true the expression will return result1, if not it will return result2. 7 == 5 ? 4 : 3 returns 3 since 7 is not equal to 5. 7 == 5 + 2 ? 4 : 3 returns 4 since 7 is equal to 5+2. 5 > 3 ? a : b returns a, since 5 is greater than 3. a > b ? a : b returns the greater one, a or b. • Bitwise Operators ( &, |, ^, ~, <<, >> ) Bitwise operators modify variables considering the bits that represent the values that they store, that means, their binary representation. • sizeof() This operator accepts one parameter, that can be either a variable type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will return 1to a because char is a one byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. Communication through console: The console is the basic interface of computers, normally it is the set composed of the keyboard and the screen. The keyboard is generally the standard input device and the screen the standard output device. In the iostream C++ library, standard input and output operations for a program are supported by two data streams: cin for input and cout for output. Additionally, cerr and clog have also been implemented - these are two output streams specially designed to show error messages. They can be redirected to the standard output or to a log file. Therefore cout (the
  • 6. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 6 UNIT - 01 INTRUDUCTION standard output stream) is normally directed to the screen and cin (the standard input stream) is normally assigned to the keyboard. By handling these two streams you will be able to interact with the user in your programs since you will be able to show messages on the screen and receive his/her input from the keyboard. • Output (cout) The cout stream is used in conjunction with the overloaded operator << (a pair of "less than" signs). cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of variable x on screen The << operator is known as insertion operator since it inserts the data that follows it into the stream that precedes it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and the variable x into the output stream cout. Notice that the first of the two sentences is enclosed between double quotes (") because it is a string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variables. For example, these two sentences are very different: cout << "Hello"; // prints Hello on screen cout << Hello; // prints the content of Hello variable on screen The insertion operator (<<) may be used more than once in a same sentence: cout << "Hello, " << "I am " << "a C++ sentence"; this last sentence would print the message Hello, I am a C++ sentence on the screen. The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables and constants or more than one variable: cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; If we supose that variable age contains the number 24 and the variable zipcode contains 90064 the output of the previous sentence would be: Hello, I am 24 years old and my zipcode is 90064 It is important to notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following sentences: cout << "This is a sentence."; cout << "This is another sentence."; will be shown followed in screen: This is a sentence. This is another sentence. even if we have written them in two different calls to cout. So, in order to perform a line break on output we must explicitly order it by inserting a new-line character, that in C++ can be written as n: cout << "First sentence.n "; cout << "Second sentence.nThird sentence.";
  • 7. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 7 UNIT - 01 INTRUDUCTION produces the following output: First sentence. Second sentence. Third sentence. Additionally, to add a new-line, you may also use the endl manipulator. For example: cout << "First sentence." << endl; cout << "Second sentence." << endl; would print out: First sentence. Second sentence. The endl manipulator has a special behavior when it is used with buffered streams: they are flushed. But anyway cout is unbuffered by default. You may use either the n escape character or the endl manipulator in order to specify a line jump to cout. Notice the differences of use shown earlier. • Input (cin) Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. This must be followed by the variable that will store the data that is going to be read. For example: int age; cin >> age; declares the variable age as an int and then waits for an input from cin (keyborad) in order to store it in this integer variable. cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you request a single character cin will not process the input until the user presses RETURN once the character has been introduced. You must always consider the type of the variable that you are using as a container with cin extraction. If you request an integer you will get an integer, if you request a character you will get a character and if you request a string of characters you will get a string of characters.
  • 8. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 8 UNIT - 01 INTRUDUCTION You can also use cin to request more than one datum input from the user: cin >> a >> b; is equivalent to: cin >> a; cin >> b; In both cases the user must give two data, one for variable a and another for variable b that may be separated by any valid blank separator: a space, a tab character or a newline. Functions: A function is a block of instructions that is executed when it is called from some other point of the program. The following is its format: type name ( argument1, argument2, ...) statement where: · type is the type of data returned by the function. · name is the name by which it will be possible to call the function. · arguments (as many as wanted can be specified). Each argument consists of a type of data followed by its identifier, like in a variable declaration (for example, int x) and which acts within the function like any other variable. They allow passing parameters to the function when it is called. The different parameters are separated by commas. · statement is the function's body. It can be a single instruction or a block of instructions. In the latter case it must be delimited by curly brackets {}. program always begins its execution with the main function. So we will begin there. We can see how the main function begins by declaring the variable z of type int. Right after that we see a call to addition function. If we pay attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself in the code lines above:
  • 9. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 9 UNIT - 01 INTRUDUCTION The parameters have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3 that correspond to the int a and int b parameters declared for the function addition. At the moment at which the function is called from main, control is lost by main and passed to function addition. The value of both parameters passed in the call (5 and 3) are copied to the local variables int a and int b within the function. Function addition declares a new variable (int r;), and by means of the expression r=a+b;, it assigns to r the result of a plus b. Because the passed parameters for a and b are 5 and 3 respectively, the result is 8. The following line of code: return (r); Finalizes function addition, and returns the control back to the function that called it (main) following the program from the same point at which it was interrupted by the call to addition. But additionally, return was called with the content of variable r (return (r);), which at that moment was 8, so this value is said to be returned by the function. The value returned by a function is the value given to the function when it is evaluated. Therefore, z will store the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by the value it returns (8). The following line of code in main is: cout << "The result is " << z; Overloaded functions / Function overloading Two different functions can have the same name if the prototype of their arguments are different, that means that you can give the same name to more than one function if they have either a different number of arguments or different types in their arguments. For example, In this case we have defined two functions with the same name, but one of them accepts two
  • 10. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 10 UNIT - 01 INTRUDUCTION arguments of type int and the other accepts them of type float. The compiler knows which one to call in each case by examining the types when the function is called. If it is called with two ints as arguments it calls to the function that has two int arguments in the prototype and if it is called with two floats it will call to the one which has two floats in its prototype. • Write a C++ program to swap two integers and to swap two floating point number using function overloading concept. //Program using pointer variable #include<iostream> using namespace std; void swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; } void swap(float *a,float *b) { float temp; temp=*a; *a=*b; *b=temp; } int main() { int m=10,n=20; float x=90,y=9; cout<<"swapping of integer no's"<<endl; cout<<"befor swaping"<<endl; cout<<"m value "<<m<<endl; cout<<"n value "<<n<<endl; swap(&m,&n); cout<<"after swaping"<<endl; cout<<"a value "<<m<<endl; cout<<"b value "<<n<<endl; OUTPUT: cout<<"swapping of floating poin no's"<<endl; cout<<"befor swaping"<<endl; cout<<"x value "<<x<<endl; cout<<"y value "<<y<<endl; swap(&x,&y); cout<<"after swaping"<<endl; cout<<"x value "<<x<<endl; cout<<"y value "<<y<<endl; }
  • 11. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 3 UNIT - 01 INTRUDUCTION Operators: • Assignment Operator (=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) The assignation operator serves to assign a value to a variable. a = 5; assigns the integer value 5to variable a. The part at the left of the =operator is known as lvalue(left value) and the right one as rvalue(right value). lvaluemust always be a variable whereas the right side can be either a constant, a variable, the result of an operation or any combination of them. For example, if we take this code int a, b; // a:? b:? a = 10; // a:10 b:? b = 4; // a:10 b:4 a = b; // a:4 b:4 b = 7; // a:4 b:7 will give us the result that the value contained in a is 4and the one contained in b is 7. The final modification of b has not affected a. value += increase; is equivalent to value = value + increase; a -= 5; is equivalent to a = a - 5; a /= b; is equivalent to a = a / b; price *= units + 1; is equivalent to price = price * (units + 1); • Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the language are: + addition - subtraction * multiplication / division % module • Increment or Decrement Operator (++,--) characteristic of this operator is that it can be used both as a prefix or as a suffix. That means it can be written before the variable identifier (++a) or after (a++). In case that the increase operator is used as a prefix (++a) the value is increased before the expression is evaluated and therefore the increased value is considered in the expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the expression. Notice the difference: Example 1 Example 2 B=3; B=3; A=++B; A=B++; // A is 4, // A is 3, B is 4 B is 4 In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and B is later increased.
  • 12. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 12 UNIT - 01 INTRUDUCTION int add(int a,int b) { int c=a+b; return (c); } int add(int a,int b,int c) { OUTPUT: return (a+b+c); } float add(float x,float y) { return(x+y); } int main() { add(); cout<<"sum of 2 integer no's:"<<add(10,20)<<endl; cout<<"sum of 3 integer no's:"<<add(100,30)<<endl; float a=2,b=3; cout<<"sum of 2 floating poin no's:"<<add(a,b); } • Write a program to find area of a rectangle, a square, a triangle and circle using function overloading. #include<iostream> using namespace std; int area(int length,int breadth) { return(length*breadth); } int area(int side) { return(side*side); } float area(float base, float height) { return(0.5*base*height); } float area(float radius) { return(3.14*radius*radius); } int main() { cout<<"area of a rectangle is:"<<area(10,20)<<endl; cout<<"area of a square is:"<<area(30)<<endl; OUTPUT: float a=10,b=20; cout<<"area of a triangle is:"<<area(a,b)<<endl;
  • 13. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 13 UNIT - 01 INTRUDUCTION float x=3.5; cout<<"area of a cirlce is:"<<area(x)<<endl; } Passing parameter to functions • Pass by value (call by value): In call-by-value, the argument expression is evaluated, and the resulting value is copied into corresponding variable in the function. If the function is able to assign values to its parameters, only its local copy is assigned. This means that anything passed into a function call is unchanged in the caller's scope when the function returns. #include<iostream> using namespace std; void swap(int a,int b) { int temp; temp=a; a=b; b=temp; } int main() { int m=10,n=20; cout<<"swapping of integer no's"<<endl; cout<<"befor swaping"<<endl; OUTPUT: cout<<"m value "<<m<<endl; cout<<"n value "<<n<<endl; swap(m,n); cout<<"after swaping"<<endl; cout<<"m value "<<m<<endl; cout<<"n value "<<n<<endl; } • Pass-by-reference (call-by-reference): In the strategy, a function receives a reference to the argument, rather than a copy of its value The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. This typically means that the function can modify the argument. Because arguments do not need to be copied, call-by-reference has the advantage of greater time- and space- efficiency as well as the potential for greater communication between a function and its caller since the function can return information using its reference arguments.
  • 14. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 14 UNIT - 01 INTRUDUCTION #include<iostream> using namespace std; void swap(int &a , int &b) { int temp; temp=a; a=b; b=temp; } int main() { int m=10,n=20; cout<<"swapping of integer no's"<<endl; cout<<"befor swaping"<<endl; cout<<"m value "<<m<<endl; OUTPUT: cout<<"n value "<<n<<endl; swap(m,n); cout<<"after swaping"<<endl; cout<<"m value "<<m<<endl; cout<<"n value "<<n<<endl; } • Pass-by- address (call-by-address / call by pointer): The call by pointer method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by pointer, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. #include<iostream> using namespace std; void swap(int *a , int *b) { int temp; temp=*a; *a=*b; *b=temp; } int main() { int m=10,n=20; float x=90,y=9; cout<<"swapping of integer no's using pointers"<<endl; cout<<"befor swaping"<<endl; cout<<"m value "<<m<<endl;
  • 15. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 15 UNIT - 01 INTRUDUCTION cout<<"n value "<<n<<endl; OUTPUT: swap(&m, &n); cout<<"after swaping"<<endl; cout<<"a value "<<m<<endl; cout<<"b value "<<n<<endl; } Inline functions There is an important feature in C++, called an inline function that is commonly used with classes. In C++, you can create short functions that are not actually called; rather, their code is expanded in line at the point of each invocation. This process is similar to using a function-like macro. To cause a function to be expanded in line rather than called, precede its definition with the inline keyword. For example, in this program, the function max() is expanded in line instead of called: #include<iostream> using namespace std; inline int max(int a,int b) { return (a>b?a:b); } int main() { Cout<<max(20,30); Cout<<max(100,10); Return 0; } Inline function is expanded whenever it is called, #include<iostream> using namespace std; inline int max(int a,int b) { return (a>b?a:b); } int main() OUTPUT: { cout<<((20>30)?20:30)<<endl; cout<<((100>10)? 100: 10)<<endl; return 0; }
  • 16. OBJECT ORIENTED PROGRAMMING WITH C++ ATMECE 16 UNIT - 01 INTRUDUCTION Recursive functions A Function calls by itself it called as recursive function. Example for recursion function: void recursion( ) { recursion( ); } int main( ) { recursion( ); } • Write a program to find factorial of given number using recursion. #include<iostream> using namespace std; int fact(int n) { if(n==0 || n==1) OUTPUTS: return 1; else return (n*fact(n-1)); } int main() { int n; cout<<"enter a number"<<endl; cin>>n; cout<<"factrorial("<<n<<")="<<fact(n); }