0% found this document useful (2 votes)
984 views

Mastering C++ Programs Preview

A practical approach to c# by Jb Gupta

Uploaded by

wikedsunny
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (2 votes)
984 views

Mastering C++ Programs Preview

A practical approach to c# by Jb Gupta

Uploaded by

wikedsunny
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 494
Copyright © 2004 by Firewall Media (An imprint of Laxmi Publications Pvt. Ltd.). All rights reserved. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher. International Standard Book Number : 81-7008-364-8 10987654321 Limits of liability and disclaimer of warranty : The information and material contained in this book are provided “as is", without any warranty concerning the accuracy, adequacy, or completeness of such information or material or the results to be obtained from using such information or material. Firewall Media (An Imprint of Laxmi Publications Pvt. Ltd.) shall not be responsible for any claims attributable to errors, omissions, or other inaccuracies in the information or material contained in this book, and in no event shall Firewall Media (An Imprint of Laxmi Publications Pvt. Ltd.) be liable for direct, indirect, special, incidental, or consequential damages arising out of the use of such information or material. ‘Trademarks : Trademarked names appear throughowe this book. Rather than list the names and organizations that own the trademarks or insert trademark symbols with each mention of the trademarked name, the publisher states that this book uses the names only for editorial purposes, and to the benefit of the trademark owner, and has no intention of infringing upon thet trademark. Published by FIREWALL MEDIA Branches (An Imprint of Laxmi Publications Pvt. Ltd.) | Bangalore (Phone : 080-661 15 61) 22, Golden House, Daryaganj, Chennai (Phone : 044-2434 47 26) New Delhi-110002 Cochin (Phone : 0484-239 70 04) India ‘Guwahati (Phones : 0361-254 36 69, 251 38 81) Phone : 011-28 25 25 74 Hyderabad (Phone : 040-2475 02 47) Fax : 011.28 25 25 72 Jalandhar City (Phone : 0181-222 12 72) Kolkata (Phones : 033-22 80 2931, 22 80 90 19) ‘Lucknow (Phone : 0522-220 95.78) Mumbai (Phone : 022-24 46 39 98) Ranchi (Phone : 0651-230 77 64) /erwre Jnxmipublicat E-mail : [email protected] First Edition : 2003 Reprint : December 2003 Price : Rs. 295.00 Only C—7927/03/11 Typesetting by : ABRO Enterprises, Delhi Printed at : Ajit Printers, Maujpur, Delhi erage epe = Find roots of a quadratic equation 9. Print first ‘n’ natural numbers and their sum using while loop 10. Print first ‘n’ natural numbers and their sum using do-while loop 11._Print first ‘n’ natural numbers and their sum using for loop 12, Convert temperature given in centigrade to fahrenheit and viceversa 13, Print number of days in a month 14. Generate a simple calculator 15. Generate given pattern BERBRREBmaaane RRS a7 BBE a 28. Generate first ‘n’ prime numbers 29. Generate prime numbers upto a specific limit 20. Obtain the prime factors of a number 81 Print all composite numbers between 1 and ‘n’. 32, Print multiplication table of a number 83, Print all possible combination of three digits 44. Calcultae LOM and G.C.D of two numbers 36. Print first ‘n’ natural numbers in ascending/decending order 86. Print sum of first ‘n’ even/odd numbers in ascending/descending order ei Find the factorial of a number a 2 . ‘ ‘Swap two numbers without using temporary variable Count occurence of positive negative and zero in a stream of data terminated by some specific value Determine pythagorean triplets between 1 to 200 Input a character and check whether it is an alphabet, digit or any other character Calculate area of either circle, rectangle or triangle depending upon user’s choice Find sum of series X+X*2+X*3+X"4 Convert decimal numeral to roman numeral Generate a triangle pattern BREBBE a Chapter 2 FUNCTIONS Haar Display general message Display welcome message Calculate compound interest Find sum of three numbers Emulate ‘stremp’ function Perform base conversion ‘Swap two numbers using call by reference Calculate area and perimeter of a circle using call by reference Demonstrate default argument function . Add the specific number of distance values ( feet and inches) using inline function. 12. Sum of sine series 13._Sum of cosine series 14. Sum of series 1+1/1!+1/21+1/3!+ .... 15, Sum of series x- (x*2V2! +(x*3V8! - (x*4)4l +. SPAN MAs ETE See Chapter 3 STRUCTURES 1. Read an employee record and print it 2. Accept and print student's marks 3. Read employees record using array of srtucture and display them @SSSRRF BRESSRELSSRRE Bee 72 73 18 76 7 18 81 82 ses PBB PF 6B BF Beexnege oe ep BEBpexe NOT Ae PE (xi) Search for a particular employee and display its record Prepare salary chart of emlpoyees Calculate area of either circle, rectangle or triangle Check for a valid date ‘Add days to a valid date Create records of countries and capitals Pass structues to function by value(here two times are entered in hh-mm-ss format and then added up) Acess structures using pointers Pass structures to function by refernce(here seconds are entered as input and converted to hh-mm-ss format) Return a structure from a function.(here two times are entered in hh-mm-ss format and then added up) Read employee records using array of pointers to structures and display them Return refernce to a structure from a function (here two times are entered in hh-mm-ss format and then added up) Operate on weekdays using enumerated data type Accept income of user from all the months, sum up the same and print the message Create boolean data type Chapter 4 CLASSES AND OBJECTS Store bank client data Register the entrance of people(male/female) using static class data Input and display library records and demonstrate array of objects Maintain employee records using classes Construct a class for storage of dimensions of a circle ,triangle and rectangle and calculate their areas Demonstrate the destructor while calculating the area of a circle Practical demonstration of the destructor Perform arithmatic operation on complex data using class and object, Enter a date and add or subtract an integer from it depending upon user's choice Accept and count votes of candidates Chapter 5 RECURSION Generate first ‘n’ fibonacci terms Find sum of digits of a number Find factorial of a number Find G.C.D of two positive numbers Solve the problem of tower of hanoi Compute binomial coefficient Compute Ackermann’s function Bee 100 102 105 107 108 109 1 113 15 7 118 BE 6B BEBee Noone BRE Seesaapere eeNe (xii) Compute positive or negative integer exponential power of floating-point number Add two positive integers Multiply two positive integers Perform binary search Evaluate F(x)=0 if x=1 = Fov2)41 if >1 Evaluate F(i)=F(A,n,i) =0 if i=0 =F(i-1)+Ali] if O>,<<) Find volume using overloaded functions Add seconds and time (hh-mm-ss) to a specific time(hh-mm-ss) value using overloaded functions. Chapter 7 INHERITANCE Implement inheritance Override base class members Complement inheritance using the public access specifier Implement inheritance using the private access specifier Illustrate base class initialization Mllustrate multiple inheritance |. Illustrate ambiguities in multiple inheritance Resolve ambiguity in multiple inheritance (use the scope resolution operator) ). Resolve ambiguity in multiple inheritance (use of an overridden member function) |. Mlustrate ambiguity in multiple inheritance Resolve ambiguity in multiple inheritance(use of scope resolution operator) t. Resolve ambiguity in multiple inheritance(use of virtual base class) . Illustrate the order of the execution of constructors and destructors Chapter 8 POINTERS Illustrate dynamic memory allocation . Print array elements being pointed to by an array of pointers E the position of the strings in an using an of; ‘Swaplint )) two variables using pointers 160 161 162 163 165 166 167 168 173 175 amg 179 181 183 REEE BRESe8s Ee BS (xiii) 5. Return a pointer from a function Search for a given character i of match Ilustrate the use of structure pointers Illustrate the use of pointers Tllustrate the use of this pointer Illustrate concept of pointers Mlustrate the pointer to a pointer Illustrate usage of array of pointers to objects Illustrate the usage of the pointers to derived objects Pp tring and print the string from start to the point BRE Bees Chapter 9 VIRTUAL AND FRIEND FUNCTIONS . Mlustrate virtual function Mlustrate runtime polymorphism Mlustrate pure virtual funetion Tilustrate working of a friend function Mlustrate a friend class Ilustrate the friend function as bridges . Multiply two matrices using a friend function NOTP EYE Chapter 10 FILE HANDLING IN C++ Create a file to store integers and display the contents Create a file to store the text in it and display the contents Ilustrate the usage of put ( ) function Copy a text file to another Create a file which will store student's records Print the result of students whose records are stored in a file Create a file of objects and display the objects stored in the file Find the size of a file in bytes . Read a text file and create another file in which multiple blanks are replaced by a single one Show use of write( ) function. Illustrate working with multiple files Tlustrate command line arguments SPIAAReym Bre Chapter 11 TEMPLATES Find minimum of two values using a function template Find largest value contained in an array Illustrate a template function with multiple parameters Bubble sort using nested template functions Overload a template function Ilustrate a class template ‘L Mustrate a template class with three generic data types PoP eye 261 264 266 268 270 275 276 277 279 281 282 285 B RBEEEBREBBBEBBBEBBEBBE BRBREE BEB eenageene (xiv) Chapter 12 ARRAYS Generate Pascal triangle ind maximum, minimum and sum of array elements Find sum and average of ‘n’ numbers Find largest of ‘n’ numbers Reverse an array of ‘n' numbers Reverse an array of ‘n’ numbers without using temporary variable Check a number for palindrome Concatenate two arrays Perform insertion in an array at a specific position Perform insertion in a sorted array Perform deletion from an array from a specific position Perform deletion of a specific element from an unsorted array (only first occurence is deleted) Perform deletion from a sorted array given in ascending order Generate prime number from 1 to size(say 200) by ‘sieve of Eratosthenes’ method Merge two sorted arrays(given in ascending order and resultant array in ascending order) Merge two sorted arrays(given in ascending order and resultant array in descending order) Delete all occurence of a number and shift other elements to left and fill unused spaces by zero Find the maximal subsequence out of a given sequence Remove the duplicate elements from an array Evaluate student record using an array Find transpose of a matrix, Find transpose of a square matrix and the store result in itself Find trace of a square matrix Perform addition of two matrices Perform subtraction of two matrices Perform multiplication of two matrices Find sum of individual rows and columns of a matrix. Find sum of the elements on both diagonals of a square matrix. Find sum of elements above and below main diagonal of a square matrix. Perform row-wise sorting of a matrix(selection sort) Print lower and upper triangle of a square matrix. Check @ square matrix for symmetry Calculate the norm of a matrix. Check a square matrix for orthogonality Create spiral matrix. Find inverse of a square matrix. Read a document and display all the words along with the corresponding lines in which each particular word appears Input four words and display first and third word horizontally in the same line together with second and fourth word vertically intersecting the first and the third word respectively at the first common letter(without using gotoxy ( ) function) 311 313 317 320 323 328 EEBEEES 347 Sa888 362 S88 875 8 (xv) Chapter 13 STRINGS 1. Input a string and convert the lower case characters to upper case 2. Check a string for palindrome 8. Reverse all the strings stored in an array 4. Check for the presence of a character in a string 5. Concatenate two strings 6. Find the ney of a particular character in a stream of data 7. Calculate frequency of all characters in a stream of data 8. Accept a month number and display the month name @ Eneryption and Decryption of your string Chapter 14 LINKED LIST o 4 display a linked list Insert a node at the beginning or at the end of a linked list Insert a node at the desired position in a linked list Insert a node at the proper position in an ordered linked list fuck a Haket anata ; z ink PR ; z Modify the contents of a specific node in a linked list 5 inked ‘Merge two linked lists in ascending order without concatenation Merge two linked lists in ascending order by concatenating them first Create and traverse a doubly linked list Insert a node at the first place in a doubly linked list Insert a node at the end of a doubly linked list, ‘a node at the desired position in a doubly linked list Concatenate two doubly linked lists ‘Add two numbers using doubly linked list Chapter 15 STACKS Perform push,pop,peep and update operations using array implementation Perform push,pop,peep and update operations using linked list implementation Check an inputted expression for balanced parenthesis Convert infix expression into postfix expression using stacks and doubly linked list Evaluate postfix expression Carry out base conversion Reversal of string FSpexrgaupene BBPREER Rese eye 385 386 387 390 391 392 394 395 eeepr yeepe veep Gi) Chapter 16 QUEUES Perform insertion, deletion, peep and update operations (array implementation) Perform insertion, deletion, peep and update operations (linked list implementation) Check a string for palindrome using stack and queue Create circular queue(array implementation) Implemantation of queue as circular linked list Chapter 17 TREES Create a binary tree recursively Create a binary tree Create and traverse a binary search tree recursively Delete a node from a binary search tree Create and perform various operations on a binary tree (traversing is done non recursively) Chapter 18 GRAPHS Implement a graph using adjacency matrix. ‘Traverse a graph using depth first search technique ‘Traverse a graph using breadth first search technique Find the shortest path between two vertices using WARSHALL'S algorithm Find the shortest path between two vertices (nodes) using WARSHALL'S modified algorithm 6. Find the shortest path between two vertices (nodes) using DIJKASTRA’S algorithm Peraasepe Find all pair shortest path matrix from a weighted matrix using FLYOD’S algorithm Chapter 19 SEARCHING AND SORTING Perform linear search Perform binary search Perform selection sort Perform bubble sort Perform insertion sort Perform quick sort Perform shell sort Perform merge sort Perform heap sort Chapter 20 GRAPHICS Scroll a message using graphics 2. Generate rectangle pattern Simulate grid game using graphics Appendices 473 476 483 493 496 499 527 532 541 552 872 575 578 587 593 ELEMENTARY PROGRAMS Copyrighted material // To calculate the sum and average of five numbers #include //for ‘cout’ and ‘cin’ functions #include //for clrscr() function void main() { float a,b,¢,d,e,sum,avg; elrser(); cout<<"\nEnter the five numbers: \n"; cin>>a>>b>acr>do>e; sums (atb+c+dte) ; avg=sum/5; cout<<"\nSum= “< #include void main() { float principal, rate, time, interest; elrser(); coutc<"\nmnter the principal: *; cin>>principal; coutc<"\nEnter the rate of interest: *; cin>>rate; coute«"\nEnter the time period(in year: cin>>time; interest=(principal*rate*time) /100.0; cout<<"\n\nSimple Interest is computed as: “< #include void main() { int a,b,c, big; clrser()} cout<<"\nEnter the three numbers:\n"; cin>>as>be>c; bigsa; //assuming ‘a’ as the largest number if (b>big) big=b; if (c>big) big=c; cout<<"\nLargest number is= “< #include void main() { int a,b,c; elrser(); cout<<"\nEnter the three numbers: \n"; cin>>a>sbe>c; if (acb) { if (ace) cout<<*\nSmallest number is= “< #include void main() { ; int year; elrser(); cout<<"Enter the year \n"; cin>>year; cout<<"\n"; if( ((yeart4e=0) && (yearti00!«0)) || ( yeart400==0) ) coutccyearcc" is a leap year\n"; else coutccyearcc” is not a leap year\n"; Enter the year 2002 2002 is not a leap year Enter the year 2004 2004 is a leap year //t0 find area of a triangle and its type #include #include #includecmath.h> //for sqrt() function void main() { float a,b,c,s,area; MASTERING G++ PROGRAMS elrser(); cout<<*\nEnter the three sides of the triangle:\n"; cin>>a>>b>>c; coutcc"\na= “ceace* be “ccbec* ce “cecccendl; if( ({avb)>c) && ((bec)>a) && ((cra)>b) ) { if((ameb) && (a==c)) cout<<"\nEquilateral triangle\n"; else { if({as=b) || (be=c) || (c==a) coutc<"\nIsosceles triangle\n"; else cout«<"\nScalene triangle\n"; } s=(atbec) /2.0; area=sqrt (s*(s-a) *(s-b) *(s-c)); cout<<"\nArea= “< #includecconio. h> void main() { int day; clrser(); cout<<“\nEnter the no. of weekday (1-7):\n"; cin>>day; switch (day) { case 1: break; cout<<"\nWeekday break; cout<<"\nWeekday break; cout<<"\nWeekday break; cout<<"\nWeekday break; cout<<"\nWeekday break; case 7: cout<<"\nWeekday break; case 2: case 3: case 4: case 5: case 6: cout<<"\nWeekday i Sunday”; Monday” ; Tuesday"; Wednesday’ Thursday"; Friday"; Saturday”; default :cout<<"\nWrong choice”; }//switch ends geteh(); } Enter the no. of weekday (17) : 5 Weekday is Thursday Enter the no, of weekday (1—7) : 8 Wrong choice _ ea // To find the roots of a quadratic equation #include #include #includecmath.h> void main() { float a,b,c, disc, xr1,xr2, imgl, img?; clrser(); coutcc"Enter the coefficients\n"; cin>>a>2b>>c; //echo the data cout<<"\na= “0.0) { cout<<"\nReal and distinct roots\n"; xrl=(-besgrt (disc)) /(2.0*a) ; xra=(-b-sqrt (disc) ) /(2.0*a); cout<<"\n\nFirst root = “< #include void main() { int sum=0,n; elrser (); cout<<"\nHow many natural numbers you want to print with their sum:\n"; cinson; coutc<'\n‘ccn //for ‘cout’ and ‘cin’ functions #include //for clrscr() function void main() { float cent, fahr; int choice; do { elrser(); cout<<"1, Centigrade to fahrenheit\n"; cout<<"2. Fahrenheit to Centigrade”; cout<<™\n\nEnter the desired conversion: *; cin>>choice; } while((choice<1) || (choice>2));//get the correct value only switch (choice) { case 1: cout<<"\nEnter the cent temperature: *; cin>>cent; fahr=1.8*cent + 32.0; cout<<"\nCent temperature= “<>fahr; cent=(fahr-32.0)/1.8; cout<<"\nFahrenheit temperature= “< //for cin() and cout() functions #include //for clrscr() function void main() { int month; do { elrscr(); cout<<"\nEnter the month number{1-12): “; cin>>month; } while((month<1) || (month>12)); //get the correct value only switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12:cout<<"\n31 days are there in the month"; break; case 2: coutc<"\n28 or 29 days are there in the month”; break; case 4: case 6: . case 9: case 11:cout<<"\n30 days are there in the month”; break; }//switch statement ends here getch() ; : } Enter the month number (1—12) : 5 31 days are there in the month Enter the month number (1—12) : 9 30 days are there in the month //To generate a simple calculator #includeciostream.h> #include void main() { float x,y; char operand; elrser(); cout<<"\nEnter the two operands cin>>x>>y; cout<<"\nEnter the operation to be performed(+,-,*,/): “; cin>>operand; switch (operand) { case ‘+! — : coutccendlecxce'+! ceyce"= “ex (x+¥) break; case ‘-' — : coutccendlccxee'-"ccyec"= “ce (x-y); break; case ‘*! —: coutccendlccxce'#/ccyce= “ec (xty) ; break; + if(yeno) cout<<"\nDivision by zero not possible”; else cout #include void main() { int line_nos; elrser(); cout<<*\nEnter the desired number of lines<=10: *; cin>>1ine_nos; cout<<"\n\nDesired pattern is:\n\n*; for(int i=1;iceline_nos;i++) for(int j=l;jeeisj++) coutccje<"\t’; cout< co 0 co 09 oo aan ee ana MASTERING C++ PROGRAMS /*To print the following pattern: 1 2 3 1 2 1 / #include #include void main() { int line_nos; clrscr()7 cout<<*\nEnter the desired number of lines<=10: *; cin>>line_nos; cout<<"\n\nDesired pattern ii for(int isline_nos;i>=1;i-~) { n\n"; for(int j=1;}<=i;j++) { coutecjee'\t?; }//j for loop ends here cout< #include void main() { int line_no; clrser(); cout<<"\nEnter the number of required lines in the pattern: cin>>line_no; cout<<™\n\nRequired pattern is:\n"; for(int i=1;ic-line_no;i++) { cout<<'1"; int sume1 for(int j=2;j<=i;j++) { coutc<'+/ ej; sum+=j; } coutcc"» “cesumecendl; } getch(); } Enter the number of required lines in the pattern : 10 14243444546 = 21 14243+4+546+7 = 28 14+243+4+54647+8 = 36 1424+3+4+546+74849 = 45 14243+-44+546+74+8+9+10 = 55, | 20 MASTERING C++ PROGRAMS //To generate the pyramid #include #include void main() int n; do elrser(); cout<<*\nHow many lines of pyramid required(1-9) :\n"; cin>on; while(({n<1) || (n>9));//get the line numbers for right value cout<<"\n\n*#***Desired Pyramid is*****\n\n"; for(int iel;icen;it+) { cout<<" % for(int j=1;j<=(n-i) ;j++) cout<<* for (j=1;jcsi;j++) cout<=2;5- cout< #include void main() { int mid; clrser(); cout<<"\n\n**#*#Desired Pyramid is**#**\n\n"; for(int isl;i<=10;i++) { cout<<" Ss, mid=(2*i)-1; for(int j=1;j<=(10-i) ;j++) coutc<* *; for (jai; jeomids ++) cout<< (#10) ; for (j= (mid-1) ;j>=i;j--) cout<< (4$10) ; cout< #includecconio.h> void main() { int a,b,next,n,count; elrser(); cout<<"\nHow many fibonacci terms required >=2 and <= 24?\n"; cinson; a=0; bel; cout<<"\nFirst “<=2 and <=24 ? 10 First 10 fibonacci terms are : 01123 5 8 13 21 34 ELEMENTARY PROGRAMS 27 me ES //To generate fibonnaci terms upto a specific limit #includeciostream.h> #include void main() { int a,b,next, limit; clrser(); cout<<"\nEnter the limit upto which fibonnaci terms required:\n"; cin>>limit; cout<<'\n'<<"fibonacci terms upto “< #include void main() { int a,b,next,num; elrser(); cout<<"\nEnter the number for fibonacci check: \n*; cin>>num; if((nume=0) || (num==2)) cout< #include void main() { int num,n,sum,r; elrser(); cout<<*\ngnter the number: \n"; cin>>num; n=num, sum=0; while (n!=0) { rent10; //obtain the remainder sum+s(rtr*r) ; n/=10; } if (sum==num) cout #include void main() { int num,n,sum,r,limit; elrscr(); cout<«"\nEnter the limit upto which armstrong numbers are require: cin>>limit; coutc<"\narmstrong numbers upto “< #includecconio.h> void main() { int num, mid, sum=0; clrscr 0; cout<<"\nEnter the number: \n"; cinssnum; mid=num/2; for(int iel;icemid;i++) { if ((numti) ==0) sum+=i; } if (sume=num) cout<<'\n’ #include void main() { int num,mid, sum, limit; elrser(); coute<"\nEnter the limit upto perfect numbers are required:\n"; cin>>limit; if (Limit<6) cout<<"\nno perfect number upto “< #includecccnio.h> #includeemath.h> //for sqrt () function void main() { int num, i, clrser(); cout<<"\nEnter the number: \n"; cin>snum; if (num<2) coute<'\n' #include #include //for sqrt() function void main() { int n,num,step,sq_rt, count; elrser(); cout<<"\nHow many primes are required?\n"; cin>>n; cout<<"\n'sq_rt) { coutcc' ‘ #includecconio.h> #includecmath.h> //for sqrt () function void main() { int Limit, num, step,sq_xrt; elrser() ; coutce"\nEnter the limit upto which prime numbers required: \n"; cin>>limit; if (Limit<2) cout<<"\nNo prime exists upto “<sq_rt) cout<<*\t! < #include #includecmath.h> void main() { } int num,mid,sq_rt, step; do { clrser(); coutonum; } while (num<=0) ;//loop continues until positive value is entered sq_rtesqrt (num) ; step=2; while (stepe=sq_rt) { if ((numtstep) ==0) break; else step++; }//while loop ends here if (step>sq_rt) cout<<'\n’ #include //for clrser() function #includecmath.h> //for sqrt () function void main() { int nj elrser (0); cout<<*\nEnter the number upto which composite numbers are required: \n"; cin>on; if (nea) coutc<"\nNo composite number exists upto “ #include void main() { int i,j,k: elrser(); cout<<"\nEnter 3 digits between (0-9) :\n"; cin>>ir>j>>k; cout<<"\n\nAll possible combinations are:\n"; G£((il=j) && (jt=k) && (kI=i)) { cout #include void main() { int num1,num2,lem,ged, temp, prod,n1,n2; do { elrser(); cout<<"\nEnter the two positive numbers: \n"; cin>>num1>>num2; } while(numi<=0 || num2<=0);//loop continues for correct values nlsnum; n2enum2; prodeni‘n2; while (n2!=0) { if {(n%m2) ==0) break; else { temp=n1*n2; nlen2; n2stemp; }//else statement ends here }//while loop ends here geden2; lem=prod/ged; cout<<"\nLCM of “ #include void main() { int n,choice; elrser(); cout<<"\nUpto what natural number you want to print:\n"; cin>on; cout<<"\nEnter 1 for ascending order coutc<"\nEnter 2 for descending order cin>>choice; switch (choice) { case 1 : cout<<"\nnatural numbers in ascending order are:\n"; for(int isl;icen;i++) coutccice \t'; break; case 2: coutc<*\nnatural numbers in descending order are:\n"; for (ien;i>=1;i--) coute #include void main{) { int n,i,choice,count=1,sum=0; elrser(); cout<<*\nHow many natural numbers you want to add?\n"; cinson; cout<<"\nEnter 1 for adding first “<>choice; switch (choice) { case 1: { ind; while (count++<=n) { sumt=i; it=2; } cout<<"\nsum= *< #tinclude void main() { int num; unsigned long factorial-1; elrser (}; cout<<"\nEnter the number: *; cin>>num; if (num #includecconic.h> #include //for pow() function #define PI 3.14 void main() { float radius,area; elrscr(); cout<<"\nEnter the radius(to terminate enter 0): *; cin>>radius; while (radius!=0) { area=PI*pow (radius, 2); cout<<"\nArea is: “radius; Enter the radius (to terminate enter 0) : 5 Area is : 78.5 sq. units Enter the radius (to terminate enter 0) : 0 //swapping of two numbers without using temporary variable #include #include void main() { int a,b; clrser(); cout<<"Enter the two numbers cin>2a>>b; cout<<*\n\nInputted numbers are:\n"; cout<<*As “< #include void main() { int num,no_of_pos=0,no_of_neg=0,no_of_zero=0; cirser(); cout<<"\nEnter the stream of data terminated by 999:\n"; cin>>num; while (num! =999) { Af (num>0) no_of_pos++; else { if (num<0) no_of_neg++; else no_of_zerot+; //outer else statement ends here } :. cin>>num; }//while loop ends here cout<<"\n\nOccurrences of positive numbers: “< #include #includecmath.h> void main() { int scroll=1; elrser(); coute<"The Pythagorean Triplets in the range 1 to 200 are: for(int i=1;i<=200;i++) { for(int j=i+1;j<=200;j++) { for(int k=j+1;k<=200;k++) { if(pow(i,2) + pow(3,2) == pow(k,2)) { coute #include #include //for pow() function void main() { int choice; do { elrser(); coutc<"\nl. Calculate the area of circle"; coutc<"\n2. Calculate the area of rectangle”; cout<<"\n3, Calculate the area of triangle”; cout<<"\n\nEnter the choice: "; cin>schoice; } while ((choice<1) || (choice>3));//Get the correct value only //ealeulate the area accordingly switch (choice) { case 1: float radius,area; cout<<"\n\nEnter the radius: cin>>radius; areae3.14 * pow(radius,2); cout<<"\nArea of the circle is: “>length>>breadth; area-length*breadth; cout<<"\nArea of the rectangle is: “>base>>height; areas (base*height) /2.0; cout #include #includecmath.h> //for pow() function void main() { double x, term; int nj elrscr(); coute<"\nEnter the value of X and N: cin>sx>on; double sum for(int i=2;icen;i++) sum+=pow (x, i); cout<<"\n\nSum of the series is: “< #include void main() { int symbol,moveto_x,moveto_y, pass, inc, number; elrser(); cout<<"\nEnter the number of triangles you want: cinssnumber; symbol=1; moveto_x=4 moveto_y=1 pass=1; ines2; for (int k=0;kenumber;k++) { //generate the right side of the triangle for(int j=0;j #include void main() { int num; unsigned long fact(int n); //function prototype elrser(); cout<<"\nEnter the number: *; cin>>num; if (num #include void main() { void display_message();//prototype declaration elrser(); display_me! getch(); } //function definition goes here void display_message() { cout<<"Welcome to world of programming\n*; cout<<*Programming is nothing but logic implementation”; ) age () ; Welcome to world of programming Programming is nothing but logic implementation FUNCTIONS 69 r a //To display welcome message using function #include #include void main() { void message();//prototype declaration elrser(); message () ; getch(); | esacesea definition goes here void message () { char name [20] ; cout<<"\nEnter your name: *; cin. getline (name, 20) ; elrser(); gotoxy (25,12); cout #include #includeciomanip.h> #include //for pow() function void main() { float principal, rate, time; void calculate(float, float, float); //function prototype elrser(); cout<<"\nEnter the following value! cout<<"\nPrincipal: °; cin>>principal; cout<<"\nRate of interest: cin>>rate; coutc<"\nTime period(in years): *; cin>>time; calculate (principal, rate, time) ; getch{); } //function definition void calculate (float p,float r,float t) { float interest; interest= p* (pow((1+r/100.0),t))-p; cout<<"\nCompound interest is: “< #include #include void main() { int number, base, a[30],total=0; char convert_to[15]; void conversion(int,int*,int&,int); //function prototype elrser(); cout<<"\nEnter the number to be converted: “; cin>snumber; cout<<"\nEnter the base(2,8,16) to which conversion is to be made: cin>>base; switch (base) { case 2: conversion (number, a,total,2); strepy (convert _to,"Binary”) ; break; case 8: conversion (number, total,8); trepy (convert_to,“Octal”) ; break; conversion (number,a,total, 16) ; strepy (convert_to, "Hexa-Decimal”) ; break; }//switch cout<<"\n\n"<<"Number converted to base “«=0;i--) { if(alil>s) cout< #include #includecmath.h> void main() { float x,term,xradians; int n=16,sign; unsigned long factorial(int); //function prototype elrscr(); cout<<"\nEnter the value of x (in degrees): *; cin>>x; xradians=x*3.14159/180; //convert x into radians sign=-1; float sum=1.0; for(int i=2;icen;i+=2) | ssemcpow retwocans! i) factorial (i); term*=sign; sum+=term; sign*=-1;//keep rotating the sign }//for loop ends here cout<<"\n\nCos ("< #include struct employee ‘ char name(20]; int empl_no; char designation(20]; char deptt [20]; } emp{10];// variable of the structure type can be defined void main() { char ch; int total; clrser(); cout<<"\nEnter the total number of employees <= cin>>tota: for(int i=0; { elrser(); cin.get(ch);//empty the buffer cout<<"Enter the record for employee- “<>emp[i].empl_n cin.get (ch) ;//empty the buffer cout<<"\nDesignation: “; cin. get (emp[i] .designation, 20); cin.get (ch) ;//empty the buffer cout<<"\nDepartment: “; cin.get (emp[i] .deptt, 20); ixtotal;it+) ) for (is0;ictotal;i++) ( elrser(); cout<<"\nRecord of employee no.- “< #include #include struct employee { char name[20]; int empl_nos int attendance; float daily wage: float salary; } emp[10];// variable of the structure type can be defined here int total; void main() t void display data (employee*) ;//prototype declaration char ch; elrser(); cout<<“\nEnter the total number of employees <=10: cin>>total; for(int i=0;ictotalsi++) elrser(); cin.get (ch);//empty the buffer cout<<“Enter the record for employee- “<>emp(i] .emp!_no; cout<<"\nAttendance: “; cin>>emp[i] .attendance; cout<<"\nDaily wage: “; cin>>emp[i].daily wage; emp [i] .salary-emp[i].attendance*emp[i} .daily wage; } //Echo the data display _data(emp);//call to function getch()7 ' void display _data(employee* emp1) { elrser{); 7 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book MASTERING C++ PROGRAMS //To check for a valid date using structure and function #include #include struct Date ‘ int day; int month; int year; }datel; enum boolean{false, true}; void main() { elrser(}; boolean valid _date(Date);//prototype declaration cout<<"\nEnter the date to be checked: \n"; cout<<“Day: “7 cin>>datel .da cout<<"Month: “ cin>>datel.month; cout<<"Year: “; cin>>datel.year; if (valid_date(datel)) cout<<*\n\nInputted date is valid “; else cout<<"\n\nInputted date is not valid”; getch(); i boolean valid date (Date ¢) f int days(]~(31,28, 32, 30,31, 30, 31,31,30,31,30,31};// days in months if({d.yeart4==0) && (d.year$100!=0)) |i (d.yeart400==0) days{1)=29;//if leap year then store 29 in corresponding position if(d.month<=12 4@ d-month>=1) { if ((d.day>0) && (d.day<=days{d.month-1]) && (d.year>0)) return true; else return false; } else return false; a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 106 Enter the time~ 1: Hours : 10 Minutes : 11 Seconds : 01 Enter the time- 2: Hours : 5 Minutes : 10 Seconds : 25 Resultant time in "hh mm ss" format is : Hours : 15 Minutes : 21 Seconds : 26 MASTERING C++ PROGRAMS a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 14 temp.minutes=-min860; return(temp) ; , Enter the time- 1: Hours ; 12 Minutes : 30 Seconds : 55 Enter the time- 2 : Hours : 8 Minutes : 10 Seconds : 45 Resultant time in "hh mm ss" format is : Hours : 20 Minutes : 41 Seconds : 40 MASTERING C++ PROGRAMS a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book CLASSES AND OBJECTS 123 //To register the entrance of people(male or female) using static class data #include #include #include class people { privat static int count; //static data member int male_num, female_num; public: people() //constructor ( male_num=0; female_num=0; ) void male_increment () { count++; male_num++; , void female increment () { count++; female_num++; ) void decrement_male() i if (count==0) cout<<"\nNo person in the room\n”; else t if (male_num!=0) 4 count-~7 male_nun--; } else cout<<"\nNo male in the room\n"; ' a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book CLASSES AND OBJECTS Designation : Systam Analyst Registration Number : 10001 Salary ; 30000 Enter the record for Employee 2 : Name: Ruchi Address : Sector 13, Karnal Designation : Lecturer Registration Number : 10002 Salary : 12000 1. Add Record 2. Delete Record 3. Display Record 4. Display List 5. Quit Enter the option : 4 Serial No. NAME DESIGNATION 1 Raman Sharma System Analyst 2 Ruchi Lecturer 1. Add Record 2. Delete Record 3. Display Record 4. Display List 5. Quit Enter the option : 1 Enter the rocord for Employee 3 : Name : Shri Bhagwan Dixit Address : S. M. Hindu School Designation : Teacher Registration Number : 10003 Salary : 9500 1. Add Record 2. Delete Record REG. NO. 10001 10002 131 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book CLASSES AND OBJECTS s=(sidel+side2+side3) /2; a=sqrt (s* (s-side1) * (s-side2) *(s-side3)); t//else statement ends here }//outer if statement ends here else a=3,14*radius*radius; cout<<"\n\nArea of the “< #include class rectangle { private: float length, breadth; public: rectangle () { //displayed whenever an object is created cout<<"I am in the constructor”; length=10.0; breadth=20.5; } float area() { return (length*breadth) ; ) Me void main() { elrser(); rectangle rect; cout<<"\nThe area of the rectangle with default parameters is: < #inelude class factorial { private: int num; public : unsigned long int fact (int); void display(int) ; //function definition fact () unsigned long int factorial:: fact{int num) { if ((nume=o) | | (nume=1)) return (1); else return (num*fact (num-1)) ; } //function definition display () void factorial:: display(int num) ! cout #include class Ackermann { public : int ack(int, int); ‘i //function definition ack() int Ackermann: :ack (int m,int n) { if( (m==0) && (n>=0) ) return (n+1}; if( (m>0) && (m==0) ) return ( ack(m-1,1) if( (m>0) && (n>0) ) return( ack ( m-1 ,ack(m,n-2) ) }; return (0); } //main function follows void main() { int m,n; Ackermann ob; //object declared elrser (); coutc<"\nenter the value of m and n\n"; cin>>m>>n; if ((mco) | | {n<0)) cout<<"\nackerman function not defined\n"; else cout<<"ack (“cemce™, "< #include fidefine size 20 class bsearch { public: int search(int*,int,int, int, int); i //function definition search () int bsearch: { if (lowshigh) return (-1); else { if (a{mid) data) return (mid+2) ; else { if (data>a [mid] ) { Lowamid+2; mid= (low+high) /2; return (search (a,data, low,high, mid) ) ; }//innermost if statement ends here else { high=mid-1; mid= (low+thigh) /2; return (search (a,data, low,high, mid) ) ; }//innermost else statement ends her‘ } }//outermost else statement ends here } //wain function follows void main() { int alsize],n,low, high, mid,data,pos; bsearch ob; //object creation elrser(); cout<<"\nenter the number of elements<# “< #include #include class reversal { publi he //function definition reverse () void reversal: :reverse(char* str) : void reverse (char*) ; { if (*str) { reverse (str+1) ; putchar (*str) ; } } //main function void main() { reversal ob; char arr [80]; elrser(); cout<<"\nenter the string\n”; cin.getline(arr, 80) ; cout<<"\nxeversed string is\n\n"; ob. reverse (arr) ; } enter the string Apoorva reversed string is avroopA a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book POLYMORPHISM, 173 //T0 demonstrate overloaded constructors (addition of length (in mt.gem.) ) #include #include class length t private: int mt,cm public: length() length(int m,int c) t mt=m+c/100; em=c$100; ) length(int total) { me=total/10) em=total¥100; i void display() { cout<<"\nMeters: “< #inélude class time ( private: int hours: int minutes; int seconds; public: time () {te time{int h,int m,int s) i hours=h? minutes=m; seconds=s; , void get_time() t cout<<"\nHours: “; cin>>hours; cout<<“Minute: cin>>minutes; sout<<"Second cin>>seconds; ) void display() 1 cout<<"\nHours: “< #include const size=5; class array { private : int arr[size]; public : array(); //constructs null array array(int *a); //constructs array from array friend array operator ‘(array temp,int n); //friend 1 friend array operator *(int n,array temp); //friend 2 friend ostream & operator << (ostream &,array &); friend istream & operator >> (istream &,array &); Me //constructor 1 definition array() array:: array() { int 4; for (i=0;ixsize;it+) arr[i}=0; i /f/eonstructor 2 definition array:: array(int *a) { int i; for (i=0;i #include const LEN =41; class publication { protected : // to provide access to derived classes char title(LEN}; float price; he class book f public publication private : int pages; public : void getdata (void) { cout<<"Enter cin. getline (title, LEN); cout<<"Enter the price : “; cin>>price; cout<<“Enter the no. of pages : “i cin>>pages; ) void putdata (void) ( cout<<"Title : “<>price; cout<<"Enter the playtime in minutes : “; a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book INHERITANCE student::getdata(); // to resolve the identity // as result has also getdata() getmarks(); cin.get(ch); // to empty the buffer cout<<"Enter the performance out of \n"; cout<<"Excellent/good/average/poor\n”; cin. getline (performance, 11); } void putdata (void) { student :: putdata(); cout<<"Performance : “< #include class ONE ( public : void display(void) ( cout<<“\nYou are in class ONE\n”; ) h class TWO ( public : void display (void) ( cout<<"\nYou are in class TWO\n”; ' he // multiple base class inheritance class derived : public ONE , public TWO ( public : // this function definition overrides the base class members void display (void) { TWO::display(); //first call display() of TWO ONE: :display(); //now call display() of ONE cout<<"\nYou are in the derived class\n"; ) hi void main() { derived obj; // object of derived class declared elrser(); //no ambiguity now obj.display(); //function call display() } ‘You are in class TWO You are in class ONE a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 217 //%0 illustrate dynamic memory allocation #include #include #include //for pointer initialization as NULL int *empno=NULL; //int pointer for empno array float ‘salary=NULL; //int pointer for salary array void main() ( int size; elrser(); cout<<"How many employees are there?\n"; cin>>size; //allocate memory dynamically for the arrays empno=new int [size]; salary=new float[size]; //check for memory availability i£((!empno) || (!salary)) cout<<"No free store available\n"; else { // enter the data for(int i=0;i>empno[i]>>salary (ils } // echo the data cout<<"\n\nYou have entered\n\n"; cout<<"\tEmpno\t\tSalary\n\n"; for (i=0;i #include void main() { elrser(); void exchange(float *a, float*b);// Prototype float valuel, value2; cout<<“Enter two numbers : "; cin>>valuel>>value2; // Echo the data cout<<“\nBefore exchange :\n”; cout<<*\nValuel= “< #include # define size 8 struct student char name(size]; int rolino; float marks; } topper={“Aanchal”, 3313, 100}; void main() { Structure elements using structure variable ar elrser(); student * ptr; ptr=atopper; // ptr points to structure variable topper cout<<"Structure elements using structure variable are :\n”; cout<<"\nName is : %; cout .write(topper.name, size); cout<<"\nRoline : “<name, size); cout<<"\nRollno : “<rollno; cout<<"\nMarks : “<mark: getch(}; Name is : Aanchal Rollno : 3313 Marks : 100 Structure elements using structure pointer are : Name is Aanchal Rollno : 3313 Marks : 100 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book // To illustrate concept of pointers #include finclude void main() { int x=336; int “ptr; int **ptr_to_ptr; ptr=6x; ptr_to_ptr= sptr; elrser{); cout<<"The addresses are shown in Hexadecimal form\n\n"; cout<<“\nYou may get some other addresses on your system\n\n”; cout<<"\naddress of x = “<<6x; cout<<"\nAddress of x = “< #include class base t public : int x; void display() ‘ cout<<"\nx = “<x = 1024; //access base using base pointer cout<<"\nb_ptr points to base object b_obj\n’ b_ptr->display(); derived d_obj; // derived class object declared b_ptr= éd_obj; // address of d obj stored in b_ptr b_ptr ->x = 2048; // to access derived using base pointer // bd ptr-> y = 3072 ; // it will give an error cout<<"\nb_ptr currently points to d_obj\n"; b_ptr->display(); 233 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 238 MASTERING C++ PROGRAMS ptr= sobj2; // now ptr points to dclass cout<<"\nptr is now pointing to delass\n\n"; ptr->messagel(); // derived version of messagel() used ptr->message2(); // belass::message2() used ptr is a pointer to belass You are using message1( ) in belass ‘You are using message% ) in belass ptr is now pointing to delass You are using message1( ) in delass You are using message2( ) in belass a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book FILE HANDLING IN_ 253 a // To create a file to store integers and display the contents #include // for file 1/0 #include void main() { ofstream Ofile(“INTEGER. TXT”) ; int x,y, elrser(); if( ! Offle) cout<<"Can’t open file for writing\n”; else { //connect file to output stream Ofile cout<<"Enter three integers\n”; cin>>x>>y>>z; Ofile<>x>>y>>z; coutccxce™ “ccyce" “ #include void main() { struct student ‘ char name[21}; int rollno; int marks[5]; int total; student stud; //structure variable declared int i,n,j,size; char target (13],ch; cirser(); cout<<"Enter the name of file to be created cin>>target; ofstream Ofile (target); //open file in output mode if( ! Ofile) cout<<"\nCan't open target file for writing\n”; else 4 size=sizeof(student); // find the size of structure cout<<"\nHow many students are there ?\n"; cin>on; for (i=1;icen:i++) { cin. get (ch); cout<<"\nEnter the name of student : “<>stud.rollno; cout<<"\nEnter the marks in five subjects for (j=0; ++) cin>>stud.marks (31+ stud.total=0 //compute the total for (5-07 4<5;5++) stud.total += stud.marks(j]; 257 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book FILE HANDLING IN C++ // To create a file of objects and display the objects stored #include #include #includeciomanip.h> //for formatting of data i.e. setw() class bill —// class definition { private int billno; float amount; public : void getdata(void); //function prototype void putdata(void); //function prototype }; // class definition over void bill { getdata(void) // function definition cout<<"\nEnter billno and amount\n"; cin>>billno>>amount ; i void bill :: putdata(void) // function definition i cout<>filename; file.open(filename, io: if( ! file) cout<<"\nCan’t open source file for writing\n’; else t in | ios :: out); cout<<"\nHow many objects are to be entered\n”; cin>>n; 261 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book FILE HANDLING IN C++ 265 cout<<"\nSource file has been copied to target file\n"; cout<<"\nMultiple blanks have been changed to single one”; , Ofile.close(); // disconnect filename from Ofile } Ifile.close(); // disconnect filename from Ifile Enter the source file name to be copied : try.txt Enter the target file name to transfer source file target.txt Source file has been copied to target file Multiple blanks have been changed to single one a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book FILE HANDLING IN C++ 269 The contents of EMPNAMES and EMPSALRY are : EMPNAME SALARY Raman Sharma 45000.00 Anil Nehra 20000.00 Rajbir Sharma 35000.00 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book Copyrighted maternal a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 278 MASTERING C++ PROGRAMS 90% QUTPUT *#eenenee Suecessful search 88 found at postion : 8 50 not found in the given list Successful search 3.5 found at position : 3 7.7 not found in the given list. a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book | 282 MASTERING C++ PROGRAMS // Tlustration of a class template #include #include fdefine s 20 //ereate a generic stack class template class stack t J st{s int top; public : stack() //constructor ( top = 0; //top initialised to 0 , void push(J obj); //prototype for push operation J pop: /Iprototype for pop operation he //function definition push!) template void stack::push(J obj) { if(top == s) { cout<<"\nStack Overflow\n"; return; , st[top] = obj; topt+; } //function definition pop() template J stack: :pop() { if (top ‘ cout<<"\nStack Underflow\n"; return (0); } top—-7 return(st (top]); 0) a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book Copyrighted material a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 290 MASTERING C++ PROGRAMS obj-pas_trianglein); // fur tion call pas_triangle() ) ends here How many lines of pascal triangle you want <=13 13 pascal triangle is z 10 «45 «=6120 210-252 210 120 4510 1 x ul 550165 880 462, 462330 165 55 n 1 1 12 66 220 495 792 924 792 495 220 66 12 1 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 294 MASTERING C++ PROGRAMS elrser(); cout<<"\nEnter the number of elements in the array<="<on; cout<<"\nEnter “< #include #define size 10 #define total 20 class array ( private: int i,a(size),b{size],c[total]; public: void enter(int *,int}; void concat (int *,int * ,int * ,int ,int); // for concatenation void display(int *,int); , // definition of the function enter() void array :: enter(int x{size),int s) ( for (i=0; i>x[i}s , // definition of the function display() void array :: display(int x(size],int s) { for (i=0;i>m; a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 308 MASTERING C++ PROGRAMS void main() { array obj int n,data; clrser(); cout<<“Enter no of elements<="<>n; cout<<"\nEnter “<>data; // echo the data cout<<"\nGiven array is\n\n"; obj.display(n); cout<<™\n\nElement to be inserted is “< #include #includecmath.h> #include // for setw() function #define size 200 class array ‘ private: int i,a(size]; public: void enter(); void sieve()}; //function sieve of Eratosthenes void display (); v2 // function definition enter(} void array: :enter() { //f411 integers from 1 to size in array for (i=0;icsize;it+) alil=itl; } // function definition sieve() void array: :sieve() ( int sqrt,ji sq_rt=sqrt (size); a(0]=0; for (i=1;i<=sq_rtyit+) { for(int j=i+l;j #include #include fdefine s 20 class array ( privat int i,als); public: void enter{int); void display(int); void maxseq(int, int &int &);//function for maximal subsequence void seq_display(int &, int &); Fy // function definition enter() void array::enter(int n) { for (isO;icn;itt) cin>>a lil; , // function definition display() void array::display(int n) { for (inO;icnsit+) cout<>n; cout<<"\nEnter “< #include fdefine size 5 class matrix { private: int i,j,order,a[size] [size]; public: void enter(int);//function prototype void display (int); void transpose (int); he // function definition enter() void matrix: :enter(int order) ( //row wise reading for (i=0;i>alil li}é , // function definition display() void matrix: :display(int order) ( for (in0;i>rowl>>colml; cout<<"\nEnter the order of second matrix <="<>row2>>colm2; if (colml==row2) { cout<<"\nEnter the first matrix of order “<>row>>colm: } //get ranged value only while(row<=0 || row>size {| colm<=0 || colm-size); cout<<"\nEnter the matrix of order “<>order; ) while(order<=0 || order>size);//get ranged value only cout<<"\nEnter the matrix of order “< ;clude fdefine size 5 enum boolean (false, true}; boolean flag; class matrix { private: int i,j,order,a[size] (size],b[size] [size]; public: void enter (int); void display(int); void transpose_multiply (int); boolean check_orthoganility(int); de // function definition enter() void matrix::enter(int order) { //row wise reading for (i=0;i>ali) (3): ' // function definition display () void matrix: :display(int order) { for (i=0; i # include //for cirser() # include //for exit() # include //for strlen() enum boolean {false, true}; char wi (20],w2(201,w3(20],w4{20]; int i1,i2,43,i4,j1,52.53, 543 void read() { cout << “ENTER THE FOUR WORDS SEPERATED BY A BLAN cin >> wl; cin >> w2; cin >> w3; cin >> wa; il = strlen(wl i2 = strlen(w2 i3 = strlen(w3); i4 = strlen(w4); ) //find the Zirst common alphabet between first & second /fand third and fourth words void find( char v1(20],char v2[(20],int il,int i2,inté j1,inté 42) { boolean flag = true; << endl; jl=-1; j2 = -1; int p = 0; while(p < il && flag) ( int k = 0 while {k < i2 && flag) { if(vl(p} == v2(k]) { ji = pF 32 = ke flag = false; )//4£ statement ends here else a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book STRINGS 389 /*To input string and a character and check if that character is present in the string or nott/ #include #include #include //for strlen() function fdefine size 40 void main() { char string{size],ch; int length, i=0; elrser(); cout<<"\nEnter the string of length<"<>ch; length=strlen (string); while (i9->8->7->6->5->NULL Enter the data field value of the node to be inserted: 77 Enter the option (1,2): 1. At the beginning 2. At the end 1 ‘The list after insertion is : T1->10->9->8->7->6->5->NULL The list before any operation is performed: 10->9->8->7->6->5->NULL Enter the data field value of the node to be inserted: 66 Enter the option (1,2) : 1, At the beginning 2. At the end 2 The list after insertion is : 10->9->8->7->6->5->66->NULL a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book MASTERING C++ PROGRAMS //fanction definition display() void link_list::display(int delete_node) { node* move= start; node* temp; while (move) { cout<data<<"->"; //display the data temp=move; move=move->next; //move to next node if{delete_node) delete (temp) ; } cout<<"NOLL"; } //function definition insert () void link_list::insert (int data) { node* move=start; node* insert_after=move; int is _first=0; while (move->datanext; ) node* new_node= new node; //create a new node; new_node->datasdata; if(is_first) i new_node->next=insert_after->next; insert_after->next=new_node; * else { new_node->next=start; start=new_node; } } void main() { int value, data, choice; clrser(); link_list links a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book //To reverse a linked list #include #include struct node { int data; //data field node* next; //pointer to the next node de class link list i private: node* start public: link_list() //constructor { start-NULL; //initially the list has no node ) void create{int i) { node* new_node= new node; //create a new node; new_node->data=i; new_node->next=start; //make new node to point to the first node start=new_node;// make new node as the first node in the list , void reverse();//function prototype void display(int);//function prototype J: //end of class //function definition reverse() void link_list::reverse() { node* previous=start; node* current=previous->next; node* temp; previous->next=NULL; while (current !=NULL) { temp=current->next; current->next=previous; previous=current; current=temp; ’ start=previous; 413 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 420 MASTERING C++ PROGRAMS Enter the elements of the list terminated by negative number: 12 45 28 49 36 70 55 -99 The list before any operation is performed (LIFO): 55->70->36->49->28->45->12->NULL Enter the old value to be replaced by the new one: 28 Enter the new value: 77 ‘The list after modification is: 55—>70->36->49->77->45->12->NULL a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book | 426 MASTERING C++ PROGRAMS //T0 merge two linked lists by concatenating them first #include #tinclude struct node { int data; //data field node* next; //pointer to the next node Me class link _list { privat node* start; public: link_list() //constructor { start=NULL; //initially the list has no node , void add_data();//function prototype void display(int);//function prototype void concatenate (link_list);//function prototype void sort ()://function prototype /fend of class //function definition add_data() void link_list::add_data() { int value; cinzavalue; while (value>=0) ‘ node* new _link= new node; //create a new node; new link->data=value; new_link->next=start; //make new node to point to the first node start=new_link;// make new node as the first node in the list cin>>value; d } //function definition display () void link_list::display(int delete_node) ‘ node* move= start; node* temp; a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 430 MASTERING C++ PROGRAMS //function definition display() void doubly class: :display() { cout<<“\n\nTraversing in the forward direction: \n\n"; doubly* move=start: do { move=move->front; cout<data<<"<->"; , while (move->front); cout<<"NULL"; cout<<"\n\nfraversing in the back direction: \n\n"; do 4 cout<data<<"<->"; move=move->back; } whi le (mave->back) ; cout<<"NULL"; ) void main{) { elrser(); doubly class d_list;//create an object d_list.create(); d_list.display(); getchi); Enter the data terminated by negative number: 20 30 10 40 60 50 -99 Traversing in the forward direction: 20<->30<—>10<->40<->60<->50<->NULL ‘Traversing in the back direction: 50<->60<->40<->10<->30<->20<-> NULL a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book LINKED LISTS 441 _ a // To concatenate two doubly linked lists #include #include struct doubly { int data; doubly* back; doubly* front; Me class doubly_class { private: doubly* start; public: doubly_class() { startenew doubly; start->front=NULL; start->back=NULL; start->data=-1; //header node- can contain other information also ) void create();//function prototype void concatenate (doubly class) ;//function protetype void display(};//function prototype Me //function definition create() void doubly _class::create() { int value; doubly* new_node=new doubly; new_node= start; cout<<“\nEnter the data terminated by negative number: \n"; cin>>value; while (value>=0) { new_node->front= new doubly; new_node->front->back=new_node; new_node=new_node->front; new_node~>data=value; new_node->front=NULL; a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book STACKS ss| //function definition peep() void stack::peep(int level) { node* temp=top; int move=1; while(move++!= level && temp) temp=temp->link; if(!temp) cout<<"Level does not exist”; else cout<<"Element found at level “<data; 1 //function definition update () void stack::update(int level, int data) { node* temp=top; int move=1; while(move++!= level 6& temp) temp=temp->Link; if (temp) cout<<"Level does not exist”; else temp->data=data; ' //function definition display() void stack: :display() { node* temp=top; while (temp) { cout<data<<* *; temp=temp->link; ) , void main() { elrser( stack s;//object created char choice; int data, level; do ‘ cout<<"\nPress: p(push), i(pop), r(peep), u(update), q(Quit) cin>>choice; switch (choice) a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book MASTERING C++ PROGRAMS { ch=getche( while (ch! ( temp=int (ch)-int ("0"); digit=digit*10+temp; chegetche(); } s.push (digit); } //i£ statement ends here Way , } while(1); } Enter the expression (with spaces) terminated by carriage return: 562+ * W4le Result of the evaluation is: 37 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 473 //Queue insert, delete, peep and update operations (array implementation) #include #include #include define size 20 enum boolean( false, true); class queue { private: int alsize], front, rear; public: queue () { fronterear ) void insert (int data) { if (rear>size) cout<<"\nQueue overflow”; else { a(+trear]=data; if(rear==1) front=rears }//insert() ends here ) void deletee() { if (front<1) cout<<"\nQueue underflow”; else cout<<"\nDeleted element: “<rear) front=rear=0; ) void peep(int) ;//function prototype void update (int, int) ;//function prototype void display();//function prototype boolean empty() ( return ( (front==0) ?truet false) ; : i //function definition peep() void queue: :peep(int level) a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book TREES 495 Enter y/Y for entering node or n/N for quitting y Enter the info : 30 The tree is : 50 40 30 Enter y/Y for entering node or n/N for quitting Enter the info : 60 The tree is : 60 40 30 Enter y/Y for entering node or n/N for quitting y Enter the info : 55 The tree is : 60 55 50 40 30 Enter y/¥ for entering node or n/N for quitting | | i | a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 522 MASTERING C++ PROGRAMS Enter the number to be inserted : 80 Binary Tree Operations (using stacks) 1, Insert a node in the tree 2, Delete a node from the tree 3, Find depth of the tree 4. Traverse the tree 5, Search a node in the tree 6. Find the number of nodes in the tree 0. Exit Enter your choice : 3 Depth of the tree is : 3 Binary Tree Operations (using stacks) Insert a node in the tree Delete a node from the tree Find depth of the tree Traverse the tree Search a node in the tree Find the number of nodes in the tree Exit SrAseypr Enter your choice : 4 Tree Traversal 1. Preorder traversing 2. Inorder traversing 3. Postorder traversing 0. Mainmenu Enter your choice : 2 35 40 50 60 80 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 528, MASTERING C++ PROGRAMS ) ) // function definition display() void graph :: display() { cout<<\nThe adjacency matrix is :\n"; for (i=0; i>vertexl>>vertex2; adj [vertex1] [vertex2]=TRUE; ) // function definition deletion() void graph :: deletion() t cout<<“Enter vertex no’s 0 - “<>vertexl>>vertex2; adj (vertex1] [vertex2]=FALSE; ) // function definition adjacent () int graph :: adjacent () { cout<<“Enter vertex no’s 0 - “<>vertexl>>vertex2; b void main() { graph obj; // object declared for class graph int choice; elrser( obj.initialize(); obj.entex(); obj.display(); a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book MASTERING C++ PROGRAMS: c edge ‘current; nod [index] . visit=TRUE; nod[index}.path_len= *dfsn; * dfsn +=1 for (current=nod [index] .ptr; current ;current=current->next) { if (nod{current->dest ination] .visit==FALSE) search (current->dest ination, dfsn, nod) 7 , void main() { graph_search obj; // object declared for class graph_search int i,n,index,dfsn; //index denotes starting node for traversal //dfsn denotes depth first search number int a{SIZE] [SIZE]; node nod{SIZE}: edge ‘nodeptr; elrser(); cout<<"Enter no of nodes (vertices) in the graph <="<>n; dfsne0; // depth first search number initialized to 0 // before the adjacency list structure is created obj.enter(n,a); obj.displayin,a); cout<<"\nPress any key to continue\n”; getch(); elrser(); ‘obj. nodetable(n,a,nod) ; cout<<™\nEnter the starting node no 0 to “<>index; obj. search (index, édfsn, nod) ; cout<<"The length of the path from node : “<next) putch( nodeptr->destinationt’A’ ); cout<data; prev=first; first=first->next; delete (prev); return (first); , void main() { graph_search obj; // object declared for class graph_search int i,n,index; //index denotes starting node for traversal int a(SIZE] (SIZE); node nod(SIZE] + edge *nodeptr; elrser(); cout<<“Enter no of nodes (vertices) in the graph <="<>n; obj.enter(n,a): obj.display(n,a); cout<<*\nPress any key to continue\n"; getch(); elrser()i obj.nodetable(n,a,nod) ; cout<<“\nEnter the starting node no 0 to “<>index; obj .search (index, nod) ; cout<<"The length of the path from node : “<next) putch( nodeptr->destinationt/A’ ); a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 544 MASTERING C++ PROGRAMS // To find the shortest path between two vertic // Using WARSHALL’s modified algorithm (nodes) #include #include #include//for setw() f#idefine SIZE i0 define INFINITY 999 // INFINITY indicates no edge between the nodes class graph ( private : int adj (SIZE) (S12E}; int c{SIZE) (SIZE];//stores the minimum length of the paths //petween nodes int i,j,k»ng public : void enter (void); //function prototype void minimal (void) void display (void); Me //function definition enter() void graph enter (void) { //enter the data cout<<"Enter the no of vertices <= “<>n; cout<<"\nEnter the adjacency matrix of order “>adj [i} (3]7 ’ //echo the data cout<<"\nThe adjacency matrix is :\n\n"; for (i=0; i #include fdefine SIZE 11 #define INFINITY 999 // INFINITY indicates no edge between the nodes #define PERMANENT 1 fdefine TENTATIVE 0 struct nodelabel { int pred; int len; int flag; he class graph ( private int travel_path[SIZE]; nodelabel state(SIZ#); int i,j,count,minimum, k; public : void enter(int,int mat (SIZE) {SIZ£]); //function prototype void display(int, int mat [SIZE] (SIZE]); int minimal (int mat {SIZE] [SIZE], int, int,int,int path[SIZ£),int *); ii //function definition enter () void graph :: enter{int maxnodes, int mat {SIZE} [SIZE]) { /fenter the data cout<<"\nEnter the adjacency matrix of order “ <>mat [i] [j]: , // function definition display() void graph :: display(int maxnodes, int mat [SIZE] [SIZE]) { a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book 552 MASTERING C++ PROGRAMS // To find all pair shortest path matrix from a weighted matrix // Using FLYOD’s algorithm #include #include #include for setw() define SIZE 10 define INFINITY 999 // INFINITY indicates no edge between the nodes class graph { private : int i,5,ki public : void enter(int, int mat [SIZE] {SIZE]); //function prototype void display (int, int mat (SIZE) [SIZE]); void flyod{int,int mat [SIZE] [SIZE], int res{SIZE) (SIZE)); he //function definition enter() void graph :: enter(int maxnodes, int mat [SIZE] [SIZE]) { //enter the data cout<<™\nEnter the adjacency matrix of order * <omat (iJ 4]; ) // function definition display() void graph :: display(int maxnodes, int mat {SIZE} (SIZE]) { for (i=0; i #include define size 20 class array { private : int i; float a{size]; public : void enter(int); void display(int); int binary _search(int, float}; // for searching of element be // definition of the function enter() void array :: enter(int n) ( for (i=0;i>a[i]; , // definition of the function display() void array :: display(int n) { for (i=0;ic #include fdefine size 20 class array { private : int i; float a[size]; public : void enter (int); void display(int); void bubble_sort (int); // for sorting of elements he // definition of the function enter() void array :: enter(int n) { for (i=O;isn;it+) cin>>alil; I // definition of the function display() void array { display(int n) for (imO;i #include fdefine size 32 // heap of upto 31 elements can be stored as index of array starts from 1 class array { private: int i,j,k; public : void enter(float *,int); void display(float * , int); void cr_heap(float *, int); void heap_sort (float *,int); ie // definition of the function enter() void array { enter (float arr(],int n) for (i=l;icen;i++) cin>>arr li}; ) // definition of the function display() void array display(float arr{j,int a) for(i=l;i<=n; i++) cout<9) goto backl: back2: gotoxy (gotox+1, gotoy) ; cout<<* '; gotoxy (gotox+1, gotoy) ; num2=getche () 7 if (num2!=13) { num2-=48; if(num2<0 |} num2>9) goto back2; a[temp1] [temp2]=num1*10+num2; } else a(temp1] [temp2)-numi; }//outermost if statement ends here else a{temp1} (temp2)=100; 1//temp2 for loop fox (temp1=0; tempi<=60;temp1++) i gotoxy (14+templ, 3); textbackground(bekgnd) ; textcolor (14); puteh (char (255) )+ : endrow=gotoy/endclm=gotox; gotoxy (endelm, endrow) ; textcolor (226); putch (char (2)) gotoxy (endelm, endrow) ; cursorx=endrow, cursory=endclm; int m=row;int n=clm; ‘int usrow;int v=clm; char mi="e' while (ml==’e") 4 get (urv); while(u==row+l || ve=clm+1 || u==0 || v==0) 591 a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book APPENDIX: 595: Category What it does ? 10. Bitwise XOR nt Bitwise oR a2. Logical AND 13. Logical OR 14. Conditional (a? x y means “if a then x, else y“) 15. Assignment 16. Comma Simple assignment Assign product Assign quotient Assign remainder (modulus) Assign sum Assign difference Assign bitwise AND Assign bitwise XxOR Assign bitwise OR Assign left shift Assign right shift Evaluate The following operators cannot be overloaded : C++ direct component selectors C++ dereference C++ scope access/resolution Conditional a You have elther reached a page that is unavailable for viewing or reached your viewing lil far this book De l| | a eh ee eee

You might also like