Introduction to Algorithms and flow charts by Dr.K. Bhaskerreddy
How to develop a program
Find the average of n numbers
Algorithm
Algorithm must be
Better way....
Pseudo Code START Read n Sum <- 0 For I <- 1 to n do Read number i Sum <- sum + number i End for Average <- sum/n Print average STOP
Flow chart
Component of a C++ Program by Dr.K. Bhaskerreddy
C++ Program structure /* * Multiple line * comment */ #include< iostream.h > //Single line comment //This is where the execution of program begins int main() { // displays Hello World! on screen cout <<"Hello World!"; return 0; }
A C++ program is structured in a specific and particular manner. In C++, a program is divided into the following three sections: Standard Libraries Section Main Function Section Function Body Section
Standard Library Section #include is a specific preprocessor command that effectively copies and pastes the entire text of the file, specified between the angular brackets, into the source code. The file < iostream >, which is a standard file that should come with the C++ compiler, is short for input-output streams. This command contains code for displaying and getting an input from the user.
Main Function The starting point of all C++ programs is the main function. This function is called by the operating system when your program is executed by the computer. { signifies the start of a block of code, and } signifies the end.
Function Body section The name cout is short for character output and displays whatever is between the << brackets. Symbols such as << can also behave like functions and are used with the keyword cout . The return keyword tells the program to return a value to the function. Ex: int main After the return statement, execution control returns to the operating system component that launched this program. Execution of the code terminates here.
Data Types in C ++
Datatypes/Types of variables Variables can be categorized based on their data type. int : These type of of variables holds integer value. char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc. bool: holds boolean value true or false. double: double-precision floating point value. float: Single-precision floating point value.
Basic Data Types Storage
Operators in C++
Operators in C++ In C++ most of the operators are binary operators i.e. these operators require two operands to perform an operation. Few operators like ++ (increment) operator are the unary operator which means they operate on one operand only. There is also a ternary operator in C++ called Conditional Operator which takes three operands(Will be discussed later).
Arithmetic Operators Operator Binary/unary Description + Binary Addition of two operands - Binary Subtraction of two operands * Binary Multiplication of two operands / Binary Division of two operands % Binary Modulus operator – the result is the remainder of the division ++ Unary Increment operator – increases the value of operand by 1 -- Unary Decrement operator – decreases the value of operand by 1
Increment and decrement operators The expression x++ is equivalent to x+=1; x = x+1; Similarly, the expression x—is equivalent to x -=1; x = x-1;
Example #include < iostream.h > #include< conio.h > void main() { clrscr (); int x=4,y; y = ++x; cout << " PreIncrement:Value of x = " <<x; cout << endl ; cout << " PreIncrement:Value of y = " <<y; cout << endl ; y = x--; cout << " PostDecrement:Value of x = " <<x; cout << endl ; cout << " PostDecrement:Value of y = " <<y; cout << endl ; getch (); } Output: PreIncrement:Value of x = 5 PreIncrement:Value of y = 5 PostDecrement:Value of x = 4 PostDecrement:Value of y = 5
Logical Operators Operator Example Meaning && expression1 && expression 2 Logical AND. true only if all the operands are true. || expression1 || expression 2 Logical OR. true if at least one of the operands is true. ! ! expression Logical NOT. true only if the operand is false.
AND Operator && a b a && b 1 1 1 1 1
OR Operator || a b a || b 1 1 1 1 1 1 1
Not Operator !
Relational Operators Operator Meaning Example == Is Equal To 3 == 5 gives us false != Not Equal To 3 != 5 gives us true > Greater Than 3 > 5 gives us false < Less Than 3 < 5 gives us true >= Greater Than or Equal To 3 >= 5 give us false <= Less Than or Equal To 3 <= 5 gives us true A relational operator is used to check the relationship between two operands. For example, // checks if a is greater than b a > b;
== Operator The equal to == operator returns true - if both the operands are equal or the same false - if the operands are unequal For example, int x = 10; int y = 15; int z = 10; x == y // false x == z // true != Operator The not equal to != operator returns true - if both operands are unequal false - if both operands are equal. For example, int x = 10; int y = 15; int z = 10; x != y // true x != z // false > Operator The greater than > operator returns true - if the left operand is greater than the right false - if the left operand is less than the right For example, int x = 10; int y = 15; x > y // false y > x // true
< Operator The less than operator < returns true - if the left operand is less than the right false - if the left operand is greater than right For example, int x = 10; int y = 15; x < y // true y < x // false >= Operator The greater than or equal to >= operator returns true - if the left operand is either greater than or equal to the right false - if the left operand is less than the right For example, int x = 10; int y = 15; int z = 10; x >= y // false y >= x // true z >= x // true <= Operator The less than or equal to operator <= returns true - if the left operand is either less than or equal to the right false - if the left operand is greater than right For example, int x = 10; int y = 15; x > y // false y > x // true
Input Output Statements in c++ cin and cout are two predefined objects which represent standard input and output stream. The standard output stream represents the screen, while the standard input stream represents the keyboard. These objects are members of iostream class. Hence the header file < iostream.h > should be included in the beginning of all programs. #include void main() { int i ; //Declaration statement cin >> i ; //Input statement cout << i ; //Output statement } The operator << is called the insertion operator and the operator >> is called the extraction operator.
Cascading of I/O Operators It is possible to use the insertion and extraction operators repeatedly in cin and cout statements. Multiple use of these operators is called Cascading. For example, the extraction operator can be cascaded as follows: cout << b1<<” “<<b2; This statement sends firsts the value of b1 to cout , two blank spaces and then the value of b2 to cout . The insertion operator can be cascaded as follows: cin >> val1>>val2; The values are assigned from left to right.
Input Operator The input operator, commonly known as the extraction operator (>>), is used with the standard input stream, cin . As stated earlier, cin treats data as a stream of characters. These characters flow from cin to the program through the input operator. The input operator works on two operands, namely, the c in stream on its left and a variable on its right. Thus, the input operator takes (extracts) the value through cin and stores it in the variable. To understand the concept of an input operator, consider this example. A program to demonstrate the working of an input operator. #include< iostream.h > int main () { int a; cin >>a; a = a+1; return 0; } In this example, the statement cin >> a takes an input from the user and stores it in the variable a.
Output Operator The output operator, commonly known as the insertion operator (<<), is used. The standard output stream cout Like cin cout also treats data as a stream of characters. These characters flow from the program to cout through the output operator. The output operator works on two operands, namely, the cout stream on its left and the expression to be displayed on its right. The output operator directs (inserts) the value to cout .
Output Operator #include< iostream.h > int main () { int a; cin >>a; a=a+1; cout <<a; return 0; } This example is similar to Example 1. The only difference is that the value of the variable a is displayed through the instruction cout << a .
Expression An expression is a combination of operators, constants and variables. An expression may consist of one or more operands, and zero or more operators to produce a value. Ex: a+b *c Types of Expressions: Constant expressions Integral expressions Constant expressions : Constant Expressions consists of only constant values. A constant value is one that doesn’t change. Examples : 5, 10 + 5 / 6.0, 'x’ Constant expressions : Constant Expressions consists of only constant values. A constant value is one that doesn’t change. Examples : 5, 10 + 5 / 6.0, 'x’
Types of Expressions: Constant expressions : Constant Expressions consists of only constant values. A constant value is one that doesn’t change. Examples : 5, 10 + 5 / 6.0, 'x’ Integral expressions : Integral Expressions are those which produce integer results after implementing all the automatic and explicit type conversions. Examples : x, x * y, x + int( 5.0) where x and y are integer variables.
Integral expressions : Integral Expressions are those which produce integer results after implementing all the automatic and explicit type conversions. Examples : x , x * y, x + int ( 5.0) where x and y are integer variables.
Floating expressions : Float Expressions are which produce floating point results after implementing all the automatic and explicit type conversions. Examples : x + y, 10.75 where x and y are floating point variables.
Relational expressions : Relational Expressions yield results of type bool which takes a value true or false. When arithmetic expressions are used on either side of a relational operator, they will be evaluated first and then the results compared. Relational expressions are also known as Boolean expressions. Examples : x <= y, x + y > 2
Logical expressions : Logical Expressions combine two or more relational expressions and produces bool type results. Examples : x > y && x == 10, x == 10 || y == 5
Bitwise expressions : Bitwise Expressions are used to manipulate data at bit level. They are basically used for testing or shifting bits. Examples: x << 3 shifts three bit position to left y >> 1 shifts one bit position to right.
Preprocessing A Preprocessor is a program that processes the source code before it is passed through the compiler. To handle preprocessing we have several commands.These commands are known as Preprocessor commands or Preprocessor directives. Every Preprocessor directive begins with a symbol hash(#). We have the following categories of Preprocessor directives: 1.Macro Expansion 2.File inclusion 3.Conditional Compilation
Macro Expansion Example: #include<iostream.h> #include<conio.h> #define PI 3.14 void main() { clrscr(); int r,a; cout<<“Enter radius of a circle:"; Cin>>r; A=PI*r*; cout<<" Area is: "<<A; getch(); }
Macro Expansion PI: Macro template/ Macro name 3.14: Macro expansion/ Macro value When we are using macros every occurrence of the macro template will be replaced by its value. This replacement is done during preprocessing i.e , before compilation only. By using macros wee can provide more clarity to the program. Generally the macro names are written in uppercase letters.
File Inclusion To include the contents of one file into another we will use a pre-processor directive called ‘#include’ and we can use this directive in two ways: 1)#include<filename> 2) # include”filename ” Note: While including the standard header files we will use angular brackets and while including the user defined files we will use double quotes.
Conditional Compilation In conditional compilation we may check some condition then based on the result of this condition we may compile some part of the program or we won’t compile some part of the program.
Conditional Compilation While using # ifdef , if the macro is defined then it will compile the statements between # ifdef and #else otherwise it will compile the statements between #else and # endif . The # endif is used to signify the end of # ifdef .
Unit-2:Control Statements By default the statements in a program are executed in sequential order from top to bottom. The control statements are used to control the flow of the program. we have the following types of control statements Sequence control statements Decision control statements Loop control statements
Decision control statements These statements are used to implement decisions. To handle these statements we may use the following: If statement Switch statement Conditional operator
If statement The ‘if’ statement is used to express the decisions. We can use the ‘if’ statement in several forms: 1 st form: Syntax: if(condition) statement; In the above form, the statement is executed only if the condition is true. Otherwise, the statement is not executed.
If statement 2 nd form: Syntax: if(condition) { statement1; statement2; . statement n; } In the above form, the statements is executed only if the condition is true. Otherwise, the statements is not executed.
If statement 3 rd form: Syntax: if(condition) statement1; else statement2; In the above form, the statement1 is executed only if the condition is true. Otherwise, the statements2 is not executed.
Switch statement Synatax : switch(char/ int expression) { case constant1: statement1; case constant1: statement2; case constantn : statementn ; default: deaault statement; }
Switch statement In the above syntax constant1, constant2,….. constantn are known as case labels, case labels must be constant expressions(char/ int ) only and case labels must be distinct. In switch, first it evaluates the integer expression. Then this value is compared with every case label. If there is a match then it will execute the statements from that case label upto break statement or upto end of switch. If there is a no match then it will execute the default statements
Conditional operator Syntax:condition?expression1:expression2 First it will check the condition. If the condition is true then it will evaluate expression 1and it will return the value of expression1. otherwise it will evaluate expression 2 and it will return the value of expression2.
Loop control statements The loops are used to execute a se of statements repeatedly. In C++ we have the following looping statements: 1)While loop 2) do- while loop 3) For loop
While loop Syntax: while(condition) Statement; The statement is executed repeatedly as long as the condition is true. Once the condition is false then the loop is terminated.
Do While loop Syntax: do { Statement; } while(condition); The statement is executed repeatedly as long as the condition is true. Once the condition is false then the loop is terminated.
for loop Syntax: for( initialization;condition ; increment/decrement) Statement;
Break, Continue and goto statements The break statement is used to terminate the loop. i.e on executing break statement the control comes out of the loop immediately. The continue statement is used to skip the current iteration of the loop. In case of while/do-while, the continue statement will transfer the control to the conditional expression but in for loop ,it will transfer the control to the increment/decrement operation. Goto is a jump statement i.e by using goto statement we can transfer the control to any where within the program.
goto Statement Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); int n; START:cout<<“type a number:”; Cin>>n; If(n!=0) goto START; getch(); }
UNIT-3: Arrays & Strings An array is nothing but collection of similar elements, which are accessed by a common name Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[5]; int i; cout<<“enter elemnets”; for( i =0;i<=4; i ++) cin >>a[ i ]; cout<<“The elemnets are”; for( i =0;i<=4; i ++) cout <<a[ i ]; getch(); }
Arrays By using arrays we can group similar quantities only When we are declaring an array we must specify the size of the array and this size must be a constant integral expression only. The array elements are placed in consecutive memory locations only. To refer the array elements we will use the position of the element in the given array, which is known as subscript or index. In arrays the first element has a subscript 0 and the the last element has a subscript (n-1) where n is the size of the array.
Initializing arrays When we are initializing an array at the time of declaration giving the array size is optional. #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[]={10,20,30,40,50}; int i; Cout<<“The elemnets are”; for( i =0;i<=4; i ++) cout <<a[ i ]; getch(); }
Program to find the sum of elements in array #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[5]; int i,sum=0; cout<<“enter elemnets”; for( i =0;i<=4; i ++) cin >>a[ i ]; for( i =0;i<=4; i ++) Sum= sum+a [ i ]; cout<<sum; getch(); }
Arrays Q:wap to Find the largest and smallest number in array? Q:wap to delete an element at the specified position in array? Q:wap to display the array elements in reverse order?
Bubble Sort #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[5] ={5,4,3,2,1}; for( i =0;i<4; i ++) { for(j=0;j<4; j++ ) { if(a[j]>a[j+1]) { int temp= a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } for( i =0;i<=4; i ++) cout <<a[ i ]<<“\n”; getch(); }
2 dimensional Arrays(Matrices) We can have single-dimensional arrays as well as multi dimensional arrays. In case of single dimensional arrays we will use only one subscript but in case of two dimensional arrays we need to use two subscripts and so on. Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[5][6]; int i,j; cout<<“enter elemnets”; for( i =0;i<=4; i ++) { for(j=0;j<=4; j++ ) cin >>a[ i ][j];} cout<<“The elemnets are”; for( i =0;i<=4; i ++) { for(j=0;j<=4; j++ ) cout <<a[ i ][j];} getch(); }
Program for Matrix Multiplication #include < iostream > using namespace std ; int main(){ int a[5][6],b[5][6],c[5][6]; int i,j,k,sum =0; cout <<"enter elemnets "; for( i =0;i<=2; i ++){ for(j=0;j<=2; j++ ) cin >>a[ i ][j];} cout <<"enter elemnets "; for( i =0;i<=2; i ++){ for(j=0;j<=2; j++ ) cin >>b[ i ][j];} for( i =0;i<=2; i ++){ for(j=0;j<=2; j++ ) { int sum=0; for(k=0;k<=2; k++) sum= sum+a [ i ][k]*b[k][j]; c[ i ][j]=sum;}} for( i =0;i<=2; i ++){ for(j=0;j<=2; j++ ) cout <<c[ i ][j]<<"\t"; cout << endl ;} return 0;}
Initializing 2 dimensional Arrays We can have single-dimensional arrays as well as multi dimensional arrays.In case of single dimensional arrays we will use only one subscript but in case of two dimensional arrays we need toi use two subscripts and so on. Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[3][6]={{1,2,3},{4,5,6}}; int i,j; cout<<“The elemnets are”; for( i =0;i<=1; i ++) { for(j=0;j<=3; j++ ) cout <<a[ i ][j];} getch(); }
Program to find sum of the matrix elements We can have single-dimensional arrays as well as multi dimensional arrays.In case of single dimensional arrays we will use only one subscript but in case of two dimensional arrays we need toi use two subscripts and so on. Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[3][6]={{1,2,3},{4,5,6}}; int i,j,sum=0; cout<<“The elemnets are”; for( i =0;i<=1; i ++) { for(j=0;j<=3; i ++) Sum= sum+a [ i ][j];} cout<<“The elemnets sum is:”<<sum; getch(); }
Problems on 2D WAP to find the trace of a matrix WAP to find the trace of a matrix WAP to find the transpose of a matrix
Strings A string is a character array, which is terminated by a null character(\0) Example: #include<iostream.h> #include<conio.h> void main() { clrscr(); char str[6]={‘A’,’B’,’C’,’\0’}; int i=0; cout<<“The string is:”; while( str [ i ]!=‘\0’) { cout << str [ i ]; i ++;} getch(); }
Program to find the length of the string #include<iostream.h> #include<conio.h> void main() { clrscr(); char str[6]={‘A’,’B’,’C’,’\0’}; int i=0; while( str [ i ]!=‘\0’) i ++; cout << “length of string is:”<< i ; getch(); }
String Functions To work with strings C ++ provides the following string functions that are available in the header file< string.h > 1.strlen():It is used to find the no.of characters in a given string. It won’t count the terminating null character. Example: #include<iostream.h> #include<conio.h> void main() { clrscr (); char s1[25]; cout << “Enter your name: ”; cin >> s1; cout << “ strlen ( s1 ): ” << strlen ( sl ) << endl ; getch (); }
String Functions 2.strcpy():It is used to copy one string into another i.e., it copies the source string into destination. Example: #include<iostream.h> #include<conio.h> void main() { clrscr (); char s1[25], s2[25]; cout << “Enter a string: ”; cin >> s1; strcpy ( s2, s1 ); cout << “ strcpy ( s2, s1 ): ” << s2; getch (); }
String Functions 3.strcat():It is used to concatenate two strings i.e., it copies the source string into destination. Example: #include<iostream.h> #include<conio.h> void main() { clrscr (); char s1[40], s2[25]; cout << “Enter string s1: ”; cin >> s1; cout << “Enter string s2: ”; cin >> s2; strcat ( s1, s2 ); cout << “ strcat ( s1, s2 ): ” << s1; getch (); }
String Functions 4.strcmp():It is used to compare two strings i.e., if the strings are equal then it will return a value 0. Example: #include<iostream.h> #include<conio.h> void main() { clrscr (); char s1[25], s2[25]; cout << “Enter string s1: ”; cin >> s1; cout << “Enter string s2: ”; cin >> s2; int status = strcmp ( s1, s2 ); cout << “ strcmp ( s1, s2 ): ”; if( status == 0 ) cout << s1 << “ is equal to ” << s2; else cout << s1 << “ is not equal to ” << s2; getch (); }
Unit-4: Modular Programming: Functions In every C/C ++ program we will use a function called main() and only one main().The main() function indicates the starting point of the program execution. i.e without main(), we can compile the program but we can’t execute the program. A C/C ++ program is a collection of several functions. we need to write every executable statement inside some function only. A block is a section of code A function is a block of code, which has been written to solve a specific task.
Functions Example1: #include<iostream.h> #include<conio.h> void main() -------------> Function calling { Void display(); -------------> Function Prototype clrscr(); cout << “I am in Main”<<“\n”; display();-------------> Function calling cout << “I am back in Main”<<“\n”; getch(); } Void display() -------------> Called Function { cout << “I am in display”<<“\n”; ------------> Function definition }
Functions Through function definition we will write the code to solve the given problem Through function calling we are executing the code which is present in the function definition. Example2: #include<iostream.h> #include<conio.h> void main() { Void display(); clrscr(); display(); display(); getch(); } Void display() { cout << “I am in display”<<“\n”; } We can define the function only once but we can call that function any number of times within the program.
Advantages of functions We can eliminate the repetition of the code. If we divide the program into several functions then understanding the program is easier.
Functions Example3: #include<iostream.h> #include<conio.h> void main() {void display1(); Void display2(); clrscr(); display1(); display2(); getch(); } Void display2() { cout << “I am in display2”<<“\n”; } Void display1() { cout << “I am in display1”<<“\n”; } The order of function calls and the order of functions definitions need not to be same.
Functions Example4: #include<iostream.h> #include<conio.h> void main() {void display1(); Void display2(); clrscr(); cout << “I am in Main”<<“\n”; display1();-------------> Function calling cout << “I am back in Main”<<“\n”; getch(); } Void display1() { cout << “I am in display1”<<“\n”; display2(); cout << “I am back in display1”<<“\n”; } Void display2() { cout << “I am in display2”<<“\n”; } We can call a function from a called function which is known as nesting of functions.
Functions We have two types of functions 1.Library functions ( strlen () , strcat() etc ) 2. User defined functions (display1() ,display2() etc ) The main() function is a user defined function only. The main() function is automatically called by the operating system.
Program to find sum of two integers #include<iostream.h> #include<conio.h> void main() { int sum( int x, int y); clrscr(); int x=10,y=20; s=sum( x,y );----- here x,y are called actual arguments cout <<“sum is:”<<s; getch(); } int sum( int x, int y) ----- here x,y are called formal parameters { int c; c= x+y ; return c; }
Functions Write a program to find area of a circle using functions Write a program to find the sum of first n natural numbers using functions Write a program to find factorial of a giving integer using functions
Inline functions If there is any function having “inline” in front of function and that function’s is code is substituted in place of its functions call. Means if we are calling any inline function from main(),then the code will be substituted and executed within main. By using inline functions we can increase the execution speed.
Inline functions #include<iostream.h> #include<conio.h> inline float square(float x) ----- here x is called formal parameters { x=x*x; return x; } void main() { clrscr(); float num; cout <<“enter a number:”; cin >> num ; cout <<“it’s square is:”<<square( num ); getch(); }
Macro functions While using macros with arguments we can’t provide type checking. While using macros with arguments the size of the program may be increased. This is because every call of the macro will be replaced by its definition While using macros with arguments the program works faster. This is because by using macros with arguments we can eliminate the function call overhead. The macros are handled by the preprocessor where as the functions are handled by the compiler.
RECURSION In c++ , a function can call itself. This process is called recursion.
Program to find factorial of a given integer #include<iostream.h> #include<conio.h> void main() { int fact( int x); clrscr(); int x=5; s=fact(x);----- here x,y are called actual arguments cout <<“factorial is:”<<s; getch(); } int fact( int x) ----- here x,y are called formal parameters { int c; if(x==0) return 1; c=x*fact(x-1); return c; }
Program to find factorial of a given integer #include<iostream.h> #include<conio.h> void main() { int fact( int x); clrscr(); int x=5; s=fact(x);----- here x,y are called actual arguments cout <<“factorial is:”<<s; getch(); } int fact( int x) ----- here x,y are called formal parameters { int c; if(x==0) return 1; else return x*fact(x-1); }
Program to find sum of first n natural numbers #include<iostream.h> #include<conio.h> void main() { int sum( int x); clrscr(); int x=5; s=sum(x);----- here x,y are called actual arguments cout <<“sum is:”<<s; getch(); } int sum( int x) ----- here x,y are called formal parameters { int c; if(x==1) return 1; else return x+sum (x-1); }
Pointers The unary ampersand (&) is known as “address of” operator. It gives address of a variable, which is present in memory. The unary asterisk (*) is known as “value at address” operator. It gives value at the specified address of a variable. A pointer is a variable that holds an address If the pointer contains address of a integer variable then it is known as a integer pointer. Every type of pointer variable will use two bytes memory only.
pointers While declaring pointers we will use asterisk (*) as follows Ex: int * i ; Here “ i ” is an integer pointer and it contains address of an integer variable only.
pointers #include<iostream.h> #include<conio.h> void main() {clrscr(); int i=10; cout << “Address of i is:”<<& i ; cout <<value of i is << i ; cout <<value of i is <<*(& i ); getch(); }
pointers #include<iostream.h> #include<conio.h> void main() {clrscr(); int i=10; int * j; j=&i; cout << “Address of i is:”<<j; cout <<value of i is <<*(j); getch(); }
Pointer to ponter #include<iostream.h> #include<conio.h> void main() {clrscr(); int i=10; int * j=&i; int ** k=&j; cout << “Address of i is:”<<*k; cout <<value of i is <<**(k); getch(); }
Functions and pointers Passing arguments to a function: 1)call by value/pass by value: In this method the values of the actual arguments in the calling function are copied into corresponding formal parameters of the called function. If we make any changes to the formal parameters these changes will not reflect to the actual arguments. 2)call by reference/ pass by reference: In this method the addresses of the actual arguments in the calling function are copied into corresponding formal parameters of the called function. By using these addresses we can make changes to the actual arguments.
Functions and pointers:call by value #include<iostream.h> #include<conio.h> void main() {void swap( int , int ); clrscr(); int x=10, y=20; cout <<“Before swaping :”<<x<<y; swap( x,y );----- here x,y are called actual arguments cout <<“After swaping :”<<x<<y; getch(); } void swap( int x, int y) ----- here x,y are called formal parameters { int c; c=x; x=y; y=c; }
Functions and pointers: call by reference #include<iostream.h> #include<conio.h> void main() {void swap( int &x, int &y ); clrscr(); int x=10, y=20; cout <<“Before swaping :”<<x<<y; swap( x,y );----- here x,y are called actual arguments cout <<“After swaping :”<<x<<y; getch(); } void swap( int &x, int & y) ----- here x,y are called formal parameters { int c; c=x; x=y; y=c; }
Functions and pointers: call by address #include<iostream.h> #include<conio.h> void main() {void swap( int *, int * ); clrscr(); int x=10, y=20; cout <<“Before swaping :”<<x<<y; swap(& x,&y );----- here x,y are called actual arguments cout <<“After swaping :”<<x<<y; getch(); } void swap( int *x, int *y) ----- here x,y are called formal parameters { int c; c=*x; *x=*y; *y=c; }
Structures A structure is a user defined data type that combines different data types into a single unit. By using structures we can provide more clarity and also we can simplify the program. Through structure declaration we are creating a new data type only.It won’t allocate any memory space at this stage. The memory will be allocated while creating a variable for the structure. The size of the structure variable is equal to the sum of sizes of it’s members. To refer the structure members through a structure variable we will use dot(.) operator
Structures #include<iostream.h> #include<conio.h> void main() { struct book { int code; char name[20];}; struct book b; clrscr(); cout <<“Enter book detaails :”; Cin >> b.code ; Cin >>b.name; cout <<“The book detaails :”; Cout << b.code ; Cout <<b.name; getch(); }
Initializing Structures #include<iostream.h> #include<conio.h> void main() { struct book { int code; char name[20];}; struct book b={101, “C++”}; clrscr(); cout <<“The book detaails :”; Cout << b.code ; Cout <<b.name; getch(); } When we are initializing a structure variable at the time of declaration we need to supply the values in the same order in which the structure is declared.
structures WAP to create a structure called “date” to represent the date and increment the date by one day. WAP to create a structure called “time” to represent the time and increment the date by one second. WAP to create a structure called “point” to represent the XY-plane and find distance between two points.
Pointers to structures We can store the address of a structure variable in a pointer, which is known as pointer to a structure. To refer the structure members through a structure pointer we will use arrow (->) operator.
Pointers to structures #include<iostream.h> #include<conio.h> void main() { struct book { int code; char name[20];}; struct book b; Struct book *p; clrscr(); p= &b; cout <<“Enter book detaails :”; Cin >>p->code; Cin >>p->name; cout <<“The book detaails :”; Cout << p->code; Cout << p->name; getch(); }
Pointers to arrays If the pointer contains the address of an array then it is known as pointer to an array. #include<iostream.h> #include<conio.h> void main() { clrscr(); int a[]={10,20,30,40,50}; int i; int *p=a; int (*q)[5]=&a; Cout<<“The elemnets are”<<endl; for( i =0;i<=4; i ++) cout <<a[ i ]<<p[ i ]<<(*q)[ i ]<< endl ; getch(); }
Passing array elements to a function To pass an array to a function, we can pass the individual elements or we can pass an entire array to a function.
passing the individual elements Call by value: #include<iostream.h> #include<conio.h> void main() {void display(int); clrscr(); int a[]={10,20,30,40,50}; int i; for( i =0;i<=4; i ++) display(a[ i ]); getch(); } void display(int n) {cout<<n<<“\n”;}
passing the individual elements Call by reference: #include<iostream.h> #include<conio.h> void main() {void display(int *); clrscr(); int a[]={10,20,30,40,50}; int i; for( i =0;i<=4; i ++) display(&a[ i ]); getch(); } void display(int * n) {cout<<*n<<“\n”;}
passing an entire array to a function #include<iostream.h> #include<conio.h> void main() {void display(int * , int ); clrscr(); int a[]={10,20,30,40,50}; int i; for( i =0;i<=4; i ++) getch(); } void display(int * p, int n) {int i; for(i=0; i<n;i++) cout<<p[i]<<“\n”;}
passing structure variable to a function Call by value: #include<iostream.h> #include<conio.h> struct book { int code; char name[20];}; void main() { void display(struct book); struct book b={101, “C++”}; clrscr(); display(b); getch(); } void display(struct book b); {cout<<“book details are:”<<endl; cout<<b.code<<endl; cout<<b.name<<“\n”;}
passing structure variable to a function Call by reference : #include<iostream.h> #include<conio.h> struct book { int code; char name[20];}; void main() { void display(struct book *); struct book b={101, “C++”}; clrscr(); display(&b); getch(); } void display(struct book *p) {cout<<“book details are:”<<endl; cout<<p->code<<endl; cout<<p->name<<endl;}
Array of structures Array of structures is nothing but collection of structure variables. #include<iostream.h> #include<conio.h> void main() { struct book { int code; char name[20];}; struct book b[3]; clrscr(); for(int i=0;i<2;i++){ cout <<“Enter book details:”<<i+1; cin >>b[ i ].code; cin >>b[ i ].name;} cout <<“The book details are:”<< endl ; for(int i=0;i<2;i++){ cout <<“ book details:”<<i+1<< endl ; cout <<b[ i ].code<< endl ; cout <<b[ i ].name<<“\n”;} getch(); }
OOPS It is a programming methodology to design computer programmes using classes and objects Features of OOP system : 1.Class/Object 2.Encapsulation 3.Abstraction 4.Inheritance 5.Polymorphism
OOPS OOP methodology has been derived from a single root concept called object. Objec t: It is any thing that really exists in the world and can be distinguished from others. Ex: Table, Car, Ball, Dog, Person etc. Not Objec t(Class): Something does not exist really. Ex: Imagination, Thoughts, Plans, Ideas etc. Difference between Class & Objec t: A class is a model for creating objects & does not exist physically. An object is any thing that really exists physically. Both class &object contain variables and methods(functions) Writing properties and actions of objects in a formula then that is a Class.
OOPS Example for creating class : Class Man { int age, weight; float height; void talk() {------} void walk() {------} }; Example for creating object: Man Ravi, Chandhu ;
OOPS Encapsulation: It is a mechanism where the data(variables) and code(functions) that act on the data will bind together. Ex: Class Generally the variables in the class are declared by using keyword ‘private’. i.e variables are not available to any other class. The functions in the class are declared by using keyword ‘public’. i.e functions can be called & used from anywhere out side the class. Encapsulation isolates the members of a class from members of another class.
OOPS Abstraction: There may be a lot of data a class contains & the user does not need the entire data. The user requires only some part of available data. In this case we can hide unnecessary data from the user and expose only that data that is of interest to the user. This is called abstraction. EX: Class Bank {private int accno , private string name; private float balance; Public void display-to-clerk() {------} };
OOPS Inheritance: It creates new classes from existing classes so that new classes will acquire all the features of the existing classes is called inheritance. Polymorphism: It represents the ability to assume several different forms. In programming we can use a single variable to refer to objects of different types and thus using that variable we can call the functions of different objects.
Classes & Objects Writing data and functions as a structure then it is a class. Every class ends with semicolon. # include<iostream.h> #include<conio.h> class Book{ private: int code; char name[20]; public: void get( ){ cout <<"The book detaails :"; cin >> name;cin >>code;} void display( ){ cout <<"The book detaails :"; cout << code;cout <<name;}}; void main(){ clrscr (); Book b ; b.get (); b.display (); getch(); }
Program to create date class #include<iostream.h> #include<conio.h> class date{ private: int d,m,y ; public: void get( ){ cout <<"The date detaails :"; cin >>d>>m>>y;} void display( ){ cout <<"The date detaails :"; cout <<d<<“/” <<m<<“/” <<y};}; void main(){ clrscr (); date today ; b.get (); b.display (); getch(); }
Program to create date class (another way) #include<iostream.h> #include<conio.h> class date{ private: int d,m,y ; public: void get( int a, int b, int c ); void display( );}; Void date:: get( int a, int b, int c){ cout <<"The date details:";d= a;m = b;y =c;} void date :: display( ){ cout <<"The date detaails :"; cout <<d<<“/” <<m<<“/” <<y}}; void main(){ clrscr (); date b ; b.get (21,11,22); b.display (); getch(); }
Access Specifiers An access specifier is a key word that specifies how to access the members of a class. we can use access specifier before its members. T here are 3 access specifiers available in c++ . p rivate: p rivate members of a class are not accessible any where outside the class. T hey are accessible only within the class by the functions of that class. public: p ublic members of a class are accessible every where outside the class. So any other program can read them and use them. protected: protectd members of a class are accessible outside the class, but generally within the same directory.
Access Specifiers #include<iostream.h> #include<conio.h> class date{ private: int d,m ; public: i nt y; void display( ){ cout <<"The date detaails :"; cout <<d<<“/” <<m<<“/” << y;} }; void main(){ clrscr (); date b ; b.d =30; b.m =11; b.y =2022; b.display (); getch(); }
constructors We can’t initialize variables in a class directly because memory will not created for class. But when we will create object for class then memory will be created then we can initialize variables. For this we have one method in C++.That method is constructor. Constructors are like member functions. These are useful only to initialize data with some starting values. Name of class constructors are same. Constructors will not return any value even void also. When object is created then the corresponding constructors of class executed automatically.
constructors There are 3 types of constructors. 1. Default Constructors 2.Parameterized constructors 3.Copy Constructors
Default constructors #include<iostream.h> #include<conio.h> class Book{ private: int code; char name[20]; public: Book( ){ name=" nmims "; code=100;} void display( ){ cout <<"The book detaails :"; cout << code;cout <<name;}}; void main(){ clrscr (); Book b ; b.display (); getch (); }
Parameterized constructors #include<iostream.h> #include<conio.h> class date{ private: int d,m,y ; public: date( int a,int b,int c ) { d=a; m= b;y =c;} void display( ){ cout <<"The date detaails :"; cout <<d<<“/” <<m<<“/” << y;}}; void main(){ clrscr (); date b(30,11,2022) ; b.display (); getch(); }
Copy constructors #include<iostream.h> #include<conio.h> class date{ private: int d,m,y ; public: date( int a,int b,int c ) { d=a; m= b;y =c ;} d ate( date &s) {d= s.d ; m= s.m ; y= s.y ;}} void display( ){ cout <<"The date detaails :"; cout <<d<<“/” <<m<<“/” << y;}}; void main(){ clrscr (); date b1(30,11,2022 ) ; date b2=b1; b1.display (); b2.display (); getch (); }
Inheritance Inheritance: It creates new classes(derived classes) from existing classes(base class) so that new classes will acquire all the features of the existing classes is called inheritance . Types of Inheritance: Single Inheritance Hierarchical Inheritance Hybrid Inheritance Multiple Inheritance
Types of Inheritance
S ingle Inheritance #include<iostream.h> #include<conio.h> class furniture{ protected: i nt l,w ; }; class table: public furniture{ private: int h ; Public: void display( ){ cout <<“Length:"<<l; cout <<“width:"<<w; cout <<“ Heigth :"<<h;}}; void accept( ){ cout <<“Enter Length, width and Heigth “; c in >>l>>w>>h;}}; void main(){ clrscr (); table t; t .accept (); t.display (); getch (); }
Single Inheritance #include < iostream > using namespace std ; class shape { protected: int l; }; class Square: public shape{ public: void area( int l ){ cout <<"Area of Square is:"<<l*l<< endl ; }}; class Rectangle: public shape{ private : int b; public: void area( int l, int b ){ cout <<"Area of Rectangle is:"<<l*b; }}; int main(){ Square s; s.area (10); Rectangle r; r.area (20,3); return 0; }
Multiple Inheritance #include<iostream.h> #include<conio.h> class base1{ protected: i nt x; Public: void display1( ){ cout <<"The x details :"; cout <<x;}}; class base2{ protected: int y; Public: void display2( ){ cout <<"The y details:"; cout <<y;}}; class derived: public base1, public base2 { void accept( ){ c in >>x>>y;}}; void main(){ clrscr (); derived D D.accept (); D.display1(); D.display2(); getch(); }
Multiple Inheritance #include<iostream.h> #include<conio.h> class base1{ Public : void display( ){ cout <<“BASE1";}; class base2{ protected: void display( ){ cout <<“BASE2";}}; class derived: public base1, public base2 { void main(){ clrscr (); derived D; D.base1::display(); D.base2::display(); getch (); }
Inheritance:Uses Making software as robust Code reusability Extensibility
Dynamic Polymorphism #include<iostream.h> #include<conio.h> class base{ Public: void display( ){ cout <<" This is base class”;}}; class derived: public base{ Public : void display( ){ cout <<" This is derived class”;}}; void main(){ clrscr (); b ase B; derived D; base * bptr ; b ptr =&B; b ptr ->display(); bptr =&D; bptr _->display(); getch(); }