C++ Book
C++ Book
Introduction
C++ is an object oriented programming language. It was developed by Bjarne Stoustup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in early 1980s. C++ is an extention of C with a major addition of the class construct. C++ earlear name was C with Classes but later in 1983 the name was changed to C++. Increment operator ++ suggest that c++ is an incremented version of C. in November 1997, the ANSI/ISO standanrds committee standardized these changes and added several new features to the language specifieactions. Application of C++: It is a versatile language for handling very large programs. It is suitable for development of editors, compilers, databases, communication systems and complex real life systems.
Tokens
Token is the smallest individual unit of a program. A c++ program contain five types of tokens. 1. Keywords 2. Identifiers 3. Constants or literals 4. Operators 5. Separators. A c++ programs is written using theses tokens. 1. Key Words: These are the words that convey a special meaning to the language compiler. These are reserved for special purpose and must not be used as normal identifier names. C++ contains around eighty key words. Example are :- break, continue, if, else, for, while etc. C++ is a case sensitive language so upper and lower case are treated separately. Example break is the key word while Break is not a key word because its B is capital.
2. Identifiers: Identifiers are fundamental building blocks of a program and are used generally to give the name to different parts of the program viz. variable, functions and array etc. we have to follow some rules while declaring identifiers , these rules are as follow: 1. Identifier can have alphabets, digits and underscore characters. 2. They must begin with an alphabet but never by a number. 3. They must not be a keyword or Boolean literal or null literal. 4. The can be of any length. 5. C++ is case sensitive language so upper and lower case will be treated separately. 3. Literals or constant: Literals often referred to as constants. These are the fixed data values. C allows several kinds of literals. Example 1. Integer literal 2. Floating literals 3. Character literals 4. Null literals. 1. Integer literals: Integer literals are whole numbers without any fractional part. There are three types of integer literals. i. Decimal Integer Literals-> An integer literal consisting of a sequence of digits. Without any fractional part. Unless it begins with 0. Example 1234, 2011, -90, +250 etc. ii. Octal Integer Literals -> A sequence of digits starting with 0 is taken to be an octal integer. Example 1 will be written as 01, 7 will be written as 07. Octal number system does not contain 8 and 9 digit. Table of octal numbers 1 01 2 02 ---- ----7 07 8 010 9 011 10 012 15 017 ---- -----16 020 17 021 23 027 ---- -----24 030 --- ----63 077 64 0100 65 0101 66 0102 71 0107 iii. Hexadecimal Integer Literals: A sequence of digits preceded by 0x or 0X is taken to be an hexadecimal integer. For example 12 will be written as 0XC as hexadecimal Integer. With hexadecimal constants only 0-9 and A-F can be used. A is equivalent to 10 and F is equivalent to 15.
Table of Hexadecimal Number 0 0x0 1 0x1 2 0x2 9 0x9 10 0xa 11 0xb 12 0xc 13 0xd 14 0xe 15 0xf 16 0x10 17 0x11 18 0x12 19 0x13 20 0x14 32 0x20 33 0x21 34 0x22 35 0x23 41 0x29 48 0x30 49 0x31 50 0x32 51 0x33 57 0x39 144 0x90 156 0x100 257 0x101 274 0x112 278 0x116 2. Floating Literals: These are also called as real literals. Real literal are numbers having fractional parts. These may be written in one of the two forms called fractional form or the exponent form. 1. A real literal in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or sign preceding it. A real literal with no sign is assumed to be positive. Following are the valid real literals in fractional form. 0, 17.5, -13.2, -0.235, -12.0 etc. 2. A real literal in exponent form has two parts. A mantissa and an exponent. The mantissa must be either an integer or a proper real literal. The mantissa is followed by a letter E or e the exponent. The exponent must be an integer. The following are the valid real literals in exponent form. 125e05, 1.56e07, 0.123e08, 124e+8, 120e04, -0.124e-3 etc.
3. Character Literals: A character literal is one character enclosed in single quotes. A character literal must contain one character, but not more than one. We can have some nongraphic character in character constants. Non-graphic character are those character that cannot be typed directly from keyboard e.g. Backspace, Tabs, Enter, Carriage return etc. these non-graphic character can be represented by using escape sequences. An escape sequence is represented by a backslash (\) followed by one or more characters. Escape Sequences \a \b \n \r \t \v \\ \ \ \? \0n \0xhn \0 Non-graphic character Audible bell (alert) Backspace New line Carriage return Horizontal tab Vertical tab Back slash Single quote Double quote Question mark Octal number Hexadecimal number Null Unicode values of character 0x0007 0x0008 0x000A 0x000D 0x0009 0x000B 0x005C 0x0027 0x0022
0x0000
4. The null literal: The null literal has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.
Separators
Separators are the symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code. The following nine ASCII characters are the separators or punctuators. ( ) for function call { } for block creation [ ] for array dimension ; for end of statement , for sepration of variable . for reference # for preprocessor : for label :: scope resolution operator (for scope representation);
Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually from a part of mathematical or logical expression. 1. Arithmetic operators Arithmetic C
+ / * %
Relation Lesser than Lesser than equals to Greater than Greater than equals to Equals to Not equals to
Pre-decrement
if p=5; find d=++p + 5; if a=48; find a=a++ + ++a; if c=2; d=++c + c++ + 4; if m=12; n=m++ * 5 +--m; if y=14; z=(++y * (y++ +5)) a=4, b=3; c=a++ * 6 + ++b*5+10; a=8; a-=++a + a++ +4;
a=12,b=8; a*=++a/6+b++%3; x=4; x+=x++ * ++x%2 a=48, b=13; a+=b++ *5/a++; q=9, r=11;' 1. p*(q++ % 4)* (++r) 2. (r--)%5+(r++/5)*p 3. p+=(--p + 5)*(p++)*(r/2) 4. q*=5+(--q)*(q++)+10 4. Conditional operators && Logical AND || Logical OR ! Logical NOT Truth table for AND (&&) Expression1 T F T F
Expression2 T T F F
Result T F F F
Truth table for OR (||) Expression1 || (OR) T || F || T || F || Truth table for NOT (!) Expression T F 5. Bitwise operator Operator & | ~ ^ << >>
Expression2 T T F F
Result T T T F
! (NOT) ! !
Result F T
Meaning Bitwise AND Bitwise OR Bitwise complement Bitwise exclusive OR Left shift operator Right shift operator
>>>
#include<iostream.h> #include<conio.h> void main() { cout<<(12 | 18); cout<<"\n"; cout<<(21 | 15); cout<<"\n"; cout<<(27 | 37); getch(); } #include<iostream.h> #include<conio.h> void main() { cout<<(12>>2); cout<<"\n"; cout<<(29>>2); cout<<"\n"; cout<<(32>>2); getch(); } #include<iostream.h> #include<conio.h> int a=10; void main() { int b=30; cout<<(12>>>2); cout<<"\n"; cout<<(29>>>2); cout<<"\n"; cout<<(32>>>3); getch(); } #include<iostream.h> #include<conio.h> void main() { cout<<(12 ^ 18); cout<<"\n"; cout<<(27 ^ 29); cout<<"\n";
6. Conditional Operator (:?) It is also known as ternary operator. This operator is used to construct condition expression. It is alternative to if else. Exp1? exp2: expt3 Condition? True: false If- Then- Else int a, b, c; a=10,b=20; c=a>b?a:b; 7. Special operators: There are some special operators like sizeof() operator and member selection operators (.). The sizeof operator is used to get the size of variable that it will occupy from memory. Example: int a; int m=sizeof(a) Dot operator (.) is used to access the instance variable and methods of class objects. Person1.age; Person1.salary (); Arithmetic Expressions An arithmetic expression is a combination of variable, constants, and operators arranged as per the syntax of the language. Example: 1. (m+n)(x+y) 2. Ab/c*d-e Precedence of operators An arithmetic expression without any parentheses will be evaluated from left to right using the rules of precedence of operators. Hierarchy of operators Operator Description Associativity Rank . Member selection Left to right 1 () Function call Do 1 [] Array elements reference Do 1 ++ -! ~ (type) * Unary minus Increment Decrement Logical Negation (not) Once complement Casting Multiplication Right to left Do Do Do Do Do Left to right 2 2 2 2 2 2 3
/ % + << >> >>> < <= > >= Instanceof == != & | ^ && || ?: = +=, *=, /= etc.
Division Modulus Addition Subtraction Left shift Right shift Right shift with zero fill Less than Less than equals to Greater than Greater than equals to Type comparison Equality Not equals to bitwise AND Bitwise OR Bitwise xor Logical AND Logical OR Conditional operator Assignment operator Shorthand operator
Do Do Left to right Do Left to right Do Do Left to right Do Do Do Do Left to right Do Left to right Do Do Do Do Do Do Do
3 3 4 4 5 5 5 6 6 6 6 6 7 7 8 8 8 8 8 8 8 8
1. (amount+qty*value)-bal 2. Fin+qty*inter 3. Inter-(qty*value)+fin 4. Q(a+b-z/4) 5. a2+b2+c2 6. 2-ye2y+4y 7. P+q(r+s)4 8. Math.abs(Math.exp(x)-x) 9. (Cos x/tan-1 x)+x 10. A=mb*3/4+k/4+8-mb+5/8 11. (a+b)>c && (c+d)>a 12. (x>y) && (!y<z) 13. X<=!y && z 14. F=(++a)*b-a 15. C=a-(b++)*(--a) 16. C=(a++)*d+a 17. Area=r2+2rh 18. Result=2m1m2/m1+m2*g 19. Side=a2+b2-2ab cos(x)
20. (x-(y/5)+z)%8)+25 21. A==c||b>a 22. B>15 && c<0 ||a>0 23. (a/20==0.0 && b/2.0!=0.0)||c<0.0 24. (5/3)*3+5%3 25. 14%3+7%2
Data types: Data type specifies the size and values that can be stored in a variable. Data types in C can be classified in number of parts as follow: Reference Type: A reference data type is a data element whose value is an address. Arrays, structure and enum are reference types. The value of reference type variable is an address of the value or set of values represented by the variable. Data Type
Primitive (intrinsic)
Non-primitive (derived)
numeric
Non-numeric
Structure
arrays
Integer
Real
Charcter
Union
Enumeration
Pointer
Classes
Type Short
Type of value can hold Can hold complete number without decimal places Do Do
Int Long
float double
Char
1 bytes (8 bits)
127
NOTE: Incase of unsigned all values range will start from 0 and will become just double to
the singed positive ranges of therit respective types. Variable: A variable is a named memory location which holds a data value of a particular data type, whose value is manipulated during the program run. Declaration and initialization of variable-> Syntax data type variable name; Example: int age; int age, salary, code; int age=25, salary=10000, code=1; float salary, bonus; salary=1000.00; bonus=500.00; int a=b=c=10; Scope of variables: The program area where a variable is accessible is known as scope of that variable. On the basis of scope variable can be classified into three categories. 1. Global variable. 2. Local variable. Global-> These are global to a program. And declared just after the header files declaration. Local variable-> Variable declared inside method are called local variables. They are called so because they are not available for use outside their method definition. Local variable can also be declared inside program blocks that are defined between an opening brace {and closing brace}. These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leave a block, all the variables in the block will cease to exist. #include<stdio.h> int x=0; { int m=5; - -- -} { int n=10; - -- -}
Block 3
Type conversion: The process of converting one predefined type into another is called type conversion. Type conversion is of two types. 1. Implicit type conversion: it is automatic type conversion done by C automatically there is no any intervention of the programmer. Automatic conversion is done when different data types are intermixed in an expression, so as not to lose information. The C compiler converts all operands up to type of the largest operant. It is based on some rules: i. if either operand is of type double, the other is converted to double. ii. If either operand is of type float, the other is converted to float. iii. if either operand is of type long, the other is converted to long. The implicit type conversion where data types are promoted to higher type are known as type promotion or coercion. It is also known as widening of data type. 2. Explicit type conversion or Type Casting: The explicit type conversion is user defined that forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called type casting. In type casting we cast (convert) the value to be stored by, proceeding it with the type name in parentheses. Casting is necessary in situations when a method returns a type different than our required type. It is also known narrowing of data or force conversion. Syntax-> (type) expression. Expression Evaluation: Expression can be pure and mixed expression. Pure expression have all operands of same data types, while impure expression have operands of mixed data types. Boolean expression: The expression that results into false or true are called Boolean expressions. The Boolean expressions are combination of constants, variables and logical and relational operators. Statement: A statement forms a complete unit of execution. It is similar to the sentence in natural language. Each statement in C is terminated by semicolon (;). Block: A block is a group of zero or more statements between balanced braces and can be used anywhere. Null or empty statement: The statement where only semicolon (;) is present on the name of statement and there is no any logic to apply is known as empty or null statement; It is required in the situations where a program requires the presence of statement only, but not logic of the program. It is generally used in loops and their bodies. Example:
cout<<"Hello"; }
#include<> : It is preprocessor directive which is used to hold the header files to associate them
with out program before execution of main.
Stdio.h or conio.h : It is header file. Header file contain predesigned program which contain
methods definition which we use in our program like cin, cout, clrscr() etc.
Void : void is the key word that specifies that main does not return any value. It is used to avoid
return type from a function
main :
main() is a function. It is library function without main C++ programming is not possible because program execution starts from main and it is also known as starting point of program. Every C program contain only one main function. Overloading of main function is not possible. C main can be with void or with int return type. If main is returning a value than this value goes to the operating system.
The output line: cout<<hello C is the output statement in the program. Cout is a library
function. Its definition is present in iostream.h header file. It display the output. Output -> Hello C
The input line: Cin>> is the input function that is used to read data from keyboard.
Intput cin>>a; Here >> and << are the right shift and left shift operator respectively. Due to operator overloading we changed their meaning. Comments: C++ permits both single line and multiple line comment. The single line comments begin with // and end at the end of the line automatically and a multi line comment starts by /* and ends with */ symbol. A simple c++ Program: #include<iostream.h> #include<conio.h> void main() { cout<<"Hello c++"; getch(); } Program with user input #include<iostream.h> #include<conio.h>
void main() { int a,b; cout<<"\n Enter two number "; cin>>a>>b; cout<<a<<"\t"<<b; getch(); }
1. pq3+0.02r #include<iostream.h> #include<conio.h> #include<math.h> void main() { double p,q,r; cout<<"\ Enter values of p, q and r "; cin>>p>>q>>r; double result=p*q*sqrt(3)+0.02*sqrt(r); cout<<result; getch(); } 2. 3. 4. 5. 6. (0.05-2y3)/(x-y) b+b2+4ac/2a 3/4a3-2/7b4 A3+b4+c5 3/8b2-c3
Data Formating
#include<iostream.h> #include<conio.h> #include<iomanip.h> void main() { cout<<setw(20)<<"Hello\n"; cout<<setprecision(5)<<12.256;//will deduct 2 digits(scaler value) from 5 first, then will show rest values as precision after point (like 12.256 contain 12 (2 digits) so (5-2=3) so it will show 12.256 as output) getch(); }
Control structure
Control structure or control statements are the statements which control the flow of program execution. These are basically of four types. 1. Decision making statement. Ex:==if, if else, nested if else, conditional operator 2. Selection statement Ex:==else if ladder, switch, nested switch 3. Iteration Ex:==for, while, do-while loop 4. Jump statement Ex: ==break, continue, return, exit.
Or
void main() { int a,b; clrscr(); cout<<\n enter value of a and b; cin>>a>>b; if(a>b) cout<<a is greater; else cout<<b is greater ; getch(); } 1. WAP to find whether a number is even or odd? 2. WAP to enter a temperature in celcius and convert it into Fahrenheit and if the temperature is 98.6 F or more than display fever otherwise normal. F=9*c/5+32; 3. WAP to find whether a number is positive or negative. 4. WAP to find whether a year is leap or not.
/* input saling price and cost price of an item and print wheither saller has made profit or loss and how much*/
import java.io.*; class profit_loss { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int sp, cp, diff; System.out.println("Enter salling price and cost price of an item "); sp=Integer.parseInt(br.readLine()); cp=Integer.parseInt(br.readLine()); diff=sp-cp; if(diff>0) System.out.println("He made profit "+ diff); else System.out.println("He made loss "+ diff); } } Nested if else -> a nested if is an if that has another if in its ifs body or in its elses body. The nested if can have one of the following three forms: if (condition) { if(condition) Statement else Statement
} else { if(condition) Statement else Statement } Example: /******Nested if else demo***/ import java.io.*; class nestedifelse { public static void main(String args[]) throws IOException { DataInputStream br=new DataInputStream(System.in); int a,b,c; System.out.println("Enter values of a, b, and c "); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); c=Integer.parseInt(br.readLine()); if(a>b) { if(a>c) System.out.println("A is greatest "); else System.out.println("C is greatest "); } else { if(b>c) System.out.println("B is greatest "); else System.out.println("C is greatest "); } } }
/*Enter a character and find whether it is vowal or consonant and find its case also*/
import java.io.*; class characters { public static void main(String arg[]) throws IOException { DataInputStream br=new DataInputStream(System.in);
char ch; System.out.println("Enter a character "); ch=(char)br.read(); if(ch>='a' && ch<='z') { if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u') System.out.println("It is lower case vowal"); else System.out.println("It is a lower case consonant"); } } } The conditional operator: this operator is alternative to if else statement. It concept is if-thenelse. It is also known as ternary operator because it requires three operands for its working. Its general form is this: Condition?expression1:expression2; If condition is true then expression one will execute otherwise expression2 will execute. Example: #include<iostream.h> #include<conio.h> void main() {int a,b,c,d; cout<<\n enter value of a,b and c; cin>>a>>b>>c; d=a>b?(a>c?a:c):(b>c?b:c); cout<<The greatest element is <<d; getch();} import java.io.*; class leapyear { public static void main(String args[]) { int year=2012; System.out.println(year%4==0?"Leap":"Not Leap"); } }
The else if ladder: it is also known as if-else-if staircase because of its appearance. It is used to handle multiple conditions one by one. Syntax: if(condition) Statement
example:
import java.io.*; class result { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int phy,che,math; int total; double pct; System.out.println("Enter marks of phy, chemisty and math "); phy=Integer.parseInt(br.readLine()); che=Integer.parseInt(br.readLine()); math=Integer.parseInt(br.readLine()); total=phy+che+math; pct=(total*100)/300; if(pct>=60) System.out.println("First division "); else if(pct>=50 && pct<60) System.out.println("Second division "); else if(pct>=40 && pct<50) System.out.println("Third division "); else System.out.println("Faile "); } }
1. Enter three sides of a triangle and find whether it is a equilateral(three sides are equal) or isosceles (two sides are equal) or a scalene (not side is equal) triangle. 2. Enter three sides of a triangle and find whether the triangle is possible or not. If sum of any two sides is greater than third, then triangle is possible otherwise not. (a+b>c) && (b+c>a) && (c+a>b) 3. Find out the total cost that will be paid by the customer Total Cost Discount (in Percentage) Less than Rs. 2000 5% Rs. 2001 to Rs. 5000 25% Rs. 5001 to Rs. 10000 35% Above Rs. 10000 50%
4. Display grade accordingly. Marks 80% and above 60% or more but less than 80% 45% or more but less than 60% 40% or more but less than 45% Less than 40% 5. Units Consumed Up to 100 units >100 and up to 200 unit >200 units
Grades Distinction First Division Second Division Pass Promotion not granted
6. root=b2-4ac , calculate root for two equaltion and find: If d>=0 Roots are real and Unequal If d=0 Roots are real and equal Id d<0 Roots are imaginary 7. Calculate charges for parsal: Weight Up to 10 kg. For the next 20 kg. For the next 20 kg. More than 50 kg. 8. Calculate simple interest: Time T=1 year T=2 years T=3 years on more 9. Find out the gross salary of an employee: Dearness Allowance (DA) Hous Rent Allowance Provident Fund Net Pay Gross Pay 25% of Basic pay 15% of Basic pay 8.33% of Basic pay Basic Pay+Dearnesss Allowance+House Rent Allowance Net pay-Provident Fund Rate R=10% R=11% R=12%
Charge Rs. 20 per kg. Rs. 10 per kg. Rs. 8 per kg. Rs 5 per kg.
10. Tax rate for water consumed by a consumer: Water Consumed (in Gallons) More than 45 but 75 or less More than 75 but 125 or less More than 125 but 200 or less Tax Rate in Rs. 475.00 750.00 1225.00
More than 200 but 350 or less More than 350 11. Calculate Income tax: Annual Salary Up to Rs. 1,00,000 Rs. 1,00,001 to Rs. 1,50,000 Rs. 1,50,001 to Rs. 2,50,000 Above Rs. 2,50,000
1650.00 2000.00
Rate of income tax No tax 10% of the amount exceeding Rs. 1,00,000 Rs. 5000+20% of the amount exceeding Rs. 1,50,000 Rs. 25,000+30% of the amount exceeding Rs. 2,50,000
Statement; Break; case 4: case 5: case 6: Statement; Break; Default : Statement; } #include<iostream.h> #include<conio.h> void main() { int ch; cout<<"\n 1 for Shristi "; cout<<"\n 2 for Akshat "; cout<<"\n Enter your choice "; cin>>ch; switch(ch) { case 1: cout<<"\n name is shristi "; break; case 2: cout<<"\n name is Akshat "; break; default : cout<<"\n Wrong choice "; } getch(); } #include<iostream.h>
#include<conio.h> void main() { char ch; cout<<"\n S for Shristi "; cout<<"\n A for Akshat "; cout<<"\n Enter your choice "; cin>>ch; switch(ch) { case 'S': cout<<"\n name is shristi "; break; case 'A': cout<<"\n name is Akshat "; break; default : cout<<"\n Wrong choice "; } getch(); } #include<iostream.h> #include<conio.h> void main() { char ch; cout<<"\n S for Shristi "; cout<<"\n A for Akshat "; cout<<"\n Enter your choice "; cin>>ch; switch(ch) { case 'S':
case 's': cout<<"\n name is shristi "; break; case 'A': case 'a': cout<<"\n name is Akshat "; break; default : cout<<"\n Wrong choice "; } getch(); } 1. Enter a character and print whether this character is vowal or consonant.
2. WAP to find area, perimeter or diagonal of a rectangle according to the choice taking length and breadth as input. (perimeter =2*(L+B), diagonal=(a2+b2), area=a*b ) #include<iostream.h> #include<conio.h> #include<process.h> void main() { int ch; cout<<"\n 1 for Shristi "; cout<<"\n 2 for Akshat "; cout<<"\n 3 for Arif "; cout<<"\n 4 for Rakesh "; cout<<"\n 5 for Vinay "; cout<<"\n Enter your choice "; cin>>ch; switch(ch) { case 3-2: cout<<"\n name is shristi ";
break; case 1+1: cout<<"\n name is Akshat "; break; case 3*1: cout<<"\n name is Arif "; break; case 8/2: cout<<"\n name is Rakesh "; break; case 37%8: cout<<"\n name is vinay "; break; case 6: exit(1); } getch(); } The Nested Switch -> when a switch is a part of the statement sequence of another switch then is known as nested switch statement. Syntax: switch(expression) { case 1: switch(expression) { case 0: Statement: break; case 1; Statement; break; } break; case 2:
Statement; break; } #include<iostream.h> #include<conio.h> #include<process.h> void main() { int ch,choice; cout<<"\n 1 for Cloths "; cout<<"\n 2 for Snacks "; cout<<"\n 3 for exit "; cout<<"\n your Choice "; cin>>ch; switch(ch) { case 1: cout<<"\n 1 for Pant "; cout<<"\n 2 for shirt "; cout<<"\n enter your choice "; cin>>choice; switch(choice) { case 1: cout<<"\n You purchase Pant "; break; case 2: cout<<"\n you purchase Shirt "; break; } break; case 2: cout<<"\n 1 for chips "; cout<<"\n 2 for biscutis "; cout<<"\n enter your choice "; cin>>choice; switch(choice) { case 1: cout<<"\n you purchase chips "; break; case 2: cout<<"\n you purchase buscuits "; break; } break; case 3: exit(1);
} getch(); } Some points about switch: 1. A switch can only work for equality comparison. 2. No two case labels in the same switch can have identical value. 3. Switch can work only constant values like int, byte, short, char, long but never with real values like double, float. 4. A switch statement execute only once when a match is found and never again in the program. /*a cloth showroom has announced the following seasonal discount on purchasing of items*/ Amount mill cloths handlooms items 0 to 100 --> 5.0% 5.5% 101 to 200 -> 7.5% , 8.5% 201 to 300--> 7.5% , 10.0% above 300 --> 10.0% , 15.0% write a program using switch and if statements to compute the amount to be paid ? */ import java.io.DataInputStream; class purchase { public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int amount=0,i=0; float discount,total; char cloth='m'; try { System.out.println("Enter the amount "); amount=Integer.parseInt(in.readLine()); System.out.println("Enter the Cloth (M/H) "); cloth=(char)System.in.read(); } catch(Exception e){} if(amount>=0 && amount<=100) i=1; else if(amount>=101 && amount<=200) i=2; else if(amount>=201 && amount<=300) i=3; else if(amount>300) i=4; switch(i) {
case 1: if(cloth=='m' || cloth=='M') { discount=0; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=5.0f; discount=amount*5/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 2: if(cloth=='m' || cloth=='M') { discount=amount*5/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=7.5f; discount=amount*5/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 3: if(cloth=='m' || cloth=='M') { discount=amount*7.5f/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=amount*10/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; case 4: if(cloth=='m' || cloth=='M') {
discount=amount*10/100; total=amount-discount; System.out.println("Total Amout of bill is "+ total); } else if(cloth=='h' || cloth=='H') { discount=amount*15/100; total=amount-discount; System.out.println("Total Amount of bill is "+total); } break; }}}
Iteration or Looping
The statements that allow a set of instruction to be performed repeatedly until a certain condition is fulfilled are known as iteration or looping. Java provides four kinds of loop For, while, do-while loop. All the loops repeat a set of statement as long as a specified condition remains true. This specified condition is generally referred to as loop control. Elements and parts of loop Generally a loop has four parts. 1. Initialization expression-> Before entering in a loop , its control variable must be initialized. The initialization of control variable takes palace under initialization expression. The initialization expression gives the loop control a starting point and this expression is executed only once in the beginning of the loop. 2. Test Expression-> this is the expression whose truth value decides whether the loop body will be executed or not. If the test expression evaluates to true the loop body gets executed otherwise the loop is terminated. 3. Update Expression-> the update expression change the value of loop variable . the update expression is executed at the end of the loop after the loop body is executed. 4. The body of the loop-> The statement that are executed repeatedly (as long as the test expression is true) form the body of the loop. Types of loop Generally loops are to two types. 1. entry control or pre-tested or top-tested loop-> the loop in which first the test expression is evaluated first of all and if it returns true then the loop body will executed otherwise loop will be terminated, is known as entry control loop. Example-> for , while , for each. 2. Exit control or post-tested or bottom tested loop-> when loop body is executed first and then the test expression is evaluated, if it evaluates to true then the loop is repeated otherwise terminated. Such type of loop is known as exit control loop. Because testing takes place at
the last of loop so in exit control loop, body of the loop will execute at least once whether the testing condition returns true of false. Example-> do-while The for loop () Syntax ---------------- for(initialization; testing ; updation) Loop body Example---1
7----------10
Example:
1 2 1 2 0 2 2 4 4 5 3 4 3 6 9 10 8 8 4 8 16 17 15 16 5-------------------------------------10 10------------------------------------20 25------------------------------------100 26------------------------------------101 24-------------------------------------99 32-------------------------------------1024
1/ 2 1/3 1/ 4 1/5------------------------------------1/10 2/2 3/3 4/4 5/5------------------------------------10/10 2/3 3/ 4 4/5 5/6------------------------------------10/11 2+2/2*2
x/3 x/4
1+1/1*1
x/2
3+3/3*3
x/5
4+4/4*4------10+10/10*10
x/6-----------------------------x/10
(1*2)+(2*3)+(3*4)+(4*5)+(5*6)+(6*7)--------------------(10*11)
Nested Loops
(1)+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+3+4+5) (1)+1+(1*2)+2+(1*2*3)+3+(1*2*3*4)+4+(1*2*3*4*5) 1/ 2-1/3+1/4-1/5+--------------------------------------------------------1/10 1/1!+1/2!+1/3!+1/4!+1/5!-----------------------------------------------1/10!
2-4+6-8+10-12+12-16+14-20------------------------------------------20 a+a/2+a/3+a/4+a/5+-----------------------------------------------------a/10
1/ a1 + 2/a2 + 3/a3 + 4/a4 + 5/a5 --------------------10/a10 a1/1+a3/5+ a5/9+ a7/13+a9 / 17-------------------- n-terms
The for loop variations Java offers several variation of for loop that increase the flexibility and applicability of for loop. 1. Multiple initialization and updation-> a for loop can contain multiple initialization and update expression and these expression are separated by comma. Example->>>> int i,j; for(i=1,j=1; i<=10 && j<=10; i++,j++) { System.out.println(i); System.out.println(j); } Optional expression-> all the expression of a for loop are optional, we can skip any of the expression. Example->>>>>>> int i=1; for(;i<=10;) { System.out.println(i); i++; } Or i=1; for(; ; ) //infinite loop { System.out.println(i); i++;
} Or for(;;) //infinite loop System.out.println(hello); Or for(i=1; i; i++); //empty loop Or long i; For(i=1;i<=10000000000;i++);
// delay loop
/*prime number*/
import java.io.*; class prime { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int num; System.out.println("Enter a number "); num=Integer.parseInt(br.readLine()); int i,c=0; for(i=1;i<=num;i++) { if(num%i==0) { c++; } } if(c==2) System.out.println("Number is prime "); else System.out.println("Number is not prime "); } }
/*fibonacci series*/
import java.io.*; class fibonacci { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int limit,i,a,b,s=0; System.out.println("Enter the limit "); limit=Integer.parseInt(br.readLine()); a=0; b=1;
System.out.print(a+" "+b+" "); s=a+b; for(i=0;i<=limit;i++) { System.out.print(s+" "); a=b; b=s; s=a+b; } } }
2 2
/***************Floayed Triangle **********************/ class fload { public static void main(String args[]) { int i,j,k=1; for(i=1;i<=13;i++) { for(j=1;j<=i;j++) { System.out.print(k+" "); k++; } System.out.println(); } } }
Output :
/***************Floayed Triangle **********************/ class fload { public static void main(String args[]) { int i,j,k=1; for(i=1;i<=13;i++) { for(j=i;j>=1;j--) { k=j%2; System.out.print(k+" "); } System.out.println(); } } Output : //**************************shape*****************************// class shape { public static void main(String args[]) { int i,j,k; for(i=1;i<=5;i++) { for(k=5;k>i;k--) { System.out.print(" "); } for(j=i;j>=1;j--) { System.out.print(i); System.out.print(" "); } System.out.println(); } } }
While loop may also have variations. It can be empty or infinite loop. Example: long wait=0; while(++wait<100000) ;;;;;;
int i=1; while(i<=10) //infinite loop System.out.println(hello); while(true) System.out.println(hello); //infinite loop while(false) System.out.println(hello); //this loop will not work , because test expression is false Question: Reverse a number. import java.io.*; class reverse { public static void main(String args[]) throws IOException { DataInputStream in=new DataInputStream(System.in); int num; System.out.println("Enter a multidit number "); num=Integer.parseInt(in.readLine()); int r,s=0; while(num>0) { r=num%10; s=s*10+r; num/=10; } System.out.println(s); } } Question: Do the sum of all digits of a number. Question: Do the sum of first and last digit of a number. Question: Sunny Number. Question: Armstrong number. Question: Palindrome Number. Question: Perfect Number. Question: Buzz Number. Question: Automorphic Number. #include<iostream.h> #include<conio.h>
void main() { int num=25; int sq=num*num; while(num>0) { if(num%10 !=sq%10) break; num/=10; sq/=10; } if(num==0) cout<<"\n Automorphic number "; else cout<<"\n not Automorphic number"; getch(); } Question: Special Number. Question: Magic Number. /*******magic number*/ import java.io.*; class magic { public static void main(String args[]) throws IOException { DataInputStream in=new DataInputStream(System.in); int num; System.out.println("Enter a number "); num=Integer.parseInt(in.readLine()); int s; while(true) { s=0; while(num>0) { int r=num%10; s=s+r; num/=10; } if(s>=1 && s<=9) break; else num=s; } if(s==1) System.out.println("Number is magic ");
else System.out.println("number is not magic "); } } Question: find out the maximum and minimum number among ten entered by the user.
char ch=a; do { System.out.println(ch); ch++; }while(ch<=z); Print twos table in this format 2*1=2 2*2=4 2*3=6
/*odd looping*/
#include<iostream.h> #include<conio.h> void main() { char ch; int s=0,num; do { cout<<"\n enter a number "; cin>>num; s=s+num; cout<<"\n Do you want to continnue "; cin>>ch; }while(ch=='y'); cout<<"\n Sum is "<<s; getch(); }
if(min>num) min=num; if(max<num) max=num; cout<<"\n Do You want to continue (Y/N) "; cin>>ch; }while(ch=='y'); cout<<"\n Maximum number you entered is "<<max; cout<<"\n Minimum number you entered is "<<min; getch(); }
/****************Buzz number***************/
if((n/10==7) && (n%7==0)) System.out.println("***BUZZ NUMBER***"); else System.out.println("NOT A buzz number!!!"); /************* and GCD**************/ #include<iostream.h> #include<conio.h> void main() { int n1,n2,i,c=0; cout<<"\n enter two numbers "; cin>>n1>>n2; for(i=n1<n2?n1:n2; i>=1; i--) { if((n1%i==0) && (n2%i==0)) { c++; break; } } if(c>0) cout<<"GCD "<<i; else cout<<"No Factor "; getch(); } Comparison of loops Thought you can use all loops in almost all situations yet there are some situations where one loop fits better then the other. The for loop is appropriate when you know in advance how many times the loop will be executed. The other two loops while and do-while loops are more suitable in the situations where it is not known before hand when the loop will terminates. The while should be preferred when you may not
want to execute the loop body even once and the do-while loop would be preferred when you are sure you want to execute the loop body at least once.
Jump Statements
The jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch i.e. jump statements. return, break, continue. return statement we can use anywhere in the program whereas break and continue are used inside smallest enclosing like loops etc. beside these statements java also provide a standard library function System.exit(1) that helps you break out of a program. The return statement is used to return from a function.
break statements
The break statements enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes at the statement immediately following the body of the terminated statement. If a break statement appears in a nested loop, then it causes an exit from only then inner loop.
#include<iostream.h> #include<conio.h> void main() { int radius,area; int i=1; while(i<=10) { cout<<"\n enter a radius "; cin>>radius; if(radius>0) { area=3.14*radius*radius; cout<<"\n Area is "<<area; } else break; i++; } getch(); } The continue statement This statement forces the next iteration of the loop to take place, skipping any code in between.
Example:
#include<iostream.h> #include<conio.h> void main() { int radius,area;
int i=1; while(i<=10) { cout<<"\n enter a radius "; cin>>radius; if(radius>0) { area=3.14*radius*radius; cout<<"\n Area is "<<area; } else continue; i++; } getch(); }
Goto
#include<iostream.h> #include<conio.h> void main() { int radius,area; int i=1; while(i<=10) { cout<<"\n enter a radius "; cin>>radius; if(radius>0) { area=3.14*radius*radius; cout<<"\n Area is "<<area; } else goto out; i++; } out: printf("\n you are outside loop "); getch(); }
Array
Array: An array is a collection of constants of similar data type which are reference by a common name i.e. the array name. Array contains continuous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Array can be of any data type but it will store the elements of its own type, i.e. array of integer type will store integers only not even a single float or a char it can store.
We need array mainly store multiple value of similar type for which multiple declaration of
variable is not possible. Like if we want to store marks of fifty students then it is not possible to declare fifty variables for them but we will simple use an array of integer for it. Array index always starts from 0, so to visit the last elements position will be one less than the total size of array. Subscripted variable: Subscripted variable is the variable that we use to visit the every element of array. It can be any valid character or identifier. Subscript: It is index of array elements. Types of array-> Array are of two types. 1. Single dimension array 2. Multidimensional array or two dimensional array Single Dimension Array: An array with single rows of elements is known as single dimension array. It represents its elements as a list and there is no tabular representation of elements. Two Dimensional Arrays: A 2-d array is a collection of elements placed in M rows and N columns. The syntax used to declare a 2-d array includes two subscripted variables, out of them one specifies the number of rows and the other specifies the number of columns of the matrix. These two subscripted variable are used to reference an element in the matrix. For example array [3][4] in a 2-d array containing 3 rows and 4 columns and array[0][2] is an element placed at 0th row and 2nd column in the array. The two dimensional array is also called a matrix. Operations of array: 1. Traversal. 2. Search 3. Insertion 6. Merging 7. Reversing.
4. Deletion
5. Sorting
/******************Array initialization**************/ #include<iostream.h> #include<conio.h> void main() { int list[]={10,20,30,40,50}; int i; clrscr(); for(i=0;i<5;i++) cout<<list[i]; getch(); } /*************array by keyboard***************/ #include<stdio.h> #include<conio.h> void main() { int list[5],i; clrscr(); printf("Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]); printf("\n Elements of array are ....\n"); for(i=0;i<5;i++) printf("%d ",list[i]); getch(); } /******************find max element from array**************/ #include<stdio.h> #include<conio.h> void main() { int list[5],i,max=0; clrscr(); printf("Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]); printf("\n Elements of array are ....\n"); for(i=0;i<5;i++) if(max<list[i]) max=list[i]; printf("\n Maximum element is %d ",max); getch();
} /**************Reverse an array************/ #include<stdio.h> #include<conio.h> void main() { int list[5],i,k=4,temp=0; clrscr(); printf("Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]); printf("\n Elements of array are ....\n"); for(i=0;i<=k;i++) { temp=list[i]; list[i]=list[k]; list[k]=temp; k--; } printf("\n Elements of array after reverse ....\n"); for(i=0;i<5;i++) printf(" %d ",list[i]); getch(); } /***********************find even and odd element in an array**********/ #include<stdio.h> #include<conio.h> void main() { int list[5],i,j=0,k=0; int even[5],odd[5]; clrscr(); printf("Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]); for(i=0;i<5;i++) { if(list[i]%2==0) even[j++]=list[i]; else odd[k++]=list[i]; } printf("\nEven elements ... "); for(i=0;i<j;i++) printf(" %d ",even[i]);
printf("\nOdd elements....."); for(i=0;i<k;i++) printf(" %d ",odd[i]); getch(); } Searching -> Searching is the technique which finds the location of a given element in a list. The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not. Searching are of two types. Linear search and binary search Linear search-> This is the simplest method of searching. In this method the element to be found is sequentially searched in the list. This method can be applied to a sorted or unsorted list. Searching is case of a sorted list starts form 0th element and continues until the element is found or an element whose value is greater than the value being searched is reached. As against this, searching in case of unsorted list starts from the 0th element and continues until the element is found or the end of list is reached. Example: //*******************linear search ************// #include<iostream.h> #include<conio.h> void main() { int arr[5]; int i,n,c=0; cout<<"\n enter elements of array "; for(i=0;i<5;i++) cin>>arr[i]; cout<<"\n enter the element that is to search "; cin>>n; for(i=0;i<5;i++) { if(arr[i]==n) { c=1; break; } } if(c==1) cout<<"\n Element found at "<<++i; else cout<<"\n element not found "; getch(); }
Binary Search: This method is fast as compared to the linear searching technique. This method requires that the list of elements be in sorted order. In this method to search an element we compare it with the element present at the center of the list. If it matches then the search is successful.Otherwise the list is divided into two halves (half): one from 0th element to the center element (first half), and another from center element to the last element (second half). As a result all the elements in first half are smaller than the center element, whereas all the elements in second half are greater than the center element. The searching now will proceed in either of the two halves depending upon where the element is greater or smaller than the center element. if the element is smaller than the center element than the searching will be done in the first half, otherwise in the second half. Same process of comparing the required element with the center element and if not found then dividing the elements into two halves is repeated for the first half or second half. This procedure is repeated till the element is found or the division of half parts gives one element. Example: //***********************Binary search ***************// import C.io.*; class binary { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int arr[]=new int[10]; int i,u,l,m=0; int no; Printf(enter the element of array in sorted form ); for(i=0;i<10;i++) { arr[i]=Integer.parseInt(br.readLine()); } int c=0; u=9; l=0; Printf(enter the element you want to search ); no=Integer.parseInt(br.readLine()); while(l<=u) { m=(l+u)/2; if(no>arr[m]) l=m+1; else if(no<arr[m]) u=m-1; else { c=1; break; }} if(c==1) Printf(no is present at the position +(m+1)); else Printf(no is not present );}}
Sorting Sorting means arranging a set of data in some order. There are different methods that are used to sort the data in ascending or descending order. These methods can be divided into two categories. Internal Sorting: if all the data that is to be sorted can be placed at a time in memory then internal sorting methods are used. 1. Bubble sort. 4. Insertion sort 2. Selection sort. 5. Binary Tree sort (BT-sort) 3. Quick sort 6. Heap Sort. 7. Merge Sort.
External Sorting: When the data is to be sorted is so large that some of the data is present in the memory and some is kept in auxiliary memory (hard disk, floppy, tape, etc.), then external sorting methods are used. In this technique data from the disk is loaded into memory part by part and each part that is loaded is sorted and the sorted data is stored into some intermediate file. Finally all the sorted parts present in different intermediate files are merged into one single file. Bubble Sort-> in this method to arrange elements in ascending order, to begin with the 0th element is compared with the 1st element. If it is found to be greater than the 1st element then they are interchanged. Then the first element is compared with the second element, if it is found to be greater, then they are interchanged. In the same way all the elements are compared with their next element and are interchanged if required. This is the first iteration and on completing this iteration the largest element gets placed at the last position. Similarly in the second iteration the comparisons are made till the last but one element and this time the second largest element gets placed at the second last position in the list. As a result after all the iterations the list becomes a sorted list. Example: Bubble Sort
#include<iostream.h> #include<conio.h> void main() { int arr[5]; int i,j; cout<<"\n enter elements of array "; for(i=0;i<5;i++) cin>>arr[i];
cout<<arr[i]<<" "; getch(); } Selection Sort this is the simplest method of sorting. In this method, to sort the data in ascending order, the 0 th element is compared with all other elements. If the 0the elements found to be greater than the compared element, then they are interchanged. So after the first iteration the smallest element is placed at the 0th position. The same procedure is repeated for the 1st element and so on. Example: #include<stdio.h> #include<conio.h> void main() { int list[5],i,j,t; clrscr(); printf("\n Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]); for(i=0;i<5-1;i++) { for(j=i+1;j<5;j++) { if(list[i]>list[j]) { t=list[i]; list[i]=list[j]; list[j]=t; } } } printf("\n Array elements after sorting "); for(i=0;i<5;i++) printf("%d ",list[i]); getch(); } Insertion Sort Insertion sort is implemented by inserting a particular element at the appropriate position. In this method, the first iteration starts with comparison of 1st element with the 0th element. In the second iteration 2nd element is compared with the 0th element and 1st element. In general, in every iteration an element is compared with all elements before it. During comparison if is found that the element in question can be inserted at a suitable position then space is created for it by shifting the other elements one position to the right and inserting the element at the suitable position. This procedure is repeated for all the elements in the array.
#include<stdio.h> #include<conio.h> void main() { int list[5],i,j,t; clrscr(); printf("\n Enter elements of array "); for(i=0;i<5;i++) scanf("%d",&list[i]);
for(i=1;i<5;i++) { t=list[i]; j=i-1; while(t<list[j]) { list[j+1]=list[j]; j--; } list[j+1]=t; } printf("\n array elements are...."); for(i=0;i<5;i++) printf("%d ",list[i]); getch(); }
Merge Sort Merging means combining two sorted lists into one sorted list. For this the elements from both the sorted lists are compared. The smaller of both the elements is then stored in the third array. The sorting is complete when all the elements from both the list are placed in the third list. Example: /************************Merge sort*******************/ #include<stdio.h> #include<conio.h> void main() { int a[5]; int b[5]; int c[10]; int i,j,k,t; printf("\n Enter elements of first array\n "); for(i=0;i<5;i++) scanf("%d",&a[i]); printf("\n Enter elements of second array\n "); for(i=0;i<5;i++) scanf("%d",&b[i]); for(i=0;i<4;i++) { for(j=i+1;j<5;j++) { if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } if(b[i]>b[j]) { t=b[i]; b[i]=b[j]; b[j]=t; } } } for(i=0,j=0,k=0; k<=9;) { if(a[i]<=b[j]) c[k++]=a[i++]; else c[k++]=b[j++];
if(i==5 || j==5) break; } for(; i<5;i++) c[k++]=a[i]; for(;j<5;j++) c[k++]=b[j]; printf("\n Sorted array is \n"); for(i=0;i<10;i++) printf("%d ",c[i]); getch(); }
/*Maxiumu occurenc of a number in an array*/ #include<iostream.h> #include<conio.h> void main() { int ar[10],i,m[10],l=0; int max=0,p=0; cout<<"\n Entter elements of array "; for(i=0;i<10;i++) cin>>ar[i]; int a,k; for(i=0;i<10;i++) { a=0; k=1; for(int j=0;j<10;j++) { if(j>=i) { if(ar[i]==ar[j] && i!=j) k++; } else if(ar[i]==ar[j]) a=1; } if(a!=1)
{ cout<<"Occurance of "<<ar[i]<<" is "<<k<<endl; if(max<k) { max=k; p=i; } } } cout<<"maximum occurence is of "<<ar[p]<<"that is "<<max; getch(); } /* a[]={2,4,1,6,5,7,9,23,10} convert this array into (by replacing alternative
element with each other {4,2,6,1,7,5,23,9,10}*/ #include<iostream.h> #include<conio.h> void main() { int a[]={2,4,1,6,5,7,9,23,10}; int j=0; for(int i=0;i<9;i=i+2) { j=i+1; int t=a[i]; a[i]=a[j]; a[j]=t; } cout<<"\n===============\n"; for(i=0;i<9;i++) cout<<a[i]<<" "; getch(); } like 2,4 into 4,2 and 1,6 into 6,1
int ar[10],i; int max=0,p=0; cout<<"\n Entter elements of array "; for(i=0;i<10;i++) cin>>ar[i]; int a,k; for(i=0;i<10;i++) { a=0; k=1; for(int j=0;j<10;j++) { if(j>=i) { if(ar[i]==ar[j] && i!=j) k++; } else if(ar[i]==ar[j]) a=1; } if(a!=1) { cout<<"Occurance of "<<ar[i]<<" is "<<k<<endl; if(max<k) { max=k; p=i; } } } cout<<"maximum occurence is of "<<ar[p]<<"that is "<<max; getch(); }
Two-D-Array
/******************initialized array**************/ #include<stdio.h> #include<conio.h> void main() { int matrix[3][3]={{10,20,30},{40,50,60},{70,80,90}};
int i,j; clrscr(); for(i=0;i<3;i++) //rows { for(j=0;j<3;j++) //column { printf("%d ",matrix[i][j]); } printf("\n"); } getch(); }
/***********input by keyboard*****************************/ #include<stdio.h> #include<conio.h> void main() { int matrix[3][3]; int i,j; clrscr(); printf("Enter elements of matrix \n"); for(i=0;i<3;i++) //rows { for(j=0;j<3;j++) //column { scanf("%d",&matrix[i][j]); } printf("\n"); } printf("\n matrix ...\n"); for(i=0;i<3;i++) //rows { for(j=0;j<3;j++) //column { printf("%d ",matrix[i][j]); } printf("\n"); } getch(); } Do the sum of all elements of a matrix? /***********Find max and min element from a matrix**************************/ #include<stdio.h> #include<conio.h>
void main() { int temprature[3][3]; int i,j,max,min; clrscr(); printf("Enter elements of temprature matrix \n"); for(i=0;i<3;i++) //rows { for(j=0;j<3;j++) //column { scanf("%d",&temprature[i][j]); } printf("\n"); } max=temprature[0][0]; min=temprature[0][0]; printf("\n matrix ...\n"); for(i=0;i<3;i++) //rows { for(j=0;j<3;j++) //column { printf("%d ",temprature[i][j]); if(temprature[i][j]>max) max=temprature[i][j]; if(temprature[i][j]<min) min=temprature[i][j]; } printf("\n"); } printf("\n Maxumum temprature is %d ",max); printf("\n Minimum temprature is %d ",min); getch(); } /************Row sum**********************/ #include<stdio.h> #include<conio.h> void main() { int matrix[3][3]; int i,j,s=0; clrscr(); printf("\n Enter elements of matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix[i][j]);
} } printf("\n Matrix row sum....\n"); for(i=0;i<3;i++) { s=0; for(j=0;j<3;j++) { printf("%d",matrix[i][j]); s=s+matrix[i][j]; } printf("--> %d",s); printf("\n"); } getch(); }
/********Column sum******************************/ #include<iostream.h> #include<conio.h> void main() { int matrix[3][3]; int i,j,s; cout<<"\n Enter elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cin>>matrix[i][j]; } } cout<<"\n Column row sum....\n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<matrix[i][j]; } cout<<"\n"; } for(i=0;i<3;i++) { s=0; for(j=0;j<3;j++) { s=s+matrix[j][i];
} cout<<s; } getch(); } /*********Diagnal print***********************************/ #include<iostream.h> #include<conio.h> void main() { int a[3][3]; int i,j; cout<<"\n Enter elements of array "; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cin>>a[i][j]; } } cout<<"\n Array elements are.....\n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(i+j==2 || i==j) cout<<a[i][j]<<" "; else cout<<" "; } cout<<"\n"; } getch(); } /**********Symatric matrix**********************/
1 2 3
2 4 5
3 5 6
clrscr(); printf("\n Enter elements of matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(matrix[i][j]==matrix[j][i]) flag++; } printf("\n"); } if(flag==9) printf("\n it is symatric matrix "); else printf("\n it is not symatric matrix "); getch(); }
/********************half matrix print*****************/ #include<stdio.h> #include<conio.h> void main() { int matrix[3][3]; int i,j; clrscr(); printf("\n Enter elements of matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(i<=j)
//if(i>=j) if((i*j==1) || (i*j==0)) if(!(i+j==1 || i+j==0)) printf("%d",matrix[i][j]); else printf(" "); } printf("\n"); } getch(); }
/*****************matrix sum**********************/ #include<stdio.h> #include<conio.h> void main() { int matrix1[3][3], matrix2[3][3],matrix3[3][3]; int i,j; clrscr(); printf("\n Enter elements of first matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix1[i][j]); } } printf("\n Enter elements of second matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix2[i][j]); } }
/*******************matrix multiplication*******************/ #include<stdio.h> #include<conio.h> void main() { int matrix1[3][3], matrix2[3][3],matrix3[3][3]; int i,j,k; clrscr(); printf("\n Enter elements of first matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix1[i][j]); } } printf("\n Enter elements of second matrix \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&matrix2[i][j]); } }
} printf("\n Sum of elements of matrix is ...\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%d ",matrix3[i][j]); } printf("\n"); } getch(); }
#include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[][3]={{1,2,3},{4,5,6},{7,8,9}}; int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { //if((( i==j) || (i+j==2)) && i*j!=1 ) //if(i*j==1) //if(i*j==1 || i*j==0) if(i+j==3 || i+j==1) cout<<arr[i][j]; else cout<<" "; } cout<<endl; } getch(); } #include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[][3]={{1,2,3},{4,5,6},{7,8,9}}; int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { //if(i<=j) if(i>=j) cout<<arr[i][j]; else cout<<" "; }
cout<<endl; } getch(); }
#include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[]={1,2,3}; int a[3][3]; int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(i*j==0 || i*j==1) a[i][j]=arr[j]; else a[i][j]=0; } } cout<<"\n=============\n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<a[i][j]; } cout<<"\n"; } getch(); }
/*Replacement of Columns*/
#include<iostream.h> #include<conio.h> void main() { int a[3][3]; int i,j,t; cout<<"\n Enter elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cin>>a[i][j]; }
} for(i=0;i<3;i++) { t=a[i][0]; a[i][0]=a[i][2]; a[i][2]=t; } cout<<"\n elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<a[i][j]; } cout<<"\n"; } getch(); }
/*Replacement of Rows*/
#include<iostream.h> #include<conio.h> void main() { int a[3][3]; int i,j,t; cout<<"\n Enter elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cin>>a[i][j]; } } j=2; for(i=0;i<3;i++) { t=a[0][i]; a[0][i]=a[j][i]; a[j][i]=t; } cout<<"\n elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<a[i][j]; } cout<<"\n";
} getch(); }
/*Print the following shape of matrix from an array*/ 100000 120000 123000 123400 123450 123456 #include<iostream.h> #include<conio.h> void conversion(int a[], int n) { int b[6][6]; int i,j; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i>=j) b[i][j]=a[j]; else b[i][j]=0; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { cout<<b[i][j]; } cout<<"\n"; } } void main() { int a[]={1,2,3,4,5,6}; int n=6; conversion(a,n); getch(); } /*Maxiumu occurenc of a number in an array*/ #include<iostream.h>
#include<conio.h> void main() { int ar[10],i; int max=0,p=0; cout<<"\n Entter elements of array "; for(i=0;i<10;i++) cin>>ar[i]; int a,k; for(i=0;i<10;i++) { a=0; k=1; for(int j=0;j<10;j++) { if(j>=i) { if(ar[i]==ar[j] && i!=j) k++; } else if(ar[i]==ar[j]) a=1; } if(a!=1) { cout<<"Occurance of "<<ar[i]<<" is "<<k<<endl; if(max<k) { max=k; p=i; } } } cout<<"maximum occurence is of "<<ar[p]<<"that is "<<max; getch(); }
Column Major Arrays address calculation when base address not given
Base Array is T [50] [20] Location of T [25] [10] =9800 Byte of each elements is =4 Location is to find of T [30] [15] = is to find? Solution Location=Base Address + Byte ((searched array row*Row of Base Array) + searched array column) T[25] [10] = Base Address + 4 (25+10*50) 9800 = Base Address+ 4(25+500) 9800 =Base address+4(525) 9800 =Base address+2100 Base Address=9800-21007700 T[30] [15]= 7700+4(30+15*50) = 7700+4(30+750) = 7700+4(780) = 7700+3120 =10820
Strings
String is the sequence of characters. #include<iostream.h> #include<conio.h> #include<ctype.h> void main() { char ch1,ch2; cout<<"\n entter a character in lower case \n"; cin>>ch1; cout<<(char)toupper(ch1); if(islower(ch1)) cout<<"\n It is lower case latter "; cout<<"\n Enter a character in upper case \n "; cin>>ch2; cout<<(char)tolower(ch2); if(isupper(ch2)) cout<<"\n It is upper case latter "; getch(); } /**********string initialization******/ #include<iostream.h> #include<conio.h> void main() { char name[]={'a','r','i','f','\0'}; cout<<name; char s[]="Mohammad Arif"; cout<<"\n"<<s; getch(); } /****string by keyboard**********/ #include<iostream.h>
#include<conio.h> #include<stdio.h> void main() { char name[25]; cout<<endl<< "enter name "; gets(name); puts(name); getch(); } /***********counter the number of character in a string*********/ #include<iostream.h> #include<stdio.h> #include<conio.h> #include<string.h> void main() { char name[20]; cout<<"\n Enter your name "; gets(name); puts(name); int c=0; for(int i=0;i<strlen(name);i++) { if(name[i]!=' ') c++; } cout<<"\n Number of character in string is "<<c; getch(); } /*************occurrence of specific character************/ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { int c=0; char ch; char name[25]; cout<<endl<< "enter name "; gets(name); cout<<"\n enter name that you want to search "; cin>>ch; for(int i=0;i<strlen(name);i++) { if(name[i]==ch)
c++; } cout<<"\n Occurence of character is "<<c; getch(); } /*********count the word in a string*************/ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { char name[25]; int i,c=1; cout<<"\n Enter name "; gets(name); puts(name); for(i=0;name[i]!='\0';i++) if(name[i]==' ' && name[i+1]!=' ') c++; cout<<c; getch(); } /*************count the vowals in a string *****************/ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { char name[25]; int i,c=0; cout<<"\n Enter name "; gets(name); puts(name); for(i=0;name[i]!='\0';i++) if(name[i]=='a' || name[i]=='e' || name[i]=='i' || name[i]=='o' || name[i]=='u') c++; cout<<c; getch(); } /************Frequenc of each character in small case string******/ #include<iostream.h> #include<stdio.h> #include<conio.h> #include<string.h>
void main() { char str[25],c; int i,j,l,small,n; cout<<"\n Enter a string in small case latter \n"; gets(str); l=strlen(str); for(i=97;i<=122;i++) { small=0; for(j=0;j<l;j++) { n=str[j]; if(n==i) small++; } if(small>0) { c=(char)i; cout<<c<<"\n comes "<<small<" times \n"; } } getch(); } /**************Initial Capital (mohammad arif ansari-->M.A.A.)***/ #include<iostream.h> #include<stdio.h> #include<conio.h> #include<string.h> void main() { char name[20]; cout<<"\n Enter your name "; gets(name); int n,i; n=name[0]; if(n>=97 && n<=122) n=n-32; cout<<(char)n<<"."; for(i=1;i<strlen(name);i++) { if(name[i]==' ' && name[i+1]!=' ') {
/*********reverse string word by word***********/ #include<conio.h> #include<string.h> #include<iostream.h> #include<stdio.h> void main() { char str[25]; int c=0; int i,j,l; cout<<"\n Enter a string in small case latter \n"; gets(str);
strcat(str," "); l=strlen(str); for(i=0;i<l;i++) { if(str[i]==' ') { for(j=i-1;j>=c;j--) cout<<str[j]; c=i+1; cout<<" "; } } getch(); } /************string class function**************/ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> #include<ctype.h> void main() {
char str1[]="Mohammad"; char str2[]=" Arif"; strcat(str1,str2); cout<<str1; strcpy(str1,"Abc"); cout<<"\n"<<str1; int d=strcmp("arif","Arif"); cout<<"\n"<<d; char ch='a'; cout<<"\n"<<(char)toupper(ch); ch='S'; cout<<"\n"<<(char)tolower(ch); cout<<"\n"<<isupper('A'); cout<<"\n"<<islower('F'); getch(); } /***************Shape**********/ #include<conio.h> #include<string.h> #include<iostream.h> #include<stdio.h> void main() { char s1[10]="Mohammad"; int i,j; for(i=strlen(s1)-1;i>=0;i--) { for(j=0;j<=i;j++) { cout<<s1[j]; } cout<<endl; } getch(); } /***********consecutive string*************/ #include<iostream.h> #include<conio.h> #include<stdio.h> void main() {
char str[25]; int i,j,c=0; cout<<"\n Enter a string "; gets(str); char ch1,ch2; for(i=0;i<strlen(str);i++) { ch1=str[i]; ch2=str[i+1]; for(char ch='a'; ch<='z';ch++) { if(ch1==ch && ch2==(++ch)) { c=1; break; } } } if(c==1) cout<<"\n Consecutive string "; else cout<<"\n Not Consecutive string "; getch(); } /****************Palindrome string****************/ #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { char str[25]; int i,j,c=0; cout<<"\n Enter a string "; gets(str); for(i=0,j=strlen(str)-1;i<=j;i++,j--) { if(str[i]!=str[j]) { c=1; break; } } if(c==0) cout<<"\n It is palindrome string "; else
Functions
Methods are known as functions in C and C++. A method (function) is set of instructions that perform a specific task. Method (Functions) can accept a set of values as arguments from the calling program and process them and pass the results back to its callar after execution of the method. When a program passes control to a method, the method does the task and returns control to the calling instruction of the program. Parts of function: 1. Function Prototype: this part contains return type, name and type of arguments of function. Prototype tells the program about the type of the value return by the function and the number and type of arguments. Signature: a function signature basically refers to the number and types of arguments. It is a part of the function prototype. Function signature and return type make a functions prototype. But sometime the term function signature is used to refer to a function prototype. Calling of function: this part contain name and values that we are passing as an argument to the function. Example: sum(10,20); Function Definition: this part contain return type, name and arguments types and their values , beside this , this part also contain body block in which we can perform on the values that we getting as argument. This part is similar to parameter. Example: int sum(int x, int y) { Body of function; } Types of functions: 1. Library function 2. User define function
Library Functions: These are known as built in function which already remains in the library of the language. There is no need to take prototype or declare definition for these functions because their prototype is present in the header file of C and C++ or in the Classes of C, and definition in the library of language so we directly call them in our program and used the value return by them. Example: pow(base, power), sqry(value), cos(value). #include<Math.h> void main() { int base,power; cout<<\n enter the value base ;
cin>>base; cout<<\n enter the value of power ; cin>>power; cout<<power is <<pow(base,power); cout<<\n\n\n\n;cout<<Squar Root is<<sqrt(144); cout<<\n\n\n\n; cout<<Value of cos <<cos(99); getch(); } Users define Functions: these functions are defined by the user. So we are in need to declare prototype, to call them and need to give definition of them in our program to use them. Example:
Fahrenheit=9/5*c+32 Celcius=5/9*(f-32)
2. The distance between two cities (in KM.) is input through keyboard and converts it into metter, feet, inches and centimeters by function.
cout<<\n Sum is <<s; int a=sum(a,b); //call cout<<\n sum is <<a; getch(); } int sum(int x, int y) //defination { return x+y; } 1. Function with if else 2. Function with switch Create a function to perform following operation while recieveing value from main. 1. Area of circle 2. Area of rectangle 3. Function with loops 4. Function with strings #include<iostream.h> #include<conio.h> void print(char []); void main() { char name[]="Amit Chauhan"; print(name); getch(); } void print(char n[]) { cout<<n; } Function with functions Function with structure Function with pointer Function with array User define functions are of two types. 1. Call by Value 2. Call by Reference 1. Call by Value: The call by value method copies the values of actual parameters into the formal parameters, that the function creates its own copy of argument values and then uses them. Of if any change takes place to the formal parameter than it will not show any effect to the actual parameter, because function is working on copy of the original values. Thus in calls by value method changes are not reflected back to the original values.
5. 6. 7. 8.
Example: #include<stdio.h> #include<conio.h> void swaping(int , int ); void main() { int a=10; int b=20; printf("\n value of a before swaping %d ",a); printf("\n value of b before swaping %d ",b); swaping(a,b); printf("\n value of a after swaping %d ",a); printf("\n value of b after swaping %d ",b); getch(); } void swaping(int a, int b) { a=a+b; b=a-b; a=a-b; printf("\n value of a %d ",a); printf("\n value of b %d ",b); } 2. Call by Reference: in call by reference method we pass a reference of the original variable to the function definition. When a function is called by reference then the formal parameters gets references of the actual parameters in the calling function. This means that in call by reference method, the called function does not create its own copy of original values, rather it refers to the original variable only by different names i.e. the references.
void main() { int a=10; int b=20; printf("\n value of a before swaping %d ",a); printf("\n value of b before swaping %d ",b); swaping(&a,&b); printf("\n value of a after swaping %d ",a); printf("\n value of b after swaping %d ",b); getch(); }
void swaping(int *a, int *b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; printf("\n value of a %d ",*a); printf("\n value of b %d ",*b); }
Example: in c++
Function overloading: When a program have more than one function with same name but different number of argument and with different data type, then it is known as function overloading. Overloading by default argument: #include<iostream.h> #include<conio.h> void calc(long pa=5000, float rate=12.5, int time=5); void main() { calc(6000); cout<<endl; calc(10000,11.25); cout<<endl; calc(4000,12.23,2); getch(); } void calc(long pa, float r, int t) { float si=pa*r*t/100; cout<<si; }
#include<conio.h> void swaping(int *, int *); void main() { clrscr(); int a,b; a=10;b=20; cout<<"\n value of a in main before swaping"<<a; cout<<"\n value of b in main before swaping "<<b; swaping(&a,&b); cout<<"\n value of a in main after swaping"<<a; cout<<"\n value of b in main after swaping "<<b; getch(); } void swaping(int *a, int *b) { int t=*a; *a=*b; *b=t; cout<<"\n value of a "<<*a; cout<<"\n value of b "<<*b; }
/*******return by reference*********/
#include<iostream.h> #include<conio.h> int & greater(int &, int &); void main() { int a=10,b=20; cout<<greater(a,b); getch(); } int & greater(int &a, int & b) { if(a>b) return a; else return b; }
Inline Function: The inline functions are a c++ enhancement designed to speed up programs. The coding of these function and normal function is same except that the inline function starts with inline keyword. The distinction between normal and inline function is the different compilation process for them. Rules: 1. An inline function must not be large than one line 2. An inline function definition should be placed above all the function definition. 3. It must be preceded by inline keyword. 4. Its definition must be befoe main. 5. Theres is not need of prototype for inline function. Some of the situations where inline expansion may not work are: 1. For functions returning values, if a loop, a switch, or a goto exits. 2. For functions not returining values, if a return statement exists. 3. If function contain static variable. 4. If inline functions are recursive. #include<iostream.h> #include<conio.h> inline int sum(int a, int b) { return a+b; } void main() { cout<<sum(10,20)<<endl; cout<<sum(5,10)<<endl; cout<<sum(1,2)<<endl; getch(); } Constant qualifier: constant qualifier tell the computr that the function should not modify the argument. The compilar will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by pointer or by reference. #include<iostream.h>
#include<conio.h> void replace(const int); void change(const int *p); void convert(const char &ch); void main() { int a=10; change(&a); char ch='a'; convert(ch); int c=10; replace(c); getch(); } void change(const int *p) { *p=*p+20; cout<<*p; } void convert(const char &ch) { ch='b'; cout<<ch; } void replace(const int c) { c=c+30; cout<<c; } The main Function: It is starting point for execution of program. C++ main can return an integer value to operating system. Normally we return 0 from main which sends a signal to the operating system that program was executed successfully. If we return a non zero value, it means program was not executed scuccesfully. #include<iostream.h> #include<conio.h> int main() { cout<<"hello"; getch(); return 0; }
int fact(int);
cout<<fact(num); getch(); }
int fact(int); void main() { int num; cout<<"\n enter a positive number "; cin>>num; cout<<fact(num); getch(); } int fact(int n) { return n<2?1:(n*fact(n-1)); } /*******Fibonacci series by Recursion******/ #include<iostream.h> #include<conio.h> int fib(int); void main() { int i; for(i=0;i<=10;i++) cout<<fib(i)<<" "; getch(); } int fib(int i) { if(i==0) return 0; else if(i==1 || i==2) return 1; else return fib(i-1)+fib(i-2); } example: /*print 20 number in reverse order by recursive function*/ #include<iostream.h> #include<conio.h> void reverse(int i); void main()
{ int i=20; reverse(i); getch(); } void reverse(int i) { if(i==1) cout<<i<<" "; else { cout<<i<<" "; reverse(--i); } }
int fib(int);
int fib(int i) { if(i==0) return 0; else if(i==1 || i==2) return 1; else return fib(i-1)+fib(i-2); }
int mult(int , int ); void main() { int a,b; cout<<"\n enter the vlaue of a and b "; cin>>a>>b; cout<<mult(a,b); getch(); } int mult(int a, int b) { if(b==0) return a; else if(b==1) return a; else return (a+mult(a,b-1)); }
5. Functions transform data from one form to another. 6. Employs top-down approach in program design. Object Oriented Programming: Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Characteristics of OOP 1. Emphasis is on data rather than procedure. 2. Programs are divided into what are known as objects. 3. Data structures are designed such that they characterized the objects. 4. Functions that operate on the data of an object are tied together in the data structure. 5. Data is hidden and cannot be accessed by external functions. 6. Objects may communicate with each other through functions. 7. New data and functions can be easily added whenever necessary. 8. Follows bottom-up approach in program design. Class: A class is an entity that binds data and its associated functions together. In c++ class makes a data type that is used to create objects of this type. Or A class is a collection of objects of similar type. For example, mango, apple etc are members of the class fruit. Class is user define data type but behaves like the built in types. Need for classes: Classes are needed to represent real world entities that not only have data type properties (their characteristics) but also have associated operations (their behavior). Declaration of class class <class name> { Variable or data member declaration. Method or member function declaration. }; Example class sum { int a,b,c; void getdata() { a=10;
b=20; c=0; } Void add() { c=a+b; } void show() { Cout<<\n Sum is <<c; } }; void main() { Sum s; s.getdata(); s.add(); s.show(); } The class method definition: Member functions can be defined in two places: 1. Outside the class definition (bookish method) 2. Inside the class definition (general method) Outside the class definition: A member function definition outside the class definition contains a full-name or qualified name of a function which can be written as: <Function return type> <class name> :: <function name>(argument list) { Body of function } Example:/*class with bookish method*/ #include<iostream.h> #include<conio.h> class Demo { int a,b,c;
public : void getdata(); void showdata(); }; void Demo :: getdata() { cout<<"\n Enter value of a and b "; cin>>a>>b; } void Demo :: showdata() { cout<<"\n Value of a "<<a; cout<<"\n Value of b "<<b; } void main() { Demo d; d.getdata(); d.showdata(); getch(); } Inside the class definition /*class with bookish method*/ #include<iostream.h> #include<conio.h> class Demo { int a,b,c; public : void getdata() { cout<<"\n Enter value of a and b "; cin>>a>>b;
} void showdata() { cout<<"\n Value of a "<<a; cout<<"\n Value of b "<<b; } }; void main() { Demo d; d.getdata(); d.showdata(); getch(); } /*Arrays within a class*/ #include<iostream.h> #include<conio.h> class Array { int arr[5]; int i; public: void getarray() { cout<<"\n Enter the elements of array "; for(i=0;i<5;i++) cin>>arr[i]; } void showarray() {
cout<<"\n Array elements are "; for(i=0;i<5;i++) cout<<arr[i]<<" "; } }; void main() { Array obj; obj.getarray(); obj.showarray(); getch(); } /*********************insertion of an element in an array****************/ #include<iostream.h> #include<conio.h> class insertion { int arr[100], size,i,p,num; public : void getarray() { cout<<"\n Enter the size of array "; cin>>size; cout<<"\n enter the elements of array "; for(i=0;i<size;i++) cin>>arr[i]; } void showarray() { cout<<"\n Array elements are.......\n"; for(i=0;i<size;i++)
cout<<arr[i]<<" "; } void insert() { int c=0; cout<<"\n Enter the position where you want to insert "; cin>>p; for(i=0;i<size;i++) { if(i==p) { c=1; break; } } if(c==1) { for(i=size;i>=p;i--) arr[i]=arr[i-1]; cout<<"\n enter a number that is to insert "; cin>>num; arr[p]=num; size++; } else cout<<"\n Position not found "; } }; void main() { insertion obj;
obj.getarray(); obj.insert(); obj.showarray(); getch(); } /******************Deletion of an element from an array*********/ #include<iostream.h> #include<conio.h> #define size 10 class deletion { int arr[size],i,num; public : void getarray() { cout<<"\n enter the elements of array "; for(i=0;i<size;i++) cin>>arr[i]; } void showarray() { cout<<"\n Array elements are.......\n"; for(i=0;i<size-1;i++) cout<<arr[i]<<" "; } void del() { int c=0,p=0;
cout<<"\n enter a number that is to delete "; cin>>num; for(i=0;i<size;i++) { if(num==arr[i]) { c=1; p=i; break; } } if(c==1) { for(i=p;i<(size-1);i++) arr[i]=arr[i+1]; } else cout<<"\n Position not found "; } }; void main() { deletion obj; obj.getarray(); obj.del(); obj.showarray(); getch(); } /*object array*/ #include<iostream.h> #include<conio.h> #include<stdio.h>
class Records { char name[25]; int age; char address[50]; public: void getrecords() { cout<<"\n Enter name "; gets(name); cout<<"\n Enter age "; cin>>age; cout<<"\n Enter address "; gets(address); } void showrecords() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; cout<<"\n Address = "<<address; } }; void main() { Records r[3]; int i; for(i=0;i<3;i++) r[i].getrecords(); cout<<"\n Records Are .. \n"; for(i=0;i<3;i++) { r[i].showrecords(); cout<<"\n==============================\n"; }
getch(); } Scope of class and its members: A class in c++ represents a group of data and associated functions divided into one or more of these parts: public, private and protected. 1. Public members: These are the members that can be directly accessed by any function. Whether that function belongs to same class or not. Example: /*Demo of public members*/ #include<iostream.h> #include<stdio.h> class X { public: int a; int sqr(int m) { return m*m; } }; void main() { X obj; int b; obj.a=10; //public data member can be used in any function b=obj.sqr(15); //public member function can be invoked from any function cout<<"\n value of b "<<b; getch(); } Private Members: These members are hidden from the outside world. These cannot access outside their class. The private members implement the OOP concept of data hiding. The private members of a class can be used by member function of this class. /*Demo of private members*/ #include<iostream.h> #include<conio.h> class X
{ private : int a; int sqr(int m) { return m*m; } public : int b; int twice(int i) { return 2*i; } }; void main() { X obj; obj.a=10;//not accisible due to private obj.b=20;//accesible due to public cout<<obj.sqr(20);//not accisible due to private cout<<obj.twice(2);//accisible due to public getch(); } Protected members: These are the members that can be used only by member functions and friends of the class in which it is declared. The protected members are similar to private members that they cannot be accessed by non-member functions. The scope rules and classes: Classes are of two type on the basis of scope: 1. Local class: A class is said to be local class if its definition occurs inside a function body, which means that objects of this class can be declared only within the function that defines this class. #include<iostream.h>
#include<conio.h> void main() { class X { private: int a; public : void getvalue() { a=10; } void showvalue() { cout<<"\n value is "<<a; } }; X obj; obj.getvalue(); obj.showvalue(); getch(); } 2. Global class: A class is said to be global class if its definition occurs outside the bodies of all functions in a program, which means that objects of this class can be declared from anywhere in the program. #include<iostream.h> #include<conio.h> class X { private: int a; public :
void getvalue() { a=10; } void showvalue() { cout<<"\n value is "<<a; } }; X obj; void main() { X obj2; obj2.getvalue(); obj2.showvalue(); getch(); } Global Object: An object is said to be global object if it is declared outside all function bodies and it means that this object is globally available to all functions in the program i.e. this object can be used anywhere in the program. #include<iostream.h> #include<conio.h> class X { private : int a; public : void getvalue() { a=20; }
void showvalue() { cout<<a; } }; X obj1; //global objecct void main() { obj1.getvalue(); obj1.showvalue(); getch(); } Local objects: An object is said to be local object if it is declared inside a function body, which means that this object is locally available to the function that declareds it and it cannot be used outside the function declaring it. #include<iostream.h> #include<conio.h> class X { public : int a; void getvalue() { a=10; } void showvalue() { cout<<"\n value of a is "<<a; }
}; void main() { class Y { public : int b; void getdata() { b=20; } Void calc() { b=b+10; } void showdata() { cout<<"\n value of b "<<b; } }; X obj1;//local object of global class Y obj2; //local object of local class obj1.getvalue(); obj1.showvalue(); obj2.getdata(); obj2.showdata(); getch(); }
Types of class Functions:The member functions of a class can be categorized into following categories: 1. Accestor function: These are those functions that allow us to access the data for fields. Example getvalue() function of above program. 2. Mutator function: These are those functions that allow us to change or manipulate the value of fields. Example: calc() function of above program. 3. Manager function:These are special function like constructor and destructor that meanly deal with initialization of class variable and destroying objects of class. Example of all above technique #include<iostream.h> #include<conio.h> #include<stdio.h> #include<process.h> class Student { private : char name[25]; char grade; public : int rollno; float marks; void readstudent() //mutator { cout<<"\n enter name "; cin>>name; cout<<"\n enter rollno "; cin>>rollno; cout<<"\n enter marks "; cin>>marks; } void displaystudent() { calc();
cout<<"\n Rollno = "<<rollno; cout<<"\n Name = "<<name; cout<<"\n Marks = "<<marks; cout<<"\n Grade = "<<grade; } void calc() { if(marks>=75) grade='A'; else if(marks>=60) grade='B'; else if(marks>=50) grade='C'; else if(marks>=40) grade='D'; else grade='F'; } }; void main() { int i; Student s[3]; for(i=0;i<3;i++) s[i].readstudent(); int ch=1,rno,highestmarks=0; do { cout<<"\n 1 : Specific Student "; cout<<"\n 2 : Topper "; cout<<"\n 3 : exit "; cout<<"\n Enter your choice ";
cin>>ch; switch(ch) { case 1: cout<<"\n Enter the rollno of student whose result you want to see "; cin>>rno; for(i=0;i<3;i++) { if(s[i].rollno==rno) { s[i].displaystudent(); break; } } if(i==3) cout<<"\n Invalid Rollno "; break; case 2: int p=0; for(i=0;i<3;i++) { if(s[i].marks>highestmarks) { highestmarks=s[i].marks; p=i; } } s[p].displaystudent(); break; } }while(ch>=1 && ch<=3); getch(); } Nested Class: A class may be declared within another class. This process is called nesting of class.
#include<iostream.h> #include<conio.h> class outer { class inner { public : int b; void print() { cout<<"\nvalue of b "<<b; } }; public : int a; inner obj; void display() { cout<<"\n value of a "<<a; } }; void main() { outer ob; ob.a=10; ob.display(); ob.obj.b=100; ob.obj.print();
getch(); } Data Encapsulation: Wrapping up of data and functions together in a single unit is known as data encapsulation. In a class we wrap up the data and function together in a single unit. Data hiding: Keeping the data in private or protected visibility mode of the class to prevent it from accidental changes is known as data hiding. Abstracation: It refers to the act of representing essential features without including the background details or explanations. Abstraction support data hiding so that only relevant information is exposed to the user and rest of the information remains hidden from the user. Inline function with class:The inline functions are a c++ enhancement designed to speed up programs. The coding of these function and normal function is same except that the inline function starts with inline keyword. The distinction between normal and inline function is the different compilation process for them. Rules: 6. An inline function must not be large than one line 7. An inline function definition should be placed above all the function definition. Some of the situations where inline expansion may not work are: 5. For functions returning values, if a loop, a switch, or a goto exits. 6. For functions not #include<iostream.h> #include<conio.h> inline int sum(int a, int b) { return a+b; } void main() { cout<<sum(10,20)<<endl; cout<<sum(5,10)<<endl; cout<<sum(1,2)<<endl; getch(); }
#include<conio.h> class inlinedemo { public: inline int sum(int a, int b) { return a+b; } }; void main() { inlinedemo obj; cout<<obj.sum(10,20)<<endl; cout<<obj.sum(2,4)<<endl; cout<<obj.sum(1,4)<<endl; getch(); } Object as argument by value and by reference: /****************passing object to a function by value********/ #include<iostream.h> #include<conio.h> class byval { public : int a; void show(byval obj) { cout<<obj.a; } }; void main() {
byval obj; obj.a=10; obj.show(obj); getch(); } /****************passing object to a function by reference********/ #include<iostream.h> #include<conio.h> class byval { public : int a; void show(byval &obj) { obj.a=20; cout<<obj.a; } }; void main() { byval obj; obj.a=10; obj.show(obj); cout<<"\n"; cout<<obj.a; getch(); } /************passing object to a function by value*******/ #include<iostream.h> #include<conio.h>
class Time { int h,m,s; public: Time() { h=0; m=0; s=0; } Time(int hours, int mint, int second) { h=hours; m=mint; s=second; } void showtime() { cout<<h<<"\t"<<m<<"\t"<<s<<endl; } Time add(Time t1, Time t2) { Time t; t.h=t1.h+t2.h; t.m=t1.m+t2.m; t.s=t1.s+t2.s; while(t.s>=60) { t.s=t.s-60;
t.m++; } while(t.m>=60) { t.m=t.m-60; t.h++; } return t; } }; void main() { Time t1(2,35,25),t2(4,45,35); cout<<"\n Hours\t Mint\tSecond \n"; t1.showtime(); t2.showtime(); Time t; t=t.add(t1,t2); cout<<"\n===================\n"; t.showtime(); getch(); }
/**************passing object by reference************/ #include<iostream.h> #include<conio.h> class byref { public: int num;
byref(int n) { num=n; }
void reverse(byref &obj) { int r,s=0; while(obj.num>0) { r=obj.num%10; s=s*10+r; obj.num=obj.num/10; } cout<<"\n revers number is "<<s; } }; void main() { byref obj(1234); obj.reverse(obj); cout<<"\n value of num "<<obj.num; getch(); } /********************Static membe demo**********/ 1. Static variable is declared by using static key before its name at the time of declratifon. 2. Static variable are global in nature. 3. Static variable auto initialized by zero. #include<iostream.h> #include<conio.h> class staticdemo {
static int a; public: staticdemo() { a++; } void show() { cout<<"\n value of a "<<a; } }; int staticdemo::a; void main() { staticdemo s1; s1.show(); staticdemo s2; s2.show(); staticdemo s3; s3.show(); getch(); } /********static function demo********/ 1. Static function always called by class name 2. Static function works with static variable only. 3. Static function declared by using static key word before its name in definition. #include<iostream.h> #include<conio.h> class staticfunction { public :
static int a; staticfunction() { a++; } static void show() { cout<<a; } }; int staticfunction::a; void main() { staticfunction s1,s2; staticfunction::show(); getch(); } Constant member function: If a member function does not alter data in function body, then we may declare it as a const member function. #include<iostream.h> #include<conio.h> void calc(int , int )const; int show(int)const; void main() { calc(10,20); cout<<show(20); getch(); }
void calc(int a, int b) const { a=a+b; } int show(int a) const { return a=a+20; }
Constant variable
#include<iostream.h> #include<conio.h> class abc { const int a; public: void show() { a=a+10; //constant variable } }; void main() { abc obj; obj.show(); getch(); } Friend function: When we want that a function should shared by two class then we can declare it as friend. A friend function have access to private data of both the class but its own definition remains out the both classes and its prototype with friend keyword are present in both the class. The function definition should not contain friend keyword before its name but its prototype in both classes have friend in beginning of their name. Features of function: 1. Its definition is not in the classes for which it is declared as friend.
2. It cant be called by object of any sharing class. 3. It can be called like a normal function without any object. 4. It can be declared in either private or public part of the class without effecting its meaning. 5. Usually it has the objects of its sharing classes as argument. 6. It can access private members of class by dot (.) operator. #include<iostream.h> #include<conio.h> class abc; class xyz { private : int x; public : xyz(int a) { x=a; } friend void max(abc, xyz); }; class abc { private: int a; public: abc(int x) { a=x; } friend void max(abc, xyz);
}; void max(abc s1, xyz s2) { if(s1.a>s2.x) cout<<"\n A is greater "; else cout<<"\n X is greater "; } void main() { abc s1(5); xyz s2(7); max(s1,s2); getch(); }
Inheritance
It is the capability of one class to inherit the properties from another class. Or this process lets us to derived a new class (derived class) from an old one (base class). Use of Inheritance: The most important benefit of inheritance is code reusability. Need for inheritance: Inheritance is the main concept of OOP. 1. The capability to express the inheritance relationship which ensures the closeness with the real world models. 2. Another reason is the concept of reusability. The advantage of reusability are faster development time, easier maintenance and easy to extend. Inheritance allows the addition of additional features to an existing class without modifying it. One can derive a new class from an existing one and add new features to it.
3. One reason is transitive nature of inheritance. For example if A class inherits the properties of class B and Class C inherits the properties of class B then Class C automatically will inherit the properties of class A, this feature is known as transitive property. Different forms of inheritance: Inheritance is of five types. 1. Single inheritance: When a subclass inherits only from one base class, it is known as single inheritance. 2. Multiple Inheritance: When a sub class inherits from multiple base classes, it is known as multiple inheritance. 3. Hierarchical Inheritance: When many sub classes inherits from a single base class, it is known as hierarchical inheritance. 4. Multilevel inheritance: The transitive nature of inheritance is reflected by this form of inheritance. When a subclass inherits from a class that itself inherits from another class, it is known as multilevel inheritance. 5. Hybrid inheritance: Hybrid inheritance combines two or more forms of inheritance. E.g. when a sub class inherits from multiple base classes and its entire base classes inherit from a single base class, this form of inheritance is known as hybrid inheritance. Note: The relationship between a base and derived class is referred to as a derivation or inheritance hierarchy. A derivation from multiple base classes is referred to as a derivation or inheritance graph. Private Inheritance: When a base class is privately inherited by a derived class, public members of the base class become private members of the derived class and therefore the public members of the base class can only be accessed by the member functions of the derived class. These are inaccessible to the object of the derived class. Public inheritance: In this type inheritance the public members of the base class become public members of the derived class and therefore they are accessible to the objects of the derived class. Protected Inheritance: In this type of inheritance the public and protected members of the base class become protected members of derived class. Note: In both the cases private members of parent class are not accessible at all.
void getstudent() { cout<<"\n Enter name and age "; gets(name); cin>>age; } void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; } }; class study : student // private inheritance { int phy,che,math; public: void getstudy() { getstudent(); cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() { showstudent(); cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math;
int phy,che,math; public: void getstudy() { cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() { cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } }; void main() { study s; s.getstudent(); s.getstudy(); s.showstudent(); s.showstudy(); getch(); }
#include<stdio.h> class student { char name[25]; int age; public: void getstudent() { cout<<"\n Enter name and age "; gets(name); cin>>age; } void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; } }; class study : public student // public inheritance { int phy,che,math; public: void getstudy() { getstudent(); cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; }
void showstudy() { showstudent(); cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } }; class sports:private study //private inheritance { char team[25]; int rank; public: void getsports() { getstudy(); cout<<"\n Enter Team name "; gets(team); cout<<"\n Enter rank "; cin>>rank; } void showsports() { showstudy(); cout<<"\n Team is "<<team; cout<<"\n Rank is "<<rank; } }; void main() { sports s; s.getsports();
s.showsports(); getch(); }
Hierarchical inheritance
#include<iostream.h> #include<conio.h> #include<stdio.h> class student { char name[25]; int age; public: void getstudent() { cout<<"\n Enter name and age "; gets(name); cin>>age; } void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; } }; class study : public student { int phy,che,math; public: void getstudy() { getstudent(); cout<<"\n Enter marks of physics ";
cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() { showstudent(); cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } }; class sports: public student { char team[25]; int rank; public: void getsports() { getstudent(); cout<<"\n Enter Team name "; gets(team); cout<<"\n Enter rank "; cin>>rank; } void showsports() { showstudent(); cout<<"\n Team is "<<team; cout<<"\n Rank is "<<rank;
} }; void main() { study s; s.getstudy(); s.showstudy(); sports obj; obj.getsports(); obj.showsports(); getch(); }
Multiple inheritance
#include<iostream.h> #include<conio.h> #include<stdio.h> class study { int phy,che,math; public: void getstudy() { cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() {
cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } }; class sports { char team[25]; int rank; public: void getsports() { cout<<"\n Enter Team name "; gets(team); cout<<"\n Enter rank "; cin>>rank; } void showsports() { cout<<"\n Team is "<<team; cout<<"\n Rank is "<<rank; } }; class student : public study, public sports { char name[25]; int age; public: void getstudent() { cout<<"\n Enter name and age "; gets(name);
cin>>age; getstudy(); getsports(); } void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; showstudy(); showsports(); } }; void main() { student s; s.getstudent(); s.showstudent(); getch(); }
Hybrid Inheritance
#include<iostream.h> #include<conio.h> #include<stdio.h> class student { char name[25]; int age; public: void getstudent() { cout<<"\n Enter name and age ";
gets(name); cin>>age; } void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; } }; class study : public student // public inheritance { public: int phy,che,math; void getstudy() { getstudent(); cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() { showstudent(); cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } };
class sports { char team[25]; int rank; public: void getsports() { cout<<"\n Enter Team name "; gets(team); cout<<"\n Enter rank "; cin>>rank; } void showsports() { cout<<"\n Team is "<<team; cout<<"\n Rank is "<<rank; } }; class result : public study, public sports { int total; public: void calculate() { total=phy+che+math; } void display() { cout<<"\n Total is "<<total; } };
void main() { result r; r.getstudy(); r.getsports(); r.calculate(); cout<<"\n============\n"; r.showstudy(); r.showsports(); r.display(); getch(); } Virtual Base class: When two or more objects are derived from a common base class, you can prevent multiple copies of base class from being present in an object derived from those objects by declaring the base class as virtual when it is inherited. This is accomplished by putting the keyword virtual before the base classs name when it is inherited. The only difference between normal base class and a virtual one is when an object inherits the base more than once. If virtual base classes are used, then only one base class is present in the object. Otherwise, multiple copies will be found.
void showstudent() { cout<<"\n Name = "<<name; cout<<"\n Age = "<<age; } }; class study : public virtual student // public inheritance { public: int phy,che,math; void getstudy() { cout<<"\n Enter marks of physics "; cin>>phy; cout<<"\n Enter marks of chemistry "; cin>>che; cout<<"\n Enter marks of math "; cin>>math; } void showstudy() { cout<<"\n Physics "<<phy; cout<<"\n chemistry "<<che; cout<<"\n Math "<<math; } }; class sports : virtual public student { char team[25]; int rank; public:
void getsports() { cout<<"\n Enter Team name "; gets(team); cout<<"\n Enter rank "; cin>>rank; } void showsports() { cout<<"\n Team is "<<team; cout<<"\n Rank is "<<rank; } }; class result : public study, public sports { int total; public: void calculate() { total=phy+che+math; } void display() { showstudent(); showstudy(); showsports(); cout<<"\n Total is "<<total; } }; void main()
{ result r; r.getstudent(); r.getstudy(); r.getsports(); r.calculate(); cout<<"\n============\n"; r.display(); getch(); } Pure virtual function:The function inside the base class is seldom used for performing any task. It only serves as a placeholder. Such function is called do-nothing function or pure virtual function. Example: virtual void display()=0; A pure virtual function is a function which declared inside a base class that has no definition relative to the base class. In such cases, the compilar requireds each derived class to either define the function or redclare it as a pure virtual function. A class containing pure virtual function cannot be used to declare any object of its own. Such classes are called abstract class.
//constructor inheritance
#include<iostream.h> #include<conio.h> class alpha { private: int a; public: alpha(int x) { a=x; } void showalpha() { cout<<"\n Value of a = "<<a; } };
class beta { private : int b; public : beta(int y) { b=y; } void showbeta() { cout<<"\n Value of beta "<<b; } }; class gama:public alpha, public beta { private : int g; public : gama(int x, int y, int z): alpha(x), beta(y) { g=z; } void showgama() { cout<<"\n Value of Gama "<<g; } }; void main() { gama s1(5,10,15);
s1.showalpha(); s1.showbeta(); s1.showgama(); getch(); } Nesting of classes: When one class is define within another class, than it is known as nesting of class. This technique provides facilities like inheritance. Nesting of classes also possible by creating objects of other classes as member of a class. When a class contains objects of other class types as its member, it is referred to as containership or containment or aggregation. in case of nesting, the contained objects are constructed first before constructing the objects of the enclosing class.
/*nested class*/
#include<iostream.h-> #include<conio.h> class first { class second { public : void display() { cout<<"\n It is method of second class "; } }; public: second obj; void show() { cout<<"\n it is method of first class "; } }; void main() {
/*nesting of class*/
#include<iostream.h> #include<conio.h> class outer { class inner { int b; public : int c; inner() { b=5; c=10; } void print() { cout<<"\n it is method of inner class \n"; cout<<"\n value of b "<<b; cout<<"\n value of c "<<c; } }; int a; inner obj1;
public : inner obj2; outer() { a=25; } void display() { cout<<"\n It is display method of outer class \n"; cout<<"\n value of c "<<obj2.c; cout<<"\n value of a "<<a; obj1.print(); } }; void main() { outer out; out.display(); out.obj2.print(); getch(); } /*nesting of class by making objects of other classes as member variable of another class*/ #include<iostream.h> #include<conio.h> #include<stdio.h> class student { int rollno; int age; public : student(int r, int a)
{ rollno=r; age=a; } void showstudent() { cout<<"\n Rollno "<<rollno; cout<<"\n age "<<age; } }; class study { public : int phy,che,math; study(int p, int c, int m) { phy=p; che=c; math=m; } void showstudy() { cout<<"\n Marks of physics "<<phy; cout<<"\n Marks of chemistry "<<che; cout<<"\n Marks of math "<<math; } }; class result { student stud; study std;
int total; public: result(int r, int a, int p, int c, int m) : stud(r, a), std(p,c,m) { total=std.phy+std.che+std.math; } void showresult() { stud.showstudent(); std.showstudy(); cout<<"\n Total is "<<total; } }; void main() { result r(101,24,25,54,36); r.showresult(); getch(); } HOLDS-A relationship between classes When a class inherits from another class, the derived class has is-a relationship with its base class. When a class contains object of another class type, then containing/enclosing class has has-a relationship with contained/enclosed class. The class having HAS-A relationship with other class has the ownership of the contained object. Ownership defines the responsibility for the creation and the destruction of an object. That means, the object having another object in it has its ownership because its constructor is responsible for the invocation of embedded objects constructor. And its destructor is responsible for embedded objects destruction. Which it does by invoking destructor of embedded object. When a class indirectly contains pointer object of another class, it is said known as HOLDS-A relationship with class whose object is its indirect member. It is similar to HAS-A relationship but ownership is missing. Example:/*HOLDS-A relationship*/ #include<iostream.h>
#include<conio.h> class Fax { public: Fax() { cout<<"\n It is constructor of Fax class"; } void display() { cout<<"\n It is display method of Fax class "; } }; class Modem { Fax * connect; long bps; char type; public: Modem(long sp, char c, Fax * f): connect(f) { bps=sp; type=c; } void show() { cout<<"\n Speed = "<<bps; cout<<"\n Type = "<<type; connect->display();
} }; void main() { Fax * f; Modem obj(10000l,'a',f); obj.show(); getch(); } Static class member: There may be static data member and static member function in a class. Static data member: A static data member of a class is just like a global variable for its class. And it is globally available for every object of its class. The static data members are usually maintained to store values common to the entire class. A static data member is different from ordinary data members of a class in various respects: 1. There is only one copy of this data member maintained for the entire class which is shared by all the object of that class. 2. It is visible only within the class; however, its lifetime is the entire program. Two things are needed for making a data member static: 1. Declaration within the class definition. 2. Definition outside the class definition. 3. Static variable always preceded by static key word.
Constructor
Constructor: A member function with the same name as class name is called constructor. A constructor has following characteristics: 1. It name is same as class name. 2. It is not preceded by any return type like int, float , byte, short etc. even void also. 3. Constructor never returns a value. 4. Constructor can be with or without argument. 5. Constructor automatically called when its class object is created.
6. Constructor can be private, public and protected but it must always be declared as public so that its object can be created in main method or in any other class. If constructor is private then its objects creation in main is not possible because a private member of a class cannot be access outside the class. 7. A constructor may not be static. 8. Default constructor and copy constructor are generated by the compiler where needed. Generated constructors are public. 9. It is not possible to take address of a constructor. 10. An object of a class with a constructor cannot be a member of a union. 11. Member function can be called from within constructor. Need of constructor: basically a constructor is used to initialize private data member of a class or to initialize object of a class. Type of constructor: Constructors are of two types. Parameterized or arguemented and default or non-parameterized constructor. Default constructor: Constructor without arguments is known as default constructor. It does not accept parameters. It is generally used to initialize the instance variable of a class. Default constructor are very useful when you want to create an object without having to type the initial values or want to initialize objects every time with prespecified initial values. We can not create an array of object unless our class have a default constructor. #include<iostream.h> #include<conio.h> class abc { int a,b,c; public : abc() //default constructor { a=10; b=20; c=0; } void sum() { c=a+b;
cout<<"\n Sum is "<<c; } }; void main() { abc obj; obj.sum(); getch(); } Parameterized constructors: Constructor which accepts parameters are known as parameterized constructor. These are also known as regular constructor. Declaring the constructor with arguments hides the default constructor. #include<iostream.h> #include<conio.h> class abc { int a,b,c; public: abc(int x, int y) //argumentd constructor { a=x; b=y; c=0; } void sum() { c=a+b; cout<<"\n Sum is "<<c; } }; void main() { abc obj(10,20); obj.sum();
getch(); } Implicit call to the constructor: It means that the constructor is called when its name has not been mentioned in the statement. For example: abc obj(10,20); //implicit call This statement will create an object of class abc and invoke the constructor (implicitly) of abc to initialize the value 10 and 20 to variable a and b. Explicit call to constructor: It means that the name of the constructor is explicitly provided to invoke it, so that the object can be initialized. Example: abc obj=abc(10,20); This statement will create an object of class abc and invoke the constructor explicitly to initialize object with value 10 and 20. Temporary object or Temporary instance: The explicit call to a constructor also allows you to create a temporary instance or temporary object. A temporary object is the one the lives in the memory as long as it is being used or referenced in an expression and after this it dies. The temporary are anonymous i.e. they do not bear a name.
class temp { int a,b; public: temp() { a=0; b=0; } temp(int x , int y) { a=x; b=y; } void show() { cout<<" Value of a "<<a; cout<<"\n value of b "<<b; } }; void main() { temp().show(); temp(12,24).show(); getch(); }
int i(3), j(4); cout<<i; cout<<"\n"<<j; getch(); } Copy constructor: A copy is a constructor which receives the object of its class as argument. And copy constructor takes a reference to an object of the same class as an argument. The process of initializing through a copy constructor is known as copy initialization. When an object is defined and initialized with another object, then a copy constructor is called. Why the argument to a copy constructor is passed by reference? If we try to pass the argument by value to a copy constructor, the compiler complains out of memory. The reason is this, when an argument is passed by value, a copy of it is constructed. So in case of pass by value a copy constructor is creating a copy of the object for itself, thus it calls itself again and again until the compiler runs out of memory. So in the copy constructor the argument must be passed by reference, so that to make a copy of the passed object, original object is directly available. #include<iostream.h> #include<conio.h> class code { int id; public: code() { } code(int a) { id=a; } code(code &x)//copy constructor { id=x.id; }
void display() { cout<<id; } }; void main() { code a(100); code b(a); //copy constructor called code c=a; //copy constructor called cout<<"\n First call \n"; a.display(); cout<<"\n Second call \n"; b.display(); cout<<"\n Third call \n"; c.display(); cout<<"\n Forht call \n"; code d; d=a; //will work!! copy constructor called d.display(); getch(); }
/*copy constructor*/
#include<iostream.h> #include<conio.h> class sample { int i,j; public : sample(int a, int b)
{ i=a; j=b; } sample(sample & s) { j=s.j; i=s.i; cout<<"\n Copy constructor working \n"; } void print() { cout<<"\n value of i "<<i; cout<<"\n value of j "<<j; } }; void main() { sample s1(10,20); sample s2(s1); sample s3=s1; getch(); } Sequence of execution of constructor: When multiple object of a class are constructor then their sequence of execution will be same as they are declared. For example if we declared three object of class sample like this: Sample a, b, c; Then these object will execute one by one from a to c. But if there two or more classes in a program then constructor of first will invoke first then the constructor of child will invoke. Example: Incomplete?????????????????????????????????????????????????????
subject (int d, int sn) { days=d; sno=sn; } subject(int d=123, int sn=101); void printsubject() { cout<<"\n Subject no "<<sno; cout<<"\n Days "<<days; } }; class student { int rollno; float marks; public : student() { rollno=0; marks=0; } void getvalue()
{ cout<<"\n Enter rollno number and marks "; cin>>rollno; cin>>marks; } }; class admission { subject sub; student stud; float fees; public : admission() { fees=0; } void print() { stud.getvalue(); sub.printsubject(); cout<<"\n Fees "<<fees; } }; void main() { admission obj; cout<<"\n Back in main "; getch(); }
Dynamic initialization of objects: It means initial values may be provided during runtime. Even class objects can be initialized dynamically i.e. with the values provided at runtime. #include<iostream.h> #include<conio.h> class dynamic { int a,b; public : dynamic(int x, int y) { a=x; b=y; } void show() { cout<<"\n value of a "<<a; cout<<"\n value of b "<<b; } }; void main() { int a,b; cout<<"\n Enter value of a and b "; cin>>a>>b; dynamic obj(a,b); //dynamic initialization obj.show(); getch(); } Constructor with array #include<iostream.h> #include<conio.h> class array {
int a[10],i; public: array() { cout<<"\n Enter array elements ...\n"; for(i=0;i<10;i++) cin>>a[i]; } void show() { cout<<"\n Array elements are.....\n"; for(i=0;i<10;i++) cout<<a[i]<<" "; } }; void main() { array obj; obj.show(); getch(); } Constructor overloading: Constructor can be overloading with respect the number of arguments and types of argument.
/*constructor overloading*/
#include<iostream.h> #include<conio.h> class sample { int a,b,c; public :
sample(int x) { a=x; b=0; c=0; } sample(int x, int y) { a=x; b=y; c=0; } sample(int x, int y, int z) { a=x; b=y; c=z; } void show() { cout<<"\n value of a "<<a; cout<<"\n value of b "<<b; cout<<"\n value of c "<<c; cout<<"\n\n"; } }; void main() { sample s1(10), s2(20,30), s3(40,50,60); s1.show(); s2.show();
s3.show(); getch(); }
void show() { cout<<"\n Name "<<name; cout<<"\n Age } }; void main() { records r; r.show(); "<<age; cout<<"\n Salary "<<salary;
cout<<"\n"; records r1("amir"); r1.show(); cout<<"\n"; records r2("sumit",35); r2.show(); getch(); } Dynamic initialization of object #include<iostream.h> #include<conio.h> #include<string.h> class records { char name[25]; int age; float salary; public: records(char n[], int a, float sal) { strcpy(name,n); age=a; salary=sal; }
void show() { cout<<"\n Name "<<name; cout<<"\n Age } "<<age; cout<<"\n Salary "<<salary;
}; void main() { char nm[25]; int age; float sal; cout<<"\n Enter name , age and salary "; cin>>nm; cin>>age; cin>>sal; records r(nm,age,sal); r.show(); getch(); } Dynamic constructor: The constructor can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is know as dynamic construction of objects. The memory is allocated with the help of new operator. #include<iostream.h> #include<conio.h> class string { char *name; int length; public: string() { length=0; name=new char[length+1]; } string(char *s) { length=strlen(s);
name=new char[length+1]; strcpy(name,s); } void display() { cout<<"\n Name : "<<name; } void join(string &a, string &b) { length=a.length+b.length; delete name; name=new char[length+1]; strcpy(name, a.name); strcat(name, b.name); } }; void main() { char *first="joseshp"; string name1(first), name2("louis"), name3("david"), s1,s2; s1.join(name1, name2); s2.join(s1,name3); name1.display(); name2.display(); name3.display(); s1.display(); s2.display(); getch(); }
Destructor: A destructor is also a member function of class whose name is same as class name but is preceded by tilde (~) symbol. It used to free the memory occupied by constructor. A destructor takes no arguments, and not return type can be specified for it. It is called automatically by the compiler when an object is destroyed. The tilde symbol indicate that is it not a constructor and it will de-initialize the object that is initialized by constructor. Need for Destructors: during constructor of an object resources are allocated for use. These allocated resources must be de-allocated before the object is destroyed. So it is the duty of destructor to free these resources. So a destructor perform all clean up task like closing a file, de-allocating and releasing memory area automatically. Characteristics of destructor 1. We can have only one destructor for a class. So over loading of destructor is not possible. 2. If a class has a destructor then every object of that class will be de-initialized before the object goes out of scope. 3. Access rule for destructor is same as for other member functions. 4. Destructor is always without argument. And it cant not return any value. 5. They cant be inherited. 6. A destructor may not be static. 7. It is not possible to take address of destructor. 8. Member function may be called from within a destructor. 9. An object of a class with a destructor cannot be a member of a union. /*use of destructor*/ #include<iostream.h> #include<conio.h> class sample { int a,b; public : sample(int x, int y) { a=x; b=y; } void show() {
cout<<"\n value of a "<<a; cout<<"\n value of b "<<b; } ~sample() { cout<<"Destroying object "; } }; void main() { sample obj(10,20); obj.show(); sample obj2(20,30); obj2.show(); getch(); }
Pointers
Pointer: A pointer is a variable that holds a memory address, usually the location of another
variable in memory. Or A variable storing a memory address is called a pointer as it points to a specific memory location whose address it is storing under its name. Use of pointers 1. Pointers provide the means through which the member location of a variable can be directly accessed and hence can be manipulated in the way as required.
2. Pointers support c++s dynamic allocation routines. 3. Pointers can improve the efficiency of certain routines. Disadvantages 1. Uninitialized, or wild pointers can cause system to crash. 2. It is easy to use pointers incorrectly, causing bugs that are very difficult to find. Declaration and initialization of pointers int i=25; int *ptr; ptr=&i; The two special operator (* and &) are used with pointers. The & is a unary operator that returns the memory address of its operand. * is the dereference operator. It is also called as value at the address of. #include<iostream.h> #include<conio.h> void main() { int a=10; int *b=&a; cout<<"\n value of a "<<a; cout<<"\n address of a "<<&a; cout<<"\n address of a "<<b; getch(); } #include<stdio.h> #include<conio.h> void main() { int a=10,*b,**c; b=&a; c=&b; clrscr(); printf("\n value of a %d", a); //value of a printf("\n value of a %d", *b);//value of a
printf("\n value of a %d", **c);//value of a printf("\n value of b %u", *c);//address of b printf("\n value of b %u", b); //address of b printf("\n value of c %u", c); //addrss of c printf("\n value of a %d", b); //grabage value due to pointer printf("\n value of a %d", c); //grabage value due to pointer getch(); } C++ Memory Map: C++ creates four logically distinct regions of memory that are used for four distinct specific functions. Area used for function calls return addresses, arguments and local variables Area used for dynamic allocation of memory.
1. Once region in the memory holds the compiled code of the program. Every instruction and every function of the program starts at a particular address. 2. The next region is the memory area where the global variables of the program are stored. Global variables remain in the memory as long as program continues. 3. The third region known as stack is used for great many things while your program executes. The stack is used for holding the return addresses at function calls, arguments passed to the functions, and local variables for functions. The local variables remain in memory as logn as the function continues and after that they are erased from the memory. The stack also stores the current state the CPU. 4. The heap memory area is a region of free memory from which chunks of memory are allocated via c++s dynamic memory allocation functions.
Pointer Arithmetic
Only two arithmetic operation, addition and subtraction may be performed on pointers. When we add 1 to a pointer, we are actually adding the size of whatever the pointer is pointing at, i.e. each
time a pointer is incremented by 1. It points to the memory location of the next element of its base type. Example: int *ptr= 1001 Ptr++ 1003 Ptr++ 1005 A pointer holds the address of the very first byte of the memory location where it is pointing to. The address of first by is known as base address. /******arithmetic operation on pointer**/ #include<iostream.h> #include<conio.h> void main() { int i=10; int *ptr=&i; cout<<ptr<<endl; ptr++; cout<<ptr<<endl; ptr++; cout<<ptr<<endl; ptr++; cout<<ptr<<endl; ptr--; cout<<ptr<<endl; getch(); } /*Arithmatic of pointer (Addiiton, substraction, division)*/ #include<iostream.h> #include<conio.h> void main() { int a,b;
int *p,*q; p=&a; q=&b; cout<<"\n Enter value of a and b "; cin>>*p>>*q; int add=*p+*q; cout<<"\n Sum is "<<add; int sub=*p-*q; cout<<"\n substract is "<<sub; int product=*p * *q; cout<<"\n Product is "<<product; int div=*p / *q; cout<<"\n Division is "<<div; getch(); } /***************pointer increment and decrement**************/ #include<iostream.h> #include<conio.h> void main() { int n=44; int *ptr=&n; clrscr(); cout<<"\n Value of ptr "<<*ptr; ++*ptr; cout<<"\n value of ptr after increment "<<*ptr; --*ptr; cout<<"\n value of ptr after decrement "<<*ptr; getch(); } /*************pointer with if**************/ #include<stdio.h> #include<conio.h> void main() { int a,b;
int *p,*q; clrscr(); printf("\n Enter value of a and b "); scanf("%d%d",&a,&b); p=&a; q=&b; if(*p>*q) printf(" A is greater than b"); else printf("B is greater than a "); getch(); } /*********pointer with loop****/ #include<stdio.h> #include<conio.h> void main() { int num,r,s=0; int *ptr; clrscr(); printf("\n enter a number "); scanf("%d",&num); ptr=# while(*ptr) { r=*ptr%10; s=s*10+r; *ptr/=10; } printf("\n Reverse number is %d ",s); getch(); }
/*********pointer with array ***/ #include<iostream.h> #include<conio.h> void main() { int a[5]; int i,*p; p=a; //p=&a[0]; cout<<"\n Enter the elements of array "; for(i=0;i<5;i++) cin>>*(p+i); cout<<"\n Array elements are \n"; for(i=0;i<5;i++) cout<<*(p+i)<<endl; getch(); } /******bubble sort by pointer array***/ #include<iostream.h> #include<conio.h> void main() { int a[5],i,j,t,*p; p=a; clrscr(); cout<<"\n enter the elements of array \n"; for(i=0;i<5;i++) cin>>*(p+i); for(i=0;i<5;i++) { for(j=0;j<(5-i-1);j++) { if(*(p+j)>*(p+(j+1))) { t=*(p+j); *(p+j)=*(p+(j+1)); *(p+(j+1))=t; } } } for(i=0;i<5;i++) cout<<*(p+i); getch(); }
#include<iostream.h> #include<conio.h> void main() { clrscr(); int (*a)[3]; a=new int[3][3]; int i,j; cout<<"\n Enter the elements of matrix \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cin>>*(*(a+i)+j); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<*(*(a+i)+j); } cout<<"\n"; } getch(); } /*Array of pointers*/ #include<iostream.h> #include<conio.h> void main() { int *ptr[5]; int a=1,b=2,c=3,d=4,e=5; ptr[0]=&a; ptr[1]=&b; ptr[2]=&c; ptr[3]=&d; ptr[4]=&e; for(int i=0;i<5;i++) cout<<*ptr[i]<<" "; getch();
//s2=s1;//assignment of one string to another is not possible p2=p1; //assignment of one pointer string to another pionter string is possible cout<<s1<<"\n"; cout<<s2<<"\n"; cout<<p1<<"\n"; cout<<p2<<"\n"; getch(); } /**********string array with pointer****/ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<malloc.h> #include<string.h> void main() { char *name[6]; char n[15]; int i,len; char *p; clrscr(); for(i=0;i<=5;i++) { cout<<"\n Enter a name "; gets(n); len=strlen(n); p=new char [len+1]; strcpy(p,n); name[i]=p; } cout<<"\n===============\n"; for(i=0;i<=5;i++) cout<<name[i]<<endl; getch(); } /****pointer with structure****/ #include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25], address[25]; int age, sal; }; void main()
{ clrscr(); records *r; cout<<"\n Enter name and address "; gets(r->name); gets(r->address); cout<<"\n Ene age and salary "; cin>>r->age; cin>>r->sal; cout<<"\n Records are .......\n"; cout<<"\n Name "<<r->name; cout<<"\n Addr "<<r->address; cout<<"\n age "<<r->age; cout<<"\n salary"<<r->sal; getch(); } /****pointer with structure****/ #include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25], address[25]; int age, sal; }; void main() { clrscr(); records *r; int i,n; cout<<"\n Enter how manay records "; cin>>n; r=new records[n]; for(i=0;i<n;i++) { cout<<"\n Enter name and address "; gets((r+i)->name); gets((r+i)->address); cout<<"\n Ene age and salary "; cin>>(r+i)->age; cin>>(r+i)->sal; } cout<<"\n Records are .......\n\n"; for(i=0;i<n;i++) { cout<<"\n\n Name "<<(r+i)->name; cout<<"\n Addr "<<(r+i)->address; cout<<"\n age "<<(r+i)->age;
cout<<"\n salary"<<(r+i)->sal; } getch(); } /**********function by pointer*******/ #include<iostream.h> #include<conio.h> void main() { clrscr(); int reverse(int *); int n; cout<<"\n Enter a number \n"; cin>>n; cout<<"\n number after reverse "<<reverse(&n); getch(); } int reverse(int *n) { int r, s=0; while(*n>0) { r=*n%10; s=s*10+r; *n=*n/10; } return s; } /**********function by returning pointer*******/ #include<iostream.h> #include<conio.h> void main() { clrscr(); int * reverse(int *); int n; cout<<"\n Enter a number \n"; cin>>n; int *p; p=reverse(&n); cout<<"\n number after reverse "<<*p; getch(); } int * reverse(int *n) { int r, s=0; while(*n>0)
{ r=*n%10; s=s*10+r; *n=*n/10; } return &s; } /**********pointer to object********/ #include<iostream.h> #include<string.h> #include<conio.h> class abc { private : char name[25]; int code; float price; public: void getdata(char n[],int x, int y) { strcpy(name,n); code=x; price=y; } void show() { cout<<"\n Name = "<<name; cout<<"\n Code = "<<code; cout<<"\n price = "<<price; } }; void main() { clrscr(); abc *obj=new abc(); obj->getdata("amit",10,20); obj->show(); getch(); } /**********pointer to object array********/ #include<iostream.h> #include<string.h> #include<stdio.h> #include<conio.h> class abc {
private : char name[25]; int code; float price; public: void getdata(char n[],int x, int y) { strcpy(name,n); code=x; price=y; } void show() { cout<<"\n Name = "<<name; cout<<"\n Code = "<<code; cout<<"\n price = "<<price; } }; void main() { clrscr(); char name[25]; int code; float price; abc *obj=new abc[3]; int i; for(i=0;i<3;i++) { cout<<"\n Enter name "; gets(name); cout<<"\n enter code "; cin>>code; cout<<"\n enter price "; cin>>price; (obj+i)->getdata(name,code,price); } for(i=0;i<3;i++) (obj+i)->show(); getch(); }
Memory allocation
Static memory allocation
When the amount of memory to be allocated is known before handed and the memory is allocated during compilation itself is known as static memory allocation eg.int i , In this case the computer
knows that the what type of integer variable is used so generally it is 2 bytes so a space of 2 byte will allocate to a variable i during compilation . it is a static memory allocation.
{ int *arr,r,c,i,j; cout<<"Enter row and column "; cin>>r>>c; arr=new int[r*c]; cout<<"\n ener elements of matrix \n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) { cin>>arr[i*c+j]; } } cout<<"\n matrix elements are \n"; for(i=0;i<3;i++) { for(j=0;j<3;j++) { cout<<arr[i*c+j]; } cout<<endl; } getch(); }
An objects life time: as long as the object remains in the memory during the program execution, is known as object life time or objects extent. Global variables: The variables having file scope. The storage is allocated to them before the programs start up and remains bound to the variable throughout the program execution. These are spoken as static extent or global variable. Local Variable: Variables having local scope are known as local extent. Storage is allocated to them at each entry into the local scope as soon as local cope starts and on exit from the local scope the storage is freed up. A local variable with static pacifier has static extent. Objects that are dynamically allocated on free store are known as dynamic extent. That means the dynamically
allocated objects do not have any predefined scope. They remain in memory until explicitly removed using delete. #include<iostream.h> #include<conio.h> int a=10; //galobal variable void show(); void main() { int b=20; //local variable cout<<"\n value of a "<<a; cout<<"\n value of b "<<b; //cout<<"\n value of c "<<c; show(); getch(); } void show() { int c=20; //local variable cout<<"\n value of a "<<a; //cout<<"\n value of b "<<b; cout<<"\n value of c "<<c; } /***********passing object to a function ***********/ #include<iostream.h> #include<conio.h> class sample { int x;
sample(int a) { x=a; } void calculate(sample obj) { x=obj.x; cout<<"\n value of x "<<x; } }; void main() { sample obj1(10); sample obj2; obj2.calculate(obj1); getch(); }
/*********THIS pointer*******/
this pointer mainly used for self referencing. this pointer can be used inside any method to refer to the current object. Another use of this pointer is in using redundant (duplicate) variable names. this pointer stores the value of currently calling object. When a member function is called it is automatically passed an implicit argument that is a pointer to the object that invoke the function and this pointer is known as this pointer. #include<iostream.h> #include<string.h> #include<conio.h>
class salesman { private : char name[25]; float sale; public : salesman(char *s, float f) { strcpy(name, s); sale=f; } void show() { cout.write(this->name, 26); cout<<"invokes the poject \n"; cout<<"\n Name "<<this->name; cout<<"\n age "<<this->sale; } }; void main() { clrscr(); salesman s("amit",12); s.show(); getch(); } Object as function argument: Object can be passed to a function in the same way as any other type of variable is passed. So object can be passed to a function by value and by reference. Passing object through call by value When an object is passed through call by value mechanism, it means that the called function creates a copy of the passed object. But it raised to question: 1. Is the objects constructor executed when the copy of the passed object is maid 2. Is the destructor executed when the copy is destroyed? We can get answer of these questions by this program: #include<iostream.h> #include<conio.h> class sample { int x; public : sample(int i)
{ x=i; cout<<"Constructor object with "<<i<<endl; } ~sample() { cout<<"Destroying object having "<<x<<endl; } void getdata(int i) { x=i; } int showdata() { return x; } }; void fun(sample obj) { obj.getdata(10); cout<<"This is x local to a function "; cout<<"x = "<<obj.showdata()<<endl; } void main() { clrscr(); sample obj(100); cout<<"This is the x in main \n"; cout<<"x = "<<obj.showdata()<<endl; fun(obj); cout<<"\n Back in main \n"; cout<<"x ="<<obj.showdata()<<endl; getch(); } On execution this program shows that two calls of destructor function are executed, but only one call is made to the constructor function. So it is clear that constructor is not called when the copy of object is created by function. The reason for this is when an object is passed to a function call by value mechanism; the current state of the object is passed. The constructor function is not involved when a function receives an object as its parameter rather it copies down the members of the passed object for the called function and that serves as a copy of the passed object.
However it is very much necessary to destroy the copy of the object that the called function was working with, before returning from the function. Thus the destructor function must be executed when this copy is destroyed. Passing objects through reference When we passed object by reference then the function receive original object. #include<iostream.h> #include<conio.h> class sample { int x; public : sample(int i) { x=i; cout<<"Constructor object with "<<i<<endl; } ~sample() { cout<<"Destroying object having "<<x<<endl; } void getdata(int i) { x=i; } int showdata() { return x; } }; void fun(sample & obj) { obj.getdata(10); cout<<"This is x local to a function \n"; cout<<"x = "<<obj.showdata()<<endl; } void main() { clrscr(); sample obj(100); cout<<"This is the x in main \n"; cout<<"x = "<<obj.showdata()<<endl; fun(obj); //object pass by reference
cout<<"\n Back in main \n"; cout<<"x = "<<obj.showdata()<<endl; getch(); } In this program only one call is made to the constructor and destructor. In this method the function works with original object with an alias name. What is a memory leaks If the objects, that are allocated memory dynamically, are not deleted using delete, the memory block remains occupied even at the end of the program. Such memory blocks are known as orphaned memory blocks. This orphaned memory blocks when increase in number, bring as adverse effect on the system. This situation is known as memory leak. The possible reason for this are: 1. A dynamically allocated object not deleted using delete. 2. Delete statement is not getting executed because of some logic error. 3. Assigning the result of a new statement to an already occupied pointer. The memory leak can be avoided by: 1. Making sure that a dynamically allocated is deleted. 2. A new statement stores its return value (a pointer) in a fresh pointer. Self Referential Structure: A structure having an element that refers to the structure itself, is known as self referential structure. Example struct employee { int age; char name[25]; float salary; employee *next; }; In this example *next is a self referential structure. Dynamic structure: The new operator can be used to create dynamic structures also i.e. the structure for which the memory is dynamically allocated. To do so , we write in it in the following form: employee *ptr; ptr=new employee; here struct employee is the structure for which the memory is being allocated and ptr is a employee type pointer that stores the address of newly allocated memory. A dynamic structure can be released using the de-allocation operator delete as shown below: delete ptr;
Structure
Structure declaration initialization and copy #include<iostream.h> #include<conio.h> struct book { char name[24]; int page; float price; }; void main() { book b1= {"java",500,125.23}; //structure initialization book b2; b2=b1;//copy structure cout<<"\n name of book "<<b2.name; cout<<"\n Pages "<<b2.page; cout<<"\n price "<<b2.price; getch(); } /**************structure by keyboard************/ #include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25]; int age; float salary; }; void main() { struct records r; cout<<"\n Enter name , age and salary "; gets(r.name); cin>>r.age;
cin>>r.salary; cout<<"\n==============\n"; cout<<r.name<<endl; cout<<r.age<<endl; cout<<r.salary; getch(); } /******************Structur with infinint number of records********/ #include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25]; int age; float salary; }; void main() { struct records r[100]; int i=0,j=0; char ch='y'; do { cout<<"\n Enter name , age and salary "; gets(r[i].name); cin>>r[i].age; cin>>r[i].salary; i++; cout<<"\n DO you want to enter more records \n"; cin>>ch; }while(ch=='y' || ch=='Y'); for(j=0;j<i;j++) { cout<<"\n==============\n"; cout<<r[j].name<<endl; cout<<r[j].age<<endl; cout<<r[j].salary; } getch(); } /********************structure with pointer****************/
#include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25]; int age; float salary; }; void main() { struct records *r=new records(); cout<<"\n Enter name , age and salary "; cin>>r->name; cin>>r->age; cin>>r->salary; cout<<"\n==============\n"; cout<<r->name<<endl; cout<<r->age<<endl; cout<<r->salary; getch(); } /**************structur pointer array**************/ #include<iostream.h> #include<conio.h> #include<stdio.h> struct records { char name[25]; int age; float salary; }; void main() { int i; struct records *r=new records[2]; for(i=0;i<2;i++) { cout<<"\n Enter name , age and salary "; cin>>(r+i)->name; cin>>(r+i)->age; cin>>(r+i)->salary; }
for(i=0;i<2;i++) { cout<<"\n==============\n"; cout<<(r+i)->name<<endl; cout<<(r+i)->age<<endl; cout<<(r+i)->salary; } getch(); } /*************Nested structure***************/ #include<iostream.h> #include<conio.h> struct Records { char name[25]; int age; }; struct Address { Records r; int houseno; char city[25]; char state[25]; }; void main() { Address obj; cout<<"\n Enter name and age of person \n"; cin>>obj.r.name; cin>>obj.r.age; cout<<"\n Enter Address (House No, City, State ) "; cin>>obj.houseno; cin>>obj.city; cin>>obj.state; cout<<"\n=============================\n"; cout<<"\n Name = "<<obj.r.name; cout<<"\n Age = "<<obj.r.age; cout<<"\n Address \n"; cout<<"\n House no = "<<obj.houseno; cout<<"\n City = "<<obj.city; cout<<"\n State = "<<obj.state; getch(); }
File Handling
File or data file: A file is a collection of related records placed on the disk together. A record is
the combination various related fields. And a field is the collection of characters and a character is made from bits or binary digit that is 0 and 1. The file handling in C++ can be broadly categorized in two types: 1. High Level (standards files or stream oriented files) 2. Low Level(System oriented files) High level file handling is managed by library functions while low level file handling is managed by system calls. The header file iostream.h should be included in the program to make use of the I/O functions. Like cin and cout we can do file handling with the I\O function get(), getline(), read(), write(), seekg() etc. Files are of two types: Character files or text files: Text files are in human readable form they can be created and read using any text editor. These files stores characters as per a specific character encoding scheme (ASCII in C and C++). In text format data is stored as lines of characters with each line terminated by a new line character (\n). Binary file: Binary files are not in human readable form and they can be created and read only by specific programs written for them. These files store data in machine readable form. In binary format, data is stored on the disk in the same way as it is represented in the computer memory. The binary data cant be read using a text editor. Explanation: The integer 1679 will take only 2 bytes in a binary file while it will occupy 4 bytes in a text file because in binary file it is stored as an integer while in text file it is stored as a sequence of 4 character i.e. 1,6,7, 9. Binary --- 000 0110 1000 1111 Text --- 0011 0001 0011 0110 0011 0111 0011 1001 Both text file and binary file keep record of the length of the file, and identify the end of file when this length is reached. In text file character with ASCII value 26 is considered as end of file character. All input function stops reading from a text file when this character is encountered and return end of file signal to the program. The input and output operation in binary file take less time as compared to the text file because in binary file no conversion is to take place. Note :>( UNIX System does not make any distinction between text file and binary file). Buffer: Buffer is an area in memory where the data is temporarily stored before being written to the file. When we open a file, a buffer is automatically associated with its file pointer. Whatever data we send to the file is not immediately written to the file. First it is sent to the buffer and when the buffer is full then its contents are written to the file. When the file is close, all the contents of buffer are
automatically written to the file even if the buffer is not full. This is called flushing the buffer, we can do it by fflush() method. The concept of buffer is used to increase efficiency. If there is no buffer we would have to access the disk each time for writing even single byte of data. This would have to take a lot of time because each time the disk is accessed, the read / write head has to be repositioned. When buffering is done, the data is collected in the buffer and data equal to the size of buffer is written to the file at a time, so the number of times disk is accessed decreases, which improves the efficiency. The steps for file operations in C++ programming are as follows: 1. Open a file 2. Read the file or write data in the file 3. Close the file The function open () and close () are used for opening and closing the files respectively. Stream: A stream is a general name given to a flow of data at the lowest level (i.e. when data is in binary format). Different streams are used to represent different kinds of data flow. For example the stream that supplies data to the program is known as input stream. It read data from the file and hands it over to the program. The stream that receives data from the program is known as output stream. It writes the received data to the file. The file I/O system of C++ contains a set of classes that define the file handling methods. These classes, designed to manage the disk files, are declared in fstream.h. There for we must include this header file (fstream.h) our program while doing file operations. Function of file stream classes Class Working Filebuf It sets the file buffer to read and write. Fstreambase It is base class for fstream, ifstream and ofstream classes. It provides input operations for a file.
Work To close a file To open a file This function reads a single character from the associated stream. This function handles data in binary form. So it will read character in binary format. This function reads characters from input stream and puts them in the array pointed to by buf until either num characters have been read, or the character specified by delim is
ifstream
close() get()
getline()
read()
seekg() form1: istream & sekg(long) form2: istream & seekg(long, seek_dir)
Ofstream
tellg() put()
write()
encountered. If not mentioned, the default value of delim is newline character i.e. this function removes the delimiter new line character from the input stream. This function handles data in binary form. This function reads sizeof(buf) bytes from the associated stream and puts them in the buffer pointed to by buf. This function is used to achieve random access in a file. This function is for input streams. And seekg() works with ifstream object. The seekg() when in first form moves the pointer to an absolute position. And when in second form moves the pointer to a position that is relative to the current position. This function writes a single character from the associated stream. This function handles data in binary form. So it will write a character in binary format. This function handles data in binary form. This function copies a class object from memory byte by byte with no conversion. But only those data members are written to the disk file and the member functions are
not. These functions perform operations on put pointer. Both these functions with ofstream objects. In first form seekp() moves the put pointer to the absolute position. In second form it moves the put pointer to relative to the current position.
Fstream
It is input-output file stream class. It provides support for simultaneous input and output operations. In inherits all the functions from istream and ostream classes through iostream class.
Opening and closing a file: Opening file can be achieved in two ways. 1. Using the constructor function of the stream class. (this method is apply when single file is used) 2. Using the function open() (this method is apply when multiple files are used) Opening file using constructor: ifstream input-file (data file); ofstream output-file(data file); This statement creates an object of ifstream class and open a file passed to it as argument and attached to it with input stream. Example: /**********reading and writing to a file**/ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<stdio.h> void main() { ofstream fout("student.txt"); char name[25]; int marks; cout<<"\n Enter name and marks "; gets(name); cin>>marks; fout<<name<<"\n"<<marks;
fout.close(); cout<<"\n Data written to file \n"; ifstream fin("student.txt"); fin.seekg(0); fin.get(name,25); fin>>marks; cout<<"\Name = "<<name; cout<<"\n Marks = "<<marks; fin.close(); getch(); } /*****reading and writing to a file multiple records by loop**/ #include<iostream.h> #include<fstream.h> #include<stdio.h> #include<conio.h> void main() { clrscr(); ofstream fout("student.txt"); char name[25]; int marks,i; for(i=1;i<=3;i++) { cout<<"\n enter name and marks "; gets(name); cin>>marks; fout<<name<<"\n"<<marks; } fout.close(); ifstream fin("student.txt"); fin.seekg(0); for(i=1;i<=3;i++) { fin.get(name,25); fin>>marks; cout<<"\n Name = "<<name; cout<<"\n Marks= "<<marks; cout<<endl<<endl; } fin.close(); getch(); } Opening file using open () function Stream-object.open(file name);
/*program to use multiple files in succession*/ #include<fstream.h> #include<conio.h> #include<iostream.h> void main() { ofstream fout; fout.open("studname.txt"); fout<<"Amit \n"<<"Sumit \n"<<"Raman \n"; fout.close(); fout.open("studmarks.txt"); fout<<"12.23\n"<<"34.34 \n"<<"34.34 \n"; fout.close(); char line[80]; ifstream fin; fin.open("studname.txt"); cout<<"\n The contents are \n"; fin.getline(line,80); cout<<line<<endl; fin.getline(line,80); cout<<line<<endl; fin.getline(line, 80); cout<<line<<endl; fin.close(); fin.open("studmarks.txt"); cout<<"\n Marks are \n"; fin.getline(line,80); cout<<line<<"\n"; fin.getline(line,80); cout<<line<<endl; fin.getline(line,80); cout<<line<<endl; fin.close(); getch(); }
File Mode
The file mode describes how a file is to be used: To read, to write, to append and so on. When you associate a stream with a file, either by initializing a file stream object with a file name or by using the open () method, you can provide a second argument specifying the file mode, as mentioned below: Stream-object.open(file name, file mode); The second argument i.e. file mode is of type int, and we can choose one form several constant defined in the ios class.
File mode constants Constant Meaning ios::in It opens file for reading i.e input mode. ios::out It opens file for writing i.e. in output mode. This also opens the file in ios::trunc mode by default. This means an existing file is truncate when opened i.e. its previous contents are described. ios::ate This seeks to end of file upon opening of the file. I/O operations can still occur anywhere within the file. ios::app This causes all output to that file to be appended to the end. This value can be used only with files capable of output. ios:trunk This value causes the contents of a pre existing file by the same name to be destroyed and truncates the file to zero length ios:nocreate This causes the open function to fail if the file does not already exist. It will not create a new file with that name. ios:noreplace This causes the open () function to fail if the file already exists this is used when you want to create a new file and at the same time. ios:binary This causes a file to be opened in binary mode. By default, files are opened in text mode. When a file is opened in text mode, various character translations may take place, such as the conversion of carriage return into new lines. However, no such character translation occurs in files opened in binary mode. /********writing data to a file*****/ #include<iostream.h> #include<conio.h> #include<fstream.h> void main() { clrscr(); ofstream fout; fout.open("marks.dat",ios::out); char ans='y'; int rollno; float marks; while(ans=='y' || ans=='Y') { cout<<"\n Enter Rollno "; cin>>rollno; cout<<"\n ener marks "; cin>>marks; fout<<rollno<<"\n"<<marks<<"\n"; cout<<"\n Do you want to enter more records (y/n) "; cin>>ans; } fout.close(); } /********reading data from a file by get method*****/
#include<iostream.h> #include<conio.h> #include<fstream.h> void main() { clrscr(); ifstream fin; fin.open("marks.dat",ios::in); int rollno; float marks; char ch; while(fin) { fin.get(ch); cout<<ch; } fin.close(); getch(); } /********Reading from file using getline function*****/ #include<iostream.h> #include<conio.h> #include<fstream.h> void main() { clrscr(); ifstream fin; fin.open("marks.dat",ios::in); int rollno; float marks; char ch[25]; while(fin) { fin.getline(ch,25); cout<<ch<<endl; } fin.close(); getch(); } /*****************use of append function*********/ #include<iostream.h> #include<fstream.h> #include<stdio.h> #include<conio.h> void main() { ofstream fout;
fout.open("marks.dat", ios::app); char ans='y'; int rollno; float marks; clrscr(); while(ans=='y' || ans=='Y') { cout<<"\n Enter rollno "; cin>>rollno; cout<<"\n Enter marks "; cin>>marks; fout<<rollno<<"\n"<<marks<<"\n"; cout<<"\n Want to enter more records (y/n) \n"; cin>>ans; } fout.close(); getch(); }
/*********creating a file using put******/ #include<iostream.h> #include<fstream.h> #include<conio.h> void main() { clrscr(); ofstream fout; fout.open("student.txt", ios::app); char ch; int line=0,i; for(int i=33;i<128;i++) fout.put(((char)i)); fout.close(); ifstream fin; fin.open("student.txt",ios::in); fin.seekg(0); while(fin) { fin.get(ch); cout<<ch<<" "; } getch(); } The read () and write () functions istream & read ((char *) & buf, int sizeof(buf)); ostream & write((char *) & buf, int sizeof(buf));
The read () function reads sizeof(buf) bytes from the associated stream and puts them in the buffer pointed to by buf. The write () function writes sizeof(buf) bytes to the associated stream from the buffer pointed to by buf. These functions take two arguments. The first is the address of variable but, and the second is the length of the variable in bytes. The address of the variable must be type cast to type char * i.e. a pointer to character type. /*program to write and read a structure using wrie() and read() function using a binary file*/ #include<fstream.h> #include<conio.h> #include<string.h> #include<conio.h> struct customer { char name[25]; float balance; }; void main() { clrscr(); customer cust; strcpy(cust.name, "Amir"); cust.balance=123; ofstream fout; fout.open("saving", ios::out || ios::binary); fout.write((char *) & cust, sizeof(cust)); fout.close(); ifstream fin; fin.open("saving", ios::in || ios::binary); fin.read((char *) & cust, sizeof(customer)); cout<<cust.name; cout<<" Has the balance amount of Rs "<<cust.balance<<"\n"; fin.close(); getch(); } Reading and writing class objects: The function read() and write() can also be used for reading and writing class objects. These function handle the entire structure of an object as a single unit, using the computers internal representation of data. The function write() copies a class object from memory byte by byte with no conversion. But one thing that must be remembered is that only data members are written to the disk file and not the member functions. The length of an object is obtained by sizeof operator and it represents the sum total of lengths of all data members of the object. /***program for reading and writing class object**/ #include<fstream.h>
#include<conio.h> #include<stdio.h> class student { char name[40]; char grade; float marks; public : void getdata() { cout<<"\n Enter name "; gets(name); cout<<"\n Enter grade "; cin>>grade; cout<<"\n enter marks "; cin>>marks; } void display() { cout<<"\n name "<<name<<endl; cout<<"\n Grade "<<grade<<endl; cout<<"\n marks "<<marks<<endl; } }; void main() { clrscr(); student stud[3]; fstream fin; fin.open("stud.dat", ios::in || ios::out); cout<<"\n Enter details for 3 students \n"; for(int i=1;i<=3;i++) { stud[i].getdata(); fin.write((char *) &stud[i], sizeof(stud[i])); } fin.seekg(0); cout<<"\n The contents of stud.dat are \n"; for(i=1;i<=3;i++) { fin.read((char *)&stud[i], sizeof(stud[i])); stud[i].display(); } fin.close(); getch(); }
Detecting EOF: Detection of the end of file is necessary for preventing any further attempt to read data from the file. We can detect end of file using the member function eof() which has the prototype int eof(); It returns nonzero when the end of the file has been reached, otherwise it returns zero. We can use fstream object, such as fin for detection of end of file. /*use of eof() function*/ using a binary file*/ #include<fstream.h> #include<conio.h> #include<string.h> #include<conio.h> struct customer { char name[25]; float balance; }; void main() { clrscr(); customer cust; strcpy(cust.name, "Amir"); cust.balance=123; ofstream fout; fout.open("saving", ios::out || ios::binary); fout.write((char *) & cust, sizeof(cust)); fout.close(); ifstream fin; fin.open("saving", ios::in || ios::binary); fin.read((char *) & cust, sizeof(customer)); while(!fin.eof()) { cout<<cust.name; cout<<" Has the balance amount of Rs "<<cust.balance<<"\n"; fin.read((char *) & cust, sizeof(customer)); } fin.close(); getch(); } File pointer and Random Access: Every file maintains two pointers called get pointer (writing mode) and put pointer (reading mode) which tell the current position in the file where writing or reading will take place. These pointers help in attaining the random access file. Random access means moving directly anywhere in the file rather than moving sequentially. Random access is useful when we want to insert , delete or search a record from a file. Random access is achieve by manipulating seekg(), seekp(), tellg() and tellp() functions. The seekg() and tellg() function allow
you to set and examine the get pointer, these are the ifstream function. And the seekp() and tellp() functions perform these operations on the put pointers, these are the ofstream function. Basic operations of binary files Searching: we can perform search in a binary file opened in input mode by reading each record then checking whether it is out desired record or not. Appending records to a file: When file is opened in append mode the previous records is retained and new data gets added to the file after the last record. Syntax: ios::app Example: searching and appending operation simultaneously /*Program to implement searching in a file that has records maintained through structures*/ #include<iostream.h> #include<process.h> #include<fstream.h> #include<stdio.h> #include<conio.h> struct stud { int rollno; char name[25]; char clas[4]; float marks; char grade; } s; void main() { fstream fin("students.txt", ios::app | ios::in); clrscr(); int choice; cout<<"\n 1: for append records "; cout<<"\n 2: search records "; cout<<"\n 3: for exit "; cout<<"\n Enter your choice "; cin>>choice; switch(choice) { case 1: char ch='y'; while(ch=='y' || ch=='Y') { cout<<"\n Enter Rollno "; cin>>s.rollno; cout<<"\n enter name "; gets(s.name); cout<<"\n Enter class "; gets(s.clas); cout<<"\n Enter marks "; cin>>s.marks;
cout<<"\n Enter grade "; cin>>s.grade; fin.write((char *) &s, sizeof(s)); cout<<"\n Do you want to enter more records (y/n) "; fflush(stdin); cin>>ch; } fin.close(); break; case 2: int rn; char found='n'; cout<<"\n enter rollno to be searched for "; cin>>rn; fin.seekg(0); while(!fin.eof()) { fin.read((char *)&s, sizeof(s)); if(s.rollno==rn) { cout<<s.name<<" Rollno "<<rn<<" has "<<s.marks<<"% marks and "<<s.grade<<" grade "<<endl; found='y'; break; } } if(found=='n') cout<<"\n Rollno not found "; fin.close(); break; case 3: exit(1); } getch(); }
/*A program to read a text file and counting the number of lines present in it*/ #include<iostream.h> #include<conio.h> #include<string.h> #include<fstream.h> void main() { clrscr(); int c=0; char ch; ifstream fin;
fin.open("abcd.txt", ios::in); while(fin) { fin.get(ch); if(ch=='\n') c++; } fin.close(); cout<<"\n Number of lines "<<++c; getch(); }
/*WAP to read a Text file "ABC.txt" and count number of Alphabates present in that file**/
#include<iostream.h> #include<conio.h> #include<string.h> #include<fstream.h> void main() { clrscr(); char ch; ifstream fin; fin.open("abcd.txt", ios::in); while(fin) { fin.get(ch); if(ch>='a' && ch<='z' || ch>='A' && ch<='Z') cout<<ch<<" "; } fin.close(); getch();
}
/*WAP to read a text file abc.txt and print all the digits present in it*/
#include<iostream.h> #include<conio.h> #include<string.h> #include<fstream.h> void main() { clrscr(); char ch; ifstream fin; fin.open("abcd.txt", ios::in); while(fin) { fin.get(ch); if(ch>='0' && ch<='9') cout<<ch<<" ";
} fin.close(); getch(); }
/*WAP to read a text file abc.txt and print all the space, dots, words, sentences present in it*/
#include<iostream.h> #include<conio.h> #include<string.h> #include<fstream.h> void main() { clrscr(); char ch; int word=0, sent=0, space=0, dot=0; ifstream fin; fin.open("abcd.txt", ios::in); while(fin) { fin.get(ch); if(ch==' ') space++; if(ch=='.') dot++; if(ch==' ' && ch+1!=' ') word++; if(ch=='\n') sent++; } fin.close(); cout<<"\n Number of spaces "<<space; cout<<"\n Number of dot "<<dot; cout<<"\n Number of word "<<word; cout<<"\n Number of sentance "<<++sent; getch(); }
/*count the frequence of as word*/ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> void main() { char s[10]; int c=0; ifstream fin; fin.open("abcd.txt", ios::in); //while(!fin.eof()) while(fin) {
fin.getline(s,10); if(strcmp(s,"as")==0 || strcmp(s,"As")==0) c++; } fin.close(); cout<<"Frequence of as is "<<c; getch(); } /*count the frequence of the word*/ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> void main() { char s[3]; char ch; ifstream fin; fin.open("abcd.txt", ios::in); //while(!fin.eof()) while(fin) { fin.get(ch); if(ch==' ' && ch+1!=' ') { fin.getline(s,3); if(strcmp(s,"The")==0 || strcmp(s,"The")==0) cout<<s<<"\n"; } } fin.close(); getch(); } /*count the frequence of theword*/ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> void main() { char s[10]; ifstream fin; fin.seekg(0); fin.open("abcd.txt", ios::in); //while(!fin.eof()) while(fin)
{ fin.getline(s,10); if(strcmp(s,"the")==0 || strcmp(s,"The")==0) cout<<s<<endl; } fin.close(); getch(); } /*WAP to search "Me" and "My" words present in a text file "Diary.text", if this file contains: My first book was Me and My family. it gave me chance to be known to the world. */ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<stdio.h> void main() { char str[200],s[10]; int c=0; char ch; cout<<"\n Enter a string "; gets(str); ofstream fout("Diary.txt"); fout<<str; fout.close(); ifstream read("Diary.txt"); read.seekg(0); while(read) { read.get(ch); if(ch==' ' && ch+1!=' ') { read.getline(s,3); if(strcmp(s,"Me")==0 || strcmp(s,"me")==0 || strcmp(s,"My")==0 || strcmp(s,"my")==0) c++; } } read.close(); cout<<c; getch(); } /*counting of lines in a txt file that starts from alphabate*/ #include<iostream.h>
#include<conio.h> #include<string.h> #include<fstream.h> void main() { clrscr(); int c=0; char ch[80]; ifstream fin; fin.open("abcd.txt", ios::in); while(fin) { fin.getline(ch,80); if((ch[0]>='a' && ch[0]<='z') || (ch[0]>='A' && ch[0]<='Z')) c++; } fin.close(); cout<<"\n Number of lines "<<c; getch(); } /*print the name starting with charact 'a'*/ #include<iostream.h> #include<stdio.h> #include<conio.h> #include<fstream.h> void main() { ofstream fout; fout.open("names.txt", ios::out); char name[25]; int i,n; clrscr(); cout<<"\n Enter how many students name "; cin>>n; for(i=1;i<=n;i++) { cout<<"\n Ener name "; gets(name); fout<<name<<endl; } fout.close(); ifstream fin; fin.open("names.txt", ios::in); while(fin) { fin.getline(name,25); if(name[0]=='a' || name[0]=='A')
/* Enter records of students and print the student who are in class 12th */ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> #include<stdio.h> struct records { char name[25]; int clas; }; void main() { clrscr(); fstream file; file.open("stud.dat", ios::out | ios::in | ios::binary); records r[3]; int i; for(i=0;i<3;i++) { cout<<"\n Enter name "; gets(r[i].name); cout<<"\n enter clas "; cin>>r[i].clas; file.write((char *)&r[i], sizeof(r[i])); } file.seekg(0); file.read((char *)&r[i], sizeof(r[i])); while(file) { if(r[i].clas==12) { cout<<r[i].name<<"\n"; cout<<r[i].clas<<"\n"; } file.read((char *)&r[i], sizeof(r[i])); } file.close(); getch(); }
/* Enter records of phone directory and print the phone number whos code is 123 */ #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> #include<stdio.h> struct records { int phoneno; int areacode; }; void main() { clrscr(); fstream file; file.open("directory.dat", ios::out | ios::in | ios::binary); records r[3]; int i; for(i=0;i<3;i++) { cout<<"\n Enter phoneno "; cin>>r[i].phoneno; cout<<"\n enter areacode "; cin>>r[i].areacode; file.write((char *)&r[i], sizeof(r[i])); } file.seekg(0); file.read((char *)&r[i], sizeof(r[i])); while(file) { if(r[i].areacode==123) cout<<r[i].phoneno<<"\n"; file.read((char *)&r[i], sizeof(r[i])); } file.close(); getch(); } /*******Write a mneu driven Program to : create a text file create another file using the first one which will store all the words starting with vowel. *****************/ #include<fstream.h> #include<string.h>
#include<stdio.h> #include<iostream.h> #include<conio.h> void main() { clrscr(); int choice; char temp[50]; cout<<"\n 1: To create a text file "; cout<<"\n 2: To create another file using first one which will store all the \n words starting with vowal. "; cout<<"\n enter your choice "; cin>>choice; switch(choice) { case 1: ofstream ofile; ofile.open("Source.txt"); cout<<"\n Enter some text in the file \n"; gets(temp); ofile.write((char *)&temp, sizeof(temp)); ofile.close(); cout<<"\n press enter........."; break; case 2: fstream sfile,dfile,tfile; sfile.open("Source.txt", ios::in); sfile.read((char *)&temp, sizeof(temp)); //adding blanck space at beginig of string char text[100]={" "}; strcat(text,temp); tfile.open("temp.txt",ios::out); tfile.write((char *)&text, sizeof(text)); sfile.close(); tfile.close(); //copying file after adding space back to the source file tfile.open("temp.txt", ios::in); sfile.open("Source.txt", ios::out); tfile.read((char *)&text, sizeof(text)); sfile.write((char *)&text, sizeof(text)); tfile.close(); sfile.close(); //copying words starting from vowals to the destination file sfile.open("Source.txt", ios::in);
sfile.read((char *)&text, sizeof(text)); dfile.open("Destination.txt", ios::out); for(int i=0;i<strlen(text);i++) { if((text[i]==' ' && text[i+1]!=' ') && (text[i+1]=='a' || text[i+1]=='e' || text[i+1]=='i' || text[i+1]=='o' || text[i+1]=='u')) { for(int j=i+1;text[j]!=' ';j++) { char ch=text[j]; dfile.write((char *)&ch, sizeof(ch)); } } } sfile.close(); dfile.close(); cout<<"\n File copied "; break; } getch(); }
Solution: 9 /*******Write a mneu driven Program to : 1.create a text file 2.count no of digits, vowals and words 3.create another file using the first one which will store all the text after replacing the blanks with #.*****************/ #include<fstream.h> #include<string.h> #include<stdio.h> #include<iostream.h> #include<conio.h> void main() { clrscr(); int choice; char text[50]; int i; cout<<"\n 1: To create a text file "; cout<<"\n 2: To count no of digits, vowals and words."; cout<<"\n 2: To create another file using first one which will store all the \n text replaceing blancks with #"; cout<<"\n enter your choice "; cin>>choice; switch(choice) {
case 1: ofstream ofile; ofile.open("Source.txt"); cout<<"\n Enter some text in the file \n"; gets(text); ofile.write((char *)&text, sizeof(text)); ofile.close(); cout<<"\n press enter..... "; break; case 2: int digits=0, words=1, vowals=0; ifstream readfile; readfile.open("Source.txt"); readfile.read((char *)&text, sizeof(text)); for(i=0;i<strlen(text);i++) { if(text[i]==' ' && text[i+1]!=' ') words++; if(text[i]=='a' || text[i]=='e' || text[i]=='i' || text[i]=='o' || text[i]=='u') vowals++; if(text[i]>='0' && text[i]<='9') digits++; } cout<<"\n Number of Word \t"<<words; cout<<"\n Number of Vowals \t"<<vowals; cout<<"\n Number of digit \t"<<digits; break; case 3: ofstream file; file.open("Destination.txt"); ifstream ifile; ifile.open("Source.txt"); ifile.read((char *) &text, sizeof(text)); for(i=0;i<strlen(text);i++) { if(text[i]==' ') text[i]='#'; file.write((char *)& text[i], sizeof(text[i])); } file.close(); ifile.close(); cout<<"File Copied "; break; } getch(); }
Solution: 10 /*******Write a mneu driven Program to : 1.create a text file 2.read the file and display . Uppercase Vowals . Lowercase Vowals . Uppercase Consonants . Lowercase Consonnats 3.create another file using the first one which will store only vowals from the first file */ #include<fstream.h> #include<string.h> #include<stdio.h> #include<iostream.h> #include<conio.h> void main() { clrscr(); int choice; char text[50]; int i; cout<<"\n\n 1: To create a text file "; cout<<"\n\n 2: To count no of Uppercase Vowals, Lowercase Vowals, Uppercase Consonant,\n Lowercase Consonants "; cout<<"\n\n 3: To create another file using first one which will store only vowals \n from first "; cout<<"\n\n enter your choice "; cin>>choice; switch(choice) { case 1: ofstream ofile; ofile.open("Source.txt"); cout<<"\n Enter some text in the file \n"; gets(text); ofile.write((char *)&text, sizeof(text)); ofile.close(); cout<<"\n press enter ....... "; break; case 2: int uv=0, lv=0,uc=0, lc=0; ifstream readfile; readfile.open("Source.txt"); readfile.read((char *)&text, sizeof(text)); for(i=0;i<strlen(text);i++) {
if(text[i]=='a' || text[i]=='e' || text[i]=='i' || text[i]=='o' || text[i]=='u') lv++; else if(text[i]=='A' || text[i]=='E' || text[i]=='I' || text[i]=='O' || text[i]=='U') uv++; else if(text[i]>='b' && text[i]<='z') lc++; if(text[i]>='B' && text[i]<='Z') uc++; } cout<<"\n Number of Uppercase Vowals\t \t"<<uv; cout<<"\n Number of Lowercase Vowals \t \t"<<lv; cout<<"\n Number of Uppercase Consonents \t"<<uc; cout<<"\n Number of Lowercase Consonents \t"<<lc; break; case 3: ofstream file; file.open("Destination.txt",ios::out); ifstream ifile; ifile.open("Source.txt", ios::in); ifile.read((char *) &text, sizeof(text)); for(i=0;i<strlen(text);i++) { if(text[i]=='a' || text[i]=='e' || text[i]=='i' || text[i]=='o' || text[i]=='u') file.write((char *)& text[i], sizeof(text[i])); if(text[i]=='A' || text[i]=='E' || text[i]=='I' || text[i]=='O' || text[i]=='U') file.write((char *)& text[i], sizeof(text[i])); } file.close(); ifile.close(); cout<<"File copied "; break; } getch(); } Solution: 11 /*Declare a class containing: Name Address Telephone No. write a menu driven program to: . Append record in a file . Display the name and address for a given telephone number. */ #include<iostream.h> #include<conio.h> #include<stdio.h>
#include<string.h> #include<fstream.h> class Records { public : char name[10]; char address[10]; int telephoneno; void getrecords() { cout<<"\n Enter Name "; gets(name); cout<<"\n Enter Address "; gets(address); cout<<"\n Enter telephoneno "; cin>>telephoneno; } void showrecords() { cout<<name<<"\n"; cout<<address<<"\n"; cout<<telephoneno<<"\n"; } }; void main() { clrscr(); Records r; fstream file; int choice; cout<<"\n 1: To append records in a file "; cout<<"\n 2: Display name and address of given telephone number "; cout<<"\n Enter your choice "; cin>>choice; switch(choice) { case 1: file.open("Records.txt", ios::app); r.getrecords(); file.write((char *)&r, sizeof(r)); file.close(); cout<<"\n Press Enter...."; break; case 2:
int phone; cout<<"\n Enter phone number to search "; cin>>phone; file.open("Records.txt",ios::in); file.seekg(0); while(!file.eof()) { file.read((char *)&r, sizeof(r)); cout<<"\n innn"; if(file.eof()) break; if(r.telephoneno==phone) { cout<<"nnot in"; r.showrecords(); break; } } cout<<"Phone number not found "; file.close(); break; } getch(); } Solution: 12 /*A blood bank maintains the record of donor: name, blood group. Write a menu driven program: . Create file for donor . print name of all the donors having given blood group . prit the tabular list of donors */ #include<iostream.h> #include<fstream.h> #include<string.h> #include<stdio.h> #include<conio.h> void main() { clrscr(); char name[25], address[50], bdgroup[2]; int choice; cout<<"\n 1: Create file for donor "; cout<<"\n 2: print the name of all the donors having blood group "; cout<<"\n 3: print the tabular list of donors "; cout<<"\n enter your choice "; cin>>choice;
fstream file; switch(choice) { case 1: ofstream write("Doner.txt", ios::app); cout<<"\n Enter name "; gets(name); cout<<"\n Enter address "; gets(address); cout<<"\n enter blood group "; gets(bdgroup); write<<name<<"\n"; write<<address<<"\n"; write<<bdgroup<<"\n"; write.close(); break; case 2: char group[2]; cout<<"\n enter blood group "; gets(group); ifstream read("Doner.txt", ios::in); read.seekg(0); while(!read.eof()) { if(read.eof()) break; read>>name; read>>address; read>>bdgroup; if(strcmp(bdgroup,group)==0) { cout<<name<<"\n"; cout<<address<<"\n"; } } read.close(); break; case 3: ifstream file("Doner.txt", ios::in); cout<<"\n NAME \t ADDRESS \t BLOOD GROUP \n"; file.seekg(0); while(!file.eof()) { file>>name; file>>address; file>>bdgroup;
Solution: 13 /*Declare a class Containig: . Bno . Bname . Price . Required Functions Write a menu driven program: . To add record in a file. . To modify the price of the given Bno. */ #include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> #include<fstream.h> class Records { public : int Bno; char Bname[25]; int Price; void getrecords() { cout<<"\n Enter BNo "; cin>>Bno; cout<<"\n Enter Bname "; gets(Bname); cout<<"\n Enter Price "; cin>>Price; } void showrecords() { cout<<"\n BNo \t"<<Bno; cout<<"\n BName \t"<<Bname;
cout<<"\n Price } };
\t"<<Price;
void main() { clrscr(); int choice; cout<<"\n 1: Add Records in a file "; cout<<"\n 2: To modify the price of the given Bno "; cout<<"\n Enter your choice "; cin>>choice; Records s; fstream file; switch(choice) { case 1: file.open("Records.txt",ios::app); s.getrecords(); file.write((char *)&s, sizeof(s)); file.close(); cout<<"\n Press Enter..."; break; case 2: /*file.open("Records.txt",ios::in); file.seekg(0); while(!file.eof()) { file.read((char *)&s, sizeof(s)); if(file.eof()) break; s.showrecords(); } file.close();*/ int n,bno,p; char bname[25]; cout<<"\n Enter Bno to modify the price "; cin>>n; //searching the price record in the file file.open("Records.txt", ios::in); file.seekg(0); while(!file.eof()) { file.read((char *)&s, sizeof(s));
if(file.eof()) break; if(s.Bno==n) { bno=s.Bno; strcpy(bname,s.Bname); cout<<"\n Enter new price "; cin>>p; break; } } file.close(); //to modify the price file.open("Records.txt", ios::in); fstream temp; temp.open("temp.txt", ios::out); file.seekg(0); while(!file.eof()) { file.read((char *)&s, sizeof(s)); if(file.eof()) break; if(n==s.Bno) { s.Bno=bno; strcpy(s.Bname,bname); s.Price=p; } temp.write((char *)&s, sizeof(s)); } file.close(); temp.close(); file.open("Records.txt", ios::out); temp.open("temp.txt",ios::in); temp.seekg(0); file.seekg(0); while(!temp.eof()) { temp.read((char *)&s, sizeof(s)); if(temp.eof()) break; file.write((char *)&s, sizeof(s)); } file.close(); temp.close(); //to display records after change
file.open("Records.txt", ios::in); file.seekg(0); file.read((char *)&s, sizeof(s)); while(!file.eof()) { s.showrecords(); file.read((char *)&s, sizeof(s)); } file.close(); break; } getch(); }
Solution: 14 /*Define a class clothing in c++ wit the following description: private members code of type string Type of type string Size of type string Material of type string Price of type string A function Calc_Price() which calculates and assigns the value of price as follow: For the Cotton value of Material as "COTTON" Type price TROUSER 1500 SHIRT 1200 For Material other than "COTTON" the above mentioned Price gets reduce by 25% public members .A constructor to assign initial value of code, type, and metrial with the word NOT ASSIGNED and size and price with 0 .a function Enter() to input the values of the data members code, type, size and material and invoke the Calc_Price() function. .A function show() which displays the content of all the data members for a clothing. write a program to read and write the object of the above class in a file. */ #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> class clothing { private : char code[5], type[15], size[4], material[10]; float price;
void Calc_Price() { if( strcmp(type,"trouser")==0 && strcmp(material,"cotton")==0) price=1500; else if(strcmp(type,"shirt")==0 && strcmp(material,"cotton")==0) price=1200; else if(strcmp(type,"trouser")==0 && strcmp(material,"noncotton")==0) price=1500-(1500*25)/100; else if(strcmp(type,"shirt")==0 && strcmp(material, "noncotton")==0) price=1200-(1200*25)/100; } public : clothing() { strcpy(code,"NOT ASSIGNED"); strcpy(type,"NOT ASSIGNED"); strcpy(size,"0"); price=0.0f; strcpy(material,"NOT ASSIGNED"); } void Enter() { cout<<"\n Enter Code "; gets(code); cout<<"\n Enter type (\"trouser or shirt \") "; gets(type); cout<<"\n Enter size "; gets(size); cout<<"\n Enter material (\"cotton or noncotton\") "; gets(material); Calc_Price(); } void Show() { cout<<"\n Code \t Type \t Size(CMS) \t Materia \t Price \n"; cout<<" "<<code<<"\t"<<type<<"\t "<<size<<"\t "<<material<<"\t "<<price; } }; void main() { clrscr(); clothing obj; obj.Enter(); obj.Show(); getch();
} /*Declare a class Sports having: . Sno . Sname . Fees . Required Functions Write a menu driven program: . To append record in a file. . Delete the record of given Sno. */ #include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> #include<fstream.h> class Sports { public : int Sno; char Sname[25]; int Fees; void getsports() { cout<<"\n Enter Serial No "; cin>>Sno; cout<<"\n Enter Sports name "; gets(Sname); cout<<"\n Enter Fess "; cin>>Fees; } void showsports() { cout<<"\n Serial No \t"<<Sno; cout<<"\n Sports Name \t"<<Sname; cout<<"\n Fees \t"<<Fees; } }; void main() { clrscr(); int choice; cout<<"\n 1: Append Records in a file "; cout<<"\n 2: Delete the records of a given Serial No "; cout<<"\n Enter your choice ";
cin>>choice; Sports s; fstream file; switch(choice) { case 1: file.open("Sports.txt",ios::app); s.getsports(); file.write((char *)&s, sizeof(s)); file.close(); cout<<"\n Press Enter..."; break; case 2: int n; cout<<"\n Enter serial number to delete "; cin>>n; file.open("Sports.txt",ios::in); fstream temp; temp.open("temp.txt",ios::out); //deleting records from file while(!file.eof()) { file.read((char *)&s, sizeof(s)); if(file.eof()) break; if(n!=s.Sno) temp.write((char *)&s, sizeof(s)); } file.close(); temp.close(); temp.open("temp.txt",ios::in); file.open("Sports.txt",ios::out); temp.seekg(0,ios::beg); while(!temp.eof()) { temp.read((char *)&s, sizeof(s)); if(temp.eof()) break; if(n!=s.Sno) file.write((char *)&s, sizeof(s)); } temp.close(); file.close(); // Reading records from beging after deleting one record
file.open("Sports.txt",ios::in); while(!file.eof()) { file.read((char *)&s, sizeof(s)); if(file.eof()) break; s.showsports(); } file.close(); break; } getch(); }
Operator Overloading
C++ has the ability to provide the operator with a special meaning for a data type. The mechanism of giving such special meaning to an operator is known as operator overloading. This technique provides a flexible option for the creation of new definitions for most of the c++ operators. When we do operator overloading than, operators original meaning is not lost. For example the + operator, which has been overloaded to add two vectors, can still be used to add two integers. Operator overloading is done with the help of a special function knonw as operator function. This function decribes the task. Operator overloading is of two types. 1. Uniary operator overloading. 2. Binary operator overloading. Uniary operator overloading #include<iostream.h> #include<conio.h> class sum { private : int a,b,c; public: void getdata(int x, int y, int z) { a=x; b=y; c=z; } void show() { cout<<"\n A = "<<a; cout<<"\n B = "<<b; cout<<"\n C = "<<c;
} void operator -() { a=-a; b=-b; c=-c; } }; void main() { sum s; s.getdata(10,-20,30); s.show(); -s;//calling of operator cout<<"\n================\n"; s.show(); getch(); }
else temp.a=s2.a; return temp; } }; void main() { minimum s1(4), s2(1), s3; cout<<"\n First Number "; s1.show(); cout<<"\n Second Number "; s2.show(); cout<<"\n Minimum number is "; s3=s1<s2; s3.show(); getch(); }
Tamplate
class genmethoddemo { static<t, v extends t> boolean isin(t x, v[] y) { for(int i=0;i<y.length;i++) if(x.equals(y[i])) return true; return false; } public static void main(String args[]) { Integer nums[]={1,2,3,4,5}; if(isin(2, nums)) System.out.println("2 is in nums "); } }
} } class threed extends twod { int z; threed(int a, int b, int c) { super(a,b); z=c; } } class coords<t extends twod> { t[] coords; coords(t[] o) { coords=o; } } class boundwildcard { static void showxy(coords<?> c) { System.out.println("x y coordinates "); for(int i=0;i<c.coords.length;i++) System.out.println(c.coords[i].x+" "+c.coords[i].y); System.out.println(); } public static void main(String args[]) { twod td[]={new twod(0,0),new twod(7,9), new twod(-1,-23)}; coords<twod>tdlocs=new coords<twod>(td); System.out.println("Contents of tdlocs"); showxy(tdlocs); } }
class threed { int x,y,z; threed(int a, int b, int c) { x=a; y=b; z=c; } } class coords<t extends threed>
{ t[] coords; coords(t[] o) { coords=o; } } class boundwildcard2 { static void showxyz(coords<?> c) { System.out.println("x y z coordinates "); for(int i=0;i<c.coords.length;i++) System.out.println(c.coords[i].x+" "+c.coords[i].y+" "+c.coords[i].z); System.out.println(); } public static void main(String args[]) { threed td[]={new threed(0,0,0),new threed(7,8,9), new threed(-1,-23,-50)}; coords<threed>tdlocs=new coords<threed>(td); System.out.println("Contents of tdlocs"); showxyz(tdlocs); } }