Sunteți pe pagina 1din 54

Hyderabad Institute of Technology and

Management

FACULTY PRESENTATION
Dr. P. Ila Chandana Kumari
Professor
CSE
COURSE: OOPS T C++

23/09/20
© Copyrights 2018 HITAM. All rights reserved.
OOP Through C++ 1
1
Structure of C++ Program

• // my first program in C++


# include <iostream> # include <stdio.h>
main() main()
{ {
std::cout << "Hello World!"; printf ( “ Hello world”\n);
} }

23/09/20 OOP Through C++ 2


Structure of a C++ program
• // my second program in C++
#include <iostream>
int main ()
{
std::cout << "Hello World! ";
std::cout << "I'm a C++ program";
}

23/09/20 OOP Through C++ 3


Structure of a C++ program

# include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
}

23/09/20 OOP Through C++ 4


Data Types

23/09/20 OOP Through C++ 5


Variable Definition

• type variable_list; type variable_name = value;

• int i, j, k;
• char c, ch;
• float f, salary;
• double d;
• extern int d = 3, f = 5; // declaration of d and f.
• int d = 3, f = 5; // definition and initializing d and f.
• byte z = 22; // definition and initializes z.
• char x = 'x'; // the variable x has the value 'x'.

23/09/20 OOP Through C++ 6


Variable Scope
• Local Variable

• #include <iostream>
• using namespace std;
• int main ()
• {
• // Local variable declaration:
• int a, b;
• int c;
• // actual initialization
• a = 10;
• b = 20;
• c = a + b;
• cout << c;
• return 0;
• }

23/09/20 OOP Through C++ 7


Variable Scope
• Global Variable

• include <iostream>
• using namespace std;
• // Global variable declaration:
• int g;
• int main ()
• {
• // Local variable declaration:
• int a, b;
• // actual initialization
• a = 10;
• b = 20;
• g = a + b;
• cout << g;
• return 0;
• }

23/09/20 OOP Through C++ 8


Example variable Declaration program
#include <iostream> int main ()
using namespace std; {
extern int a, b; int a, b;
int c;
extern int c;
float f;
extern float f;
a = 10;
b = 20;
c = a + b;

cout << c << endl ;

f = 70.0/3.0;

cout << f << endl ;


return 0;
}
OOP Through C++ 9
Operators
• An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators
and provide the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
23/09/20 OOP Through C++ 10
Arithmetic Operator

23/09/20 OOP Through C++ 11


Relational Operator

23/09/20 OOP Through C++ 12


Logical Operators

23/09/20 OOP Through C++ 13


Bit Wise Operator

23/09/20 OOP Through C++ 14


Assignment Operator

23/09/20 OOP Through C++ 15


Misc Operators

23/09/20 OOP Through C++ 16


Operators Precedence

23/09/20 OOP Through C++ 17


Expressions
• Lvalues and Rvalues
• There are two kinds of expressions in C++ −
• lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as
either the left-hand or right-hand side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an
expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not
left-hand side of an assignment.
• Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues
and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −
• int g = 20; But the following is not a valid statement and would generate compile-time error −
• 10 = 20;

23/09/20 OOP Through C++ 18


Expression Evaluation

23/09/20 OOP Through C++ 19


Type Conversion
• A type cast is basically a conversion from one type to another. There are two types of type conversion:
• Implicit Type Conversion Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from the user.
• Generally takes place when in an expression more than one data type is present. In such condition type conversion
(type promotion) takes place to avoid lose of data.

• All the data types of the variables are upgraded to the data type of the variable with largest data type.

bool –> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double

• It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to
unsigned), and overflow can occur (when long long is implicitly converted to float).

23/09/20 OOP Through C++ 20


Type Conversion
• // An example of implicit conversion   // y implicitly converted to int. ASCII
    // value of 'a' is 97
• #include <iostream>     K = x + y;
• using namespace std;   
   
• main()   
• {     cout << “k = " << k << endl << "y = " << y << endl
•     int x = 10; // integer x
         
•     char y = 'a'; // character c
  
• int k;
    
}
  

23/09/20 OOP Through C++ 21


Type Conversion
• Explicit Type Conversion: This process is also called type casting and
it is user-defined. Here the user can typecast the result to make it of a
particular data type.In C++, it can be done by two ways:
• Converting by assignment: This is done by explicitly defining the
required type in front of the expression in parenthesis. This can be
also considered as forceful casting.Syntax:
• (type) expressionwhere type indicates the data type to which the final
result is converted.

23/09/20 OOP Through C++ 22


Type Conversion
• // C++ program to demonstrate
• // explicit type casting
•   
• #include <iostream>
• using namespace std;
•   
• int main()
• {
•     double x = 1.2;
•   
•     // Explicit conversion from double to int
•     int sum = (int)x + 1;
•   
•     cout << "Sum = " << sum;
•   
•     return 0;
• }

23/09/20 OOP Through C++ 23


Type Conversion
Example:
#include <iostream>
• Conversion using Cast operator: A Cast operator is using namespace std;
an unary operator which forces one data type to be int main()
converted into another data type.
C++ supports four types of casting: {
• Static Cast     float f = 3.5;
• Dynamic Cast   
• Const Cast     // using cast operator
• Reinterpret Cast     int b = static_cast<int>(f);
  
    cout << b;
}
Advantages of Type Conversion:
This is done to take advantage of certain features
of type hierarchies or type representations.
It helps to compute expressions containing
variables of different data types.
23/09/20 OOP Through C++ 24
Decision Making Statements

23/09/20 OOP Through C++ 25


• // C++ program to illustrate If statement
• #include<iostream>
• using namespace std;
•   
•     int main()
•     {
•         int i = 10;
•    
•         if (i > 15)
•         {
•            cout<<"10 is less than 15";
•         }    
•          
•         cout<<"I am Not in if";
•     }

23/09/20 OOP Through C++ 26


• // C++ program to illustrate if-else statement
• #include<iostream>
• using namespace std;
•   
• int main()
•  {
•         int i = 20;
•    
•         if (i < 15)
•             cout<<"i is smaller than 15";
•         else
•             cout<<"i is greater than 15";
•               
•     return 0;    
•  }

23/09/20 OOP Through C++ 27


• // C++ program to illustrate nested-if statement
• #include <iostream>
• using namespace std;
•   
• int main() 
•{
•     int i = 10;
•   
•     if (i == 10)
•     {
•         // First if statement
•         if (i < 15)
•            cout<<"i is smaller than 15\n";
•   
•         // Nested - if statement
•         // Will only be executed if statement above
•         // is true
•         if (i < 12)
•             cout<<"i is smaller than 12 too\n";
•         else
•             cout<<"i is greater than 15";
•     }
•   
•     return 0;
•}

23/09/20 OOP Through C++ 28


• // C++ program to illustrate if-else-if ladder
• #include<iostream>
• using namespace std;
•   
• int main()
•{
•     int i = 20;
•    
•     if (i == 10)
•         cout<<"i is 10";
•     else if (i == 15)
•         cout<<"i is 15";
•     else if (i == 20)
•         cout<<"i is 20";
•     else
•         cout<<"i is not present";
•}

23/09/20 OOP Through C++ 29


• Jump Statements in C/C++
• These statements are used in C orC++ for unconditional flow of
control through out the funtions in a program. They support four type
of jump statements:

break
• continue
• goto
• return

23/09/20 OOP Through C++ 30


• // CPP program to illustrate
• // Linear Search
• #include <iostream>
• using namespace std;
•   
• void findElement(int arr[], int size, int key)
•{
•     // loop to traverse array and search for key
•     for (int i = 0; i < size; i++) {
•         if (arr[i] == key) {
•             cout << "Element found at position: " << (i + 1);
•             break;
•         }
•     }
•}
•   
• // Driver program to test above function
• int main()
•{
•     int arr[] = { 1, 2, 3, 4, 5, 6 };
•     int n = 6; // no of elements
•     int key = 3; // key to be searched
•   
•     // Calling function to find the key
•     findElement(arr, n, key);
•   
•     return 0;
•}

23/09/20 OOP Through C++ 31


• // C++ program to explain the use
• // of continue statement
•   
• #include <iostream>
• using namespace std;
•   
• int main()
•{
•     // loop from 1 to 10
•     for (int i = 1; i <= 10; i++) {
•   
•         // If i is equals to 6,
•         // continue to next iteration
•         // without printing
•         if (i == 6)
•             continue;
•   
•         else
•             // otherwise print the value of i
•             cout << i << " ";
•     }
•   
•     return 0;
•}

23/09/20 OOP Through C++ 32


• // C++ program to print numbers
• // from 1 to 10 using goto statement
• #include <iostream>
• using namespace std;
•   
• // function to print numbers from 1 to 10
• void printNumbers()
•{
•     int n = 1;
• label:
•     cout << n << " ";
•     n++;
•     if (n <= 10)
•         goto label;
•}
•   
• // Driver program to test above function
• int main()
•{
•     printNumbers();
•     return 0;
•}

23/09/20 OOP Through C++ 33


• // C++ code to illustrate return
• // statement
• #include <iostream>
• using namespace std;
•   
• // non-void return type
• // function to calculate sum
• int SUM(int a, int b) 
• { 
•     int s1 = a + b;
•     return s1; 
• } 
•   
• // returns void
• // function to print
• void Print(int s2)
•{
•     cout << "The sum is "<< s2;
•     return;
•}
•   
• int main() 
• { 
•     int num1 = 10;
•     int num2 = 10;
•     int sum_of = SUM(num1, num2);
•     Print(sum_of);
•     return 0;
•}

23/09/20 OOP Through C++ 34


• C++ provides four iteration statements — while, do-while , for

• #include <iostream> using namespace std; int main () { // Local


variable declaration: int a = 10; // while loop execution while( a < 20 )
{ cout << "value of a: " << a << endl; a++; } return 0; }

23/09/20 OOP Through C++ 35


• #include <iostream> using namespace std; int main(){ int num=1;
do{ cout<<"Value of num: "<<num<<endl; num++; }while(num<=6);
return 0; }

23/09/20 OOP Through C++ 36


• #include <iostream> using namespace std; int main(){ for(int i=1;
i<=6; i++){ /* This statement would be executed * repeatedly until the
condition * i<=6 returns false. */ cout<<"Value of variable i is:
"<<i<<endl; } return 0; }

23/09/20 OOP Through C++ 37


• A function is block of code which is used to perform a particular task,
for example let’s say you are writing a large C++ program and in that
program you want to do a particular task several number of times,
like displaying value from 1 to 10, in order to do that you have to
write few lines of code and you need to repeat these lines every time
you display values. Another way of doing this is that you write these
lines inside a function and call that function every time you want to
display values. This would make you code simple, readable and
reusable.

23/09/20 OOP Through C++ 38


• Types of function
• We have two types of function in C++:

• 1) Built-in functions
2) User-defined functions

23/09/20 OOP Through C++ 39


• 1) Built-in functions
• Built-in functions are also known as library functions. We need not to declare
and define these functions as they are already written in the C++ libraries such
as iostream, cmath etc. We can directly call them when we need.
• Example: C++ built-in function example
• Here we are using built-in function pow(x,y) which is x to the power y. This
function is declared in cmath header file so we have included the file in our
program using #include directive.
• #include <iostream> #include <cmath> using namespace std; int main(){ /*
Calling the built-in function * pow(x, y) which is x to the power y * We are
directly calling this function */ cout<<pow(2,5); return 0; }
23/09/20 OOP Through C++ 40
• 2) User-defined functions
#include <iostream> #include <cmath> using namespace std;
//Declaring the function sum int sum(int,int); int main(){ int x, y;
cout<<"enter first number: "; cin>> x; cout<<"enter second number:
"; cin>>y; cout<<"Sum of these two :"<<sum(x,y); return 0; }
//Defining the function sum int sum(int a, int b) { int c = a+b; return
c; }

23/09/20 OOP Through C++ 41


Default Arguments in Functions
• #include <iostream> using namespace std; int sum(int a, int b=10, int
c=20); int main(){ /* In this case a value is passed as * 1 and b and c
values are taken from * default arguments. */
cout<<sum(1)<<endl; /* In this case a value is passed as * 1 and b
value as 2, value of c values is * taken from default arguments. */
cout<<sum(1, 2)<<endl; /* In this case all the three values are *
passed during function call, hence no * default arguments have been
used. */ cout<<sum(1, 2, 3)<<endl; return 0; } int sum(int a, int b, int
c){ int z; z = a+b+c; return z; }

23/09/20 OOP Through C++ 42


Valid and Invalid Default Arguments
• Valid: Following function declarations are valid –
• int sum(int a=10, int b=20, int c=30); int sum(int a, int b=20, int c=30);
int sum(int a, int b, int c=30);

• Invalid: Following function declarations are invalid –


• int sum(int a=10, int b, int c=30);
• int sum(int a, int b=20, int c);
• int sum(int a=10, int b=20, int c);

23/09/20 OOP Through C++ 43


Recursive Function
• The process in which a function calls itself is known as recursion and
the corresponding function is called the recursive function. The
popular example to understand the recursion is factorial function.
• Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) =
1. Don’t worry we wil discuss what is base condition and why it is
important.

23/09/20 OOP Through C++ 44


23/09/20 OOP Through C++ 45
• #include <iostream> using namespace std; //Factorial function int
f(int n){ /* This is called the base condition, it is * very important to
specify the base condition * in recursion, otherwise your program will
throw * stack overflow error. */    if (n <= 1)         return 1;    else       
return n*f(n-1); } int main(){ int num;   cout<<"Enter a number: ";  
 cin>>num;    cout<<"Factorial of entered number: "<<f(num); return
0; }

23/09/20 OOP Through C++ 46


Inline functions
• Inline function is one of the important feature of C++. So, let’s first understand why inline functions are
used and what is the purpose of inline function?
• When the program executes the function call instruction the CPU stores the memory address of the
instruction following the function call, copies the arguments of the function on the stack and finally
transfers control to the specified function. The CPU then executes the function code, stores the function
return value in a predefined memory location/register and returns control to the calling function. This can
become overhead if the execution time of function is less than the switching time from the caller function
to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the
function call is usually insignificant compared to the amount of time the function takes to run. However,
for small, commonly-used functions, the time needed to make the function call is often a lot more than
the time needed to actually execute the function’s code. This overhead occurs for small functions because
execution time of small function is less than the switching time.
• C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is
expanded in line when it is called. When the inline function is called whole code of the inline function gets
inserted or substituted at the point of inline function call. This substitution is performed by the C++
compiler at compile time. Inline function may increase efficiency if it is small.

23/09/20 OOP Through C++ 47


• Remember, inlining is only a request to the compiler, not a command.
Compiler can ignore the request for inlining. Compiler may not
perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return
statement doesn’t exist in function body.
5) If a function contains switch or goto statement.

23/09/20 OOP Through C++ 48


• Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when
function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context
specific optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows of calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems
because inline can yield less code than the function call preamble and
return.
23/09/20 OOP Through C++ 49
• Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining function if variables
number which are going to use register increases than they may create overhead on register variable resource utilization.
This means that when inline function body is substituted at the point of function call, total number of variables used by
the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if
after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization.
• 2) If you use too many inline functions then the size of the binary executable file will be large, because of the duplication
of same code.
• 3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from
that of cache memory to that of primary memory.
• 4) Inline function may increase compile time overhead if someone changes the code inside the inline function then all the
calling location has to be recompiled because compiler would require to replace all the code once again to reflect the
changes, otherwise it will continue with old functionality.
• 5) Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more
important than speed.
• 6) Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in
memory causes performance of computer to degrade.

23/09/20 OOP Through C++ 50


• #include <iostream>
• using namespace std;
• inline int cube(int s)
•{
•     return s*s*s;
•}
• int main()
•{
•     cout << "The cube of 3 is: " << cube(3) << "\n";
•     return 0;
• } //Output: The cube of 3 is: 27

23/09/20 OOP Through C++ 51


DOUBTS
CONCLUSION AS 1 MINUTE PAPER

• List the topic we learned today

23/09/20 OOP Through C++ 53

S-ar putea să vă placă și