├── .gitignore.txt ├── AbstractClass.cpp ├── BaseMemberMethodusingObjectAsArg.cpp ├── Bit Manipulation ├── CountBitsToFlipToconvertAtoB.cpp ├── CountConsecutiveOnes.cpp └── PowerOf2.cpp ├── C++ iostreams ├── IOmanipulators.cpp ├── SetandUnsetFlags.cpp ├── StringStream.cpp ├── boolalphaFlag.cpp ├── makingCustomManipulatorFunctions.cpp └── precisionAndFillwidthMethods.cpp ├── C-practice ├── BinarySearch.c ├── Bitwise operators │ ├── BitwiseOps.c │ └── binaryConv.c ├── C library functions │ └── LibFunc.c ├── Complex Declarations │ ├── Union.c │ ├── complex.c │ └── complex2.c ├── Const keyword │ └── const.c ├── Control Flow │ └── ControlFlow.c ├── Declarations and initializations │ └── Declaration.cpp ├── Experimenting.c ├── Func1.c ├── Input and Output │ └── IO.c ├── Memory allocation │ ├── Calloc.c │ ├── Malloc.c │ └── Realloc.c ├── MergeSort.c ├── Miscellaneous │ ├── CallByValue.c │ ├── CallingMain.c │ ├── FuncCalls.c │ ├── PointerAirthmetic.c │ └── ReverseRecursive.c ├── Pointers │ └── pointer.c ├── PrimeNumber.c ├── QueueLLC.cpp ├── QuickSort.c ├── Struct Unions and Enums │ └── struct.c └── Variable arguments │ └── Stdarg.c ├── COPY CONSTRUCTOR ├── CopyConstructor2.cpp └── copy_constructor.cpp ├── COPY CONSTRUCTOR2.cpp ├── ClassesInsideFunctions.cpp ├── ConstFunctions.cpp ├── ConstKeyword.cpp ├── ConstPointers.cpp ├── Data Structures ├── Arrays │ ├── HourGlass.cpp │ ├── arrBasic.cpp │ └── arrBasic.exe ├── LinkedLists │ ├── Checking Palindrome List.cpp │ ├── CircularLists │ │ └── CircularLL.cpp │ ├── Doubly Linked List │ │ └── ReverseDLL.cpp │ ├── DoublyLinkedList.cpp │ ├── Merge2LLSorted.cpp │ ├── MergePointofLL.cpp │ ├── MiddleItemInList.cpp │ ├── RemoveCycleLinkedList.cpp │ └── Singly_LL.cpp ├── Queues │ ├── QueueArray.cpp │ ├── QueueCheckConsecutivePair.cpp │ ├── QueueInterleaving.cpp │ ├── QueueLinkedList.cpp │ ├── QueueUsing1Stack(Recursion).cpp │ ├── QueueUsing2Stacks.cpp │ ├── ReverseKItemsQueue.cpp │ ├── ReversingQueueUsingStack.cpp │ └── circularArrayQueue.cpp ├── SORTING │ ├── CountingSort.cpp │ ├── HeapSort.cpp │ ├── MergeSort,cpp.cpp │ ├── MergeSortLinkedList.cpp │ ├── QuickSort.cpp │ ├── bubbleSort.cpp │ ├── bubbleSort.exe │ ├── selectionSort.cpp │ └── selectionSort.exe ├── Searching │ ├── BinarySearch.cpp │ ├── FindingOccurenceinSortedArrayUsingBS.cpp │ ├── LinearSearch.cpp │ └── OccurenceInArrayUsingBinarySearch.cpp ├── Stacks │ ├── InfixToPostfix.cpp │ ├── InfixToPrefix.cpp │ ├── KStacksUsingArray.c │ ├── PostfixEval.cpp │ ├── PrefixEvaluation.cpp │ ├── StackUsing2Queues.cpp │ ├── balancedParenthesisusingStack.cpp │ ├── reverseStringUsingStack.cpp │ ├── stack.cpp │ ├── stackSimplified.cpp │ └── stack_linkedList.cpp └── Trees │ ├── AVL Trees │ ├── CheckIfBSTisAVL.cpp │ ├── CountInRange.cpp │ ├── DoubleLeftRightRotation.cpp │ ├── DoubleRightLeftRotation.cpp │ ├── FullHeightBalancedTree.cpp │ ├── InsertionInAVL.cpp │ ├── MinimalAVLTree.cpp │ ├── NumMinimalAVLTreesPossible.cpp │ ├── SingleLLRotation.cpp │ └── SingleRRrotation.cpp │ ├── BST │ ├── ArrayToBST.cpp │ ├── BSTfromPreorder.cpp │ ├── BSTorNot.cpp │ ├── BSTwithNkeys.cpp │ ├── BinaryTreeToBST.cpp │ ├── BinaryTreeToBSTUsingSets.cpp │ ├── Check2BSTareSameOrNot.cpp │ ├── ClosestNode.cpp │ ├── DLLtoBST.cpp │ ├── DeadEndOrNot.cpp │ ├── DeleteNode.cpp │ ├── Distance.cpp │ ├── FindParent.cpp │ ├── FloorAndCeiling.cpp │ ├── InorderPredecessorSuccessor.cpp │ ├── InorderSuccessor.cpp │ ├── InsertNode.cpp │ ├── KthLargestBST.cpp │ ├── KthLargestUsingMorrisTraversal.cpp │ ├── KthSmallestInBST.cpp │ ├── KthSmallestUsingMorrisTraversal.cpp │ ├── LinkedListToBST.cpp │ ├── MinNode.cpp │ ├── PostOrderToBST.cpp │ ├── PrinInRange.cpp │ ├── PrintAncestors.cpp │ ├── SmallestNumberInBSTGreaterThanN.cpp │ ├── SumKLargestInBST.cpp │ ├── SumOfNodesInRange.cpp │ ├── Top3PrintInBST.cpp │ ├── lowestCommonAncestor.cpp │ ├── maxNode.cpp │ └── searchNode.cpp │ ├── Binary Trees │ ├── BinrayTree.cpp │ ├── BottomView.cpp │ ├── BoundaryTraversal.cpp │ ├── CountofNode.cpp │ ├── DeepestLeftLeafNode.cpp │ ├── DeepestNodeInTree.cpp │ ├── DeleteNodeInTree.cpp │ ├── DeleteTreePostorder.cpp │ ├── DepthOrLevelOfNode.cpp │ ├── DiameterOfTree.cpp │ ├── DistanceBetweenNodes.cpp │ ├── FillingNextSiblings.cpp │ ├── FindMaxInTree.cpp │ ├── HorizontalDistance.cpp │ ├── InorderSuccessorOfaNode.cpp │ ├── InorderTraversalofThreadedTree.cpp │ ├── InsertNodeInTree.cpp │ ├── LeastCommonAncestor.cpp │ ├── LevelOrderChangedPath.cpp │ ├── LevelOrderLineByLine.cpp │ ├── MirrorTree.cpp │ ├── MirrorTreesOrNot.cpp │ ├── MorrisInorderTraversal.cpp │ ├── MorrisPreorderTraversal.cpp │ ├── NoLeafNodesInTree.cpp │ ├── NoOfFullNodes.cpp │ ├── NoOfHalfNodes.cpp │ ├── NthPreorder.cpp │ ├── ParentofANode.cpp │ ├── PrintAncestors.cpp │ ├── PrintDeepestPath.cpp │ ├── ReverseInorderForThreadedTree.cpp │ ├── ReverseInorderUsingMorrisTraversal.cpp │ ├── ReverseLevelOrder.cpp │ ├── RightView.cpp │ ├── SearchNodeInTree.cpp │ ├── SimilarlTreesOrNot.cpp │ ├── SmallestNodeAtEachLevel.cpp │ ├── SpiralTraversal.cpp │ ├── SumOfHeightsOfEachNode.cpp │ ├── SumofNodes.cpp │ ├── SwapLeftRight.cpp │ ├── TraverseLevelWise(BFS).cpp │ ├── VerticalSumMap.cpp │ ├── ZigZagTraversal.cpp │ └── heightofTree.cpp │ ├── Generic N-Ary Trees │ ├── NumChildren.cpp │ ├── NumSiblings.cpp │ └── SumNodes.cpp │ ├── Generic N-ary Trees │ └── NumWaysOfTraversal.cpp │ ├── STL and Trees │ ├── DiagonalTraversal.cpp │ ├── LargestNodeAtEachLevelInBinaryTree.cpp │ ├── NodeAndItsNextSiblingInMap.cpp │ ├── SortedLevelPrintInBinaryTree.cpp │ ├── StoreLevelAndSumofNodesAtLevelInMap.cpp │ ├── StoreLevelOfEachNodeInMap.cpp │ ├── SumOfNodesAtEachDiagonal.cpp │ ├── TopViewUsingMaps.cpp │ ├── VerticalOrderTraversal.cpp │ └── VerticalOrderTraversalUsingLeveleOrder.cpp │ └── Threaded Binary Trees │ ├── ConvertBinaryTreeToPredecessorThreadedTree.cpp │ ├── ConvertBinaryTreeToThreadedTree.cpp │ └── ReverseInorderForThreadedTree.cpp ├── Dynamic Programming ├── CatalanNumber.cpp ├── EquivalentSubarrays.cpp ├── Exponentiation.cpp ├── LongestCommonSubsequence.cpp ├── LongestPalindromicSubstring.cpp ├── LongestRepeatedSubstring.cpp ├── LongestRepeatingSubsequence.cpp ├── LongestSubstring.cpp ├── MaxProductSubarray.cpp ├── MaxSubarraySumWithout2contigiousItems.cpp ├── MaxSumSubarray,cpp.cpp ├── MaximumInMinimumWindow.cpp ├── ModularExponentiation.cpp ├── PrintLPS.cpp ├── PrintingTheLCS.cpp ├── Recursion and Memoization │ ├── FactorialDp.cpp │ └── FibonacciMemoization.cpp ├── SpecialSubsequence.cpp ├── StartEndIndexOfSubarraySumEqualsK.cpp ├── UglyNumbers.cpp ├── longestPalindromicSubsequence.cpp └── maxSumSubarrayWhoseSizeisK.cpp ├── Exception Handling ├── FunctonsThrowingExceptions.cpp ├── Multiple Catch Blocks.cpp ├── NestedTry-Catch.cpp ├── TryCatchBasic.cpp └── UserDefinedCustomExceptions.cpp ├── File Handling ├── AppendData.cpp ├── BinaryFiles.cpp ├── FileStreams.cpp ├── ReadAndWriteBinaryFile.cpp ├── ReadingData.cpp └── WritingDatatoFile.cpp ├── FriendFunction.cpp ├── FunctionOverloading.cpp ├── FunctionOverridingInheritence.cpp ├── General Programs ├── ABCDPyramid.cpp ├── ArrayRotation.cpp ├── AutomorphicNumber.cpp ├── BinomialCoefficient.cpp ├── BonacciNumbers.cpp ├── CallByValueAndRef.cpp ├── CeilAndFloorInArray.cpp ├── CeilingAndFloorInUnsortedArray.cpp ├── CheckAnagrams.cpp ├── CheckDigits.cpp ├── FactorialRecursive.cpp ├── Fibonacci.cpp ├── FindingBinary.cpp ├── FindingLargestUsingRecursion.cpp ├── GCD.cpp ├── Gen1.cpp ├── HowtoFindType.cpp ├── LCM.cpp ├── LeapYear.cpp ├── MedianDifference.cpp ├── MedianInUnionOfLists.cpp ├── MinMaxInArray.cpp ├── MultiplyBy2usingleftshift.c ├── NeonNumber.cpp ├── Oddoreven.c ├── Palindrome2.cpp ├── PerfectNumber.cpp ├── PointerToManipulateValue.cpp ├── PrimeNo.cpp ├── PrimeNoRecursive.cpp ├── RangeQuery.cpp ├── RemoveItemFromArray.cpp ├── ReversePrimeNo.cpp ├── ReverseStringRecursive.cpp ├── ReverseVowels.cpp ├── ReverseWordsOfSentence.cpp ├── SetBits.cpp ├── ShuffleArray.cpp ├── SizesofDatatypes.cpp ├── SizesofPrimitiveDataTypes.cpp ├── SortingString.cpp ├── StaticVar.cpp ├── SubArraySumEqualsK.cpp ├── SubStringFromString.cpp ├── TaylorSeries.cpp ├── VowelsorNotusingPointer.cpp ├── XORoperations.cpp ├── matrixTranspose.cpp ├── palindrome.cpp ├── reversingString.cpp └── sizeofVarWithoutUsingSizeof.cpp ├── Generic Programming ├── ExplicitSpecialization.cpp ├── ExplicitSpecializationGenericClass.cpp ├── GenericClass.cpp ├── GenericClassDefaultArguments.cpp ├── GenericFunctions.cpp ├── OverloadingGenericFunction.cpp └── TemplatesAndStaticVar.cpp ├── LICENSE ├── NAMESPACES in C++ ├── InlineNamespaces.cpp ├── NestedNamespaces.cpp ├── Un-namedNamesapces.cpp ├── multipleNamespacesInFile.cpp └── namespace.cpp ├── NestedClasses.cpp ├── OOP-2.cpp ├── Operator Overloading ├── FriendOperatorOverloading.cpp ├── IncDecOptOverloading-POSTFIX.cpp ├── IncDecOptOverloading.cpp ├── OperatorOverloading1.cpp ├── OperatorOverloadingInheritence.cpp ├── Overloading()operator.cpp ├── Overloading=operator.cpp ├── OverloadingArraySubscriptOperator.cpp ├── OverloadingFunctionCallOpt.cpp ├── OverloadingNewAndDelete.cpp ├── OverloadingStreamInputandOutputOpt.cpp └── overloadingArrowoperator.cpp ├── OperatorOverloading1.cpp ├── OrderOfExecOfConstructorsDestructorsInheritence.cpp ├── Pointers ├── DoublePointer.cpp ├── Pointer2.cpp ├── PointerToPointer.cpp ├── PointersAnd2-Darrays.cpp ├── TypecastingInPointers.cpp ├── VoidPointer.cpp ├── addressofArrayPointer.cpp ├── pointer.cpp ├── pointerIntro.cpp └── sizeofVarWithoutUsingSizeof.cpp ├── PreProcessors in CPP ├── ConditionCompilationMacros.cpp ├── FunctionLikeMacro.cpp ├── LinePreprocessor.cpp ├── ObjectLikeMacro.cpp ├── ifdefAndifndefMacro.cpp └── includeUserDefinedSourceFiles.cpp ├── PrivateInheritence.cpp ├── README.md ├── REFERENCES in C++ ├── ChangesInReferredVar.cpp ├── FactsAboutReferences.cpp ├── LvalueFunction.cpp └── Referenc1.cpp ├── STL ├── map.cpp ├── templateFunc.cpp └── vector.cpp ├── StaticClass.cpp ├── StaticVar.cpp ├── ThisPointer.cpp ├── VirtualDestructor.cpp ├── VirtualFuncInheritence.cpp ├── VirtualFunctions.cpp ├── VirtualInheritenceAndDiamondProblem.cpp ├── basic.cpp ├── basic.exe ├── classBasic.cpp ├── constClass.cpp ├── constructorOverloading.cpp ├── constructors.cpp ├── constructors.exe ├── defaultConstructor.cpp ├── destructor.cpp ├── friendClass.cpp ├── memoryDeallocationusingDestructor.cpp ├── multipleInheritence.cpp ├── protectedInheritence.cpp ├── publicInheritence.cpp └── this Pointer ├── ClassAndThis.cpp └── DeleteThis.cpp /.gitignore.txt: -------------------------------------------------------------------------------- 1 | *.exe 2 | -------------------------------------------------------------------------------- /AbstractClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | //Pure virtual functions are virtual funcions which have no defination or implementation in base class. 5 | //but those pure virtual functions are overridden(re-defined) in the derived class 6 | //Abstract Class- A class which has one or more pure virtual functions. A abstract class can have no object 7 | 8 | using namespace std; 9 | 10 | class Person { 11 | public: 12 | virtual void intro() = 0; //defination of a pure virtual function which has no defination in base class 13 | }; 14 | 15 | 16 | //pure virtual function can also be defined outside a base class using a scope resolution operator 17 | void Person :: intro() { 18 | cout<<"Hi this is a person"<intro(); 34 | 35 | } 36 | 37 | int main() { 38 | // Person p; absatract classes cannot have objects 39 | Anish a; 40 | a.intro(); 41 | getIntro(&a); 42 | a.Person::intro(); //accessing the base class intro() function, though it is a pure virtual function 43 | 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /BaseMemberMethodusingObjectAsArg.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Person { 6 | public: 7 | 8 | void getname() { 9 | cout<<"Hi I am Anish"<getname(); 19 | } 20 | 21 | 22 | int main() { 23 | Person p; 24 | printName(p); 25 | } 26 | -------------------------------------------------------------------------------- /Bit Manipulation/CountBitsToFlipToconvertAtoB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | //count number of bits to be flipped in a to convert it to b 7 | int CountFlip(int a ,int b) 8 | { 9 | int XOR = a^b; //XOR of a and b will be 1 whereever a and b bits are different 10 | 11 | 12 | int count= 0 ; 13 | while(XOR) 14 | { 15 | //counting number of set bits which is equal to number of bits to flip in a 16 | if(XOR & 1) count++; 17 | XOR /= 2; 18 | 19 | 20 | } 21 | 22 | return count; 23 | } 24 | 25 | int main() 26 | { 27 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | /*Program to count number of consecutive ones using left shifting the number until it becomes 0 7 | */ 8 | 9 | int countConsecutiveOnes(int n){ 10 | 11 | int count=0; 12 | while(n) 13 | { 14 | n &= n << 1; 15 | count++; 16 | } 17 | 18 | return count; 19 | } 20 | 21 | 22 | int main() 23 | { 24 | cout< 2 | 3 | using namespace std; 4 | 5 | //program to check if an integer is power of 2 6 | 7 | int powerof2(int n) 8 | { 9 | //we know that all powers of 2 have only 1 bit set, all other bits 0 10 | //so we check the count of set bits, if it equals 1, then it is a power of 2 11 | if(__builtin_popcount(n)==1) 12 | return true; 13 | 14 | else return false; 15 | } 16 | 17 | int powerofTwo(int n) 18 | { 19 | if(n==1) return 0; 20 | 21 | return ((n & n-1)==0) ; 22 | 23 | } 24 | /*In the above method if n is a power of 2 , then n-1 will have all the bits set from lSB to the set bit of n, as every power 25 | of 2 has only 1 set bit. And when we do n & n-1 , if it is 0 then n is a power of 2 26 | */ 27 | 28 | 29 | int main() 30 | { 31 | 32 | cout< 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | /*Program to demonstrate various manipulators of input and output streams 8 | Most general use of manipulator to manipulate or modify output stream is endl 9 | Other examples include hex,oct,dec, setw(),setfill() , setprecision() etc 10 | */ 11 | 12 | int main() 13 | { 14 | 15 | cout<< setw(10) << setfill('#') << setprecision(4) << oct << 100.3344; 16 | return 0; 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /C++ iostreams/SetandUnsetFlags.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /*2 ways of setting flags - 6 | all the flags are members of ios class 7 | 1) using setf() function and adding flag as arguent to it. 8 | 2) directly placing flag inside cin or cout streams - cin >> flag or cout << flag 9 | */ 10 | 11 | 12 | int main() 13 | { 14 | cout.setf(ios::showpos | ios::showpoint); 15 | 16 | cout< 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | //program to demonstrate the usage of string stream class in CPP to convert any type of stream to a string stream and vice versa 8 | 9 | 10 | int main() 11 | { 12 | 13 | 14 | int input; 15 | cin >>input; 16 | 17 | stringstream sobj; 18 | 19 | 20 | sobj << input; 21 | string input_String; 22 | sobj >> input_String; 23 | 24 | 25 | cout<> my_age; 42 | 43 | cout<<"my age in integer form is "< 2 | 3 | using namespace std; 4 | 5 | 6 | //using boolalpha flag to output true ot false if input is true or false 7 | //Boolean values can be input/output using the words "true" and "false". 8 | 9 | int main() 10 | { 11 | bool boolval; 12 | cin.setf(ios::boolalpha); 13 | 14 | cout.setf(ios::boolalpha); 15 | 16 | cin>>boolval; //if input is true - output true 17 | cout< 2 | #include 3 | 4 | /*program to demonstrate how to build custom manipulator functions 5 | a) these functions can be of 2 types - one with a parameter like setw(),setprecision() etc 6 | b) other manipulator methods can be without any parameter like hex, dec , endl 7 | 8 | NOTE- 9 | Manipulator functions should return either reference to ostream class object os istream class and should take a default argument which is passed by reference of type 10 | ostream or istream class like demonstrated below 11 | */ 12 | using namespace std; 13 | 14 | 15 | ostream& print(ostream &output) 16 | { 17 | output<<"Hex value is:" << hex ; 18 | // output<<"Octal value is: "<< oct<>input>>x; 42 | 43 | 44 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | /*Program to demonstarte the use of precision(),width(),fill() methods belonging to ios class 7 | 1) precision() method can be used to print/display only particular sequence on a floating point number, cannot work on normal integers 8 | */ 9 | 10 | int main() 11 | { 12 | cout.precision(4); //precision 13 | cout<<122.112< 2 | #include 3 | 4 | 5 | //program to do binary search in c-recursive implementation 6 | 7 | //selection sort has minimum number of swaps 8 | 9 | void Swap(int *a,int *b) 10 | { 11 | 12 | int temp = *a; 13 | *a = *b; 14 | *b = temp; 15 | 16 | 17 | } 18 | 19 | 20 | void SelectionSort(int *arr, int size) 21 | { 22 | 23 | for(int i = 0; i < size;i++) 24 | { 25 | int min = i; 26 | 27 | for(int j = i+1 ; j=data) 56 | return BinarySearch(arr,data,low,mid-1); 57 | else 58 | return BinarySearch(arr,data,mid+1,high); 59 | 60 | } 61 | 62 | else 63 | return -1; 64 | } 65 | 66 | int main() 67 | { 68 | int arr[] = {50,40,10,20,30}; 69 | 70 | int size = sizeof(arr)/sizeof(arr[1]); 71 | 72 | SelectionSort(arr,size); 73 | printf("\n"); 74 | 75 | 76 | 77 | printf("%d",BinarySearch(arr,10,0,size)); 78 | } 79 | -------------------------------------------------------------------------------- /C-practice/Bitwise operators/BitwiseOps.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | //BITWISE OPERATORS AND OPERATIONS 5 | 6 | int main() 7 | { 8 | int x = 4; 9 | printf("%x ",(x << 1) >> 2); 10 | printf("%x",-1>>4);//ffffffff is output 11 | } 12 | -------------------------------------------------------------------------------- /C-practice/Bitwise operators/binaryConv.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | //program to convert a number to its binary equivalent 5 | 6 | int main() 7 | { 8 | unsigned int num; 9 | int i; 10 | scanf("%u",&num); 11 | for(i=0;i<16;i++) 12 | { 13 | printf("%d",(num< 2 | #include 3 | 4 | 5 | 6 | //Important C library functions 7 | 8 | int main() 9 | { 10 | // int i; 11 | // 12 | // i = printf("How are you ?\n"); 13 | // i = printf("%d\n",i);//prints 14 i.e the length of the above char sequence 14 | // printf("%d\n",i); //prints length of the above seq i.e 3 15 | 16 | 17 | int c = scanf("%d %d %s"); 18 | printf("%d",c);//will print 3, ie the number of inputs 19 | 20 | 21 | 22 | return 0; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /C-practice/Complex Declarations/Union.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | union n { 4 | int age; 5 | int sal; 6 | 7 | }; 8 | int main(){ 9 | 10 | union n n1={10,250}; 11 | //error as when defining a union variable, we can only initialize one member 12 | 13 | printf("%d",n1.age); 14 | } 15 | -------------------------------------------------------------------------------- /C-practice/Complex Declarations/complex.c: -------------------------------------------------------------------------------- 1 | //Complext declarations in C 2 | #include 3 | 4 | double i; 5 | 6 | int main() 7 | { 8 | 9 | (char)(float)(int)i; 10 | printf("%d\n",sizeof(i));//prints size of a double 11 | 12 | 13 | //but here it prints the size of a long double as i becomes a long double, and sizeof() operator has right to left associativity 14 | //so left most is evaluated at last i.e long double 15 | printf("%d",sizeof((long double)(double)(char)(int)(float)i)); //prints 16 16 | 17 | 18 | //program 2 19 | 20 | 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /C-practice/Complex Declarations/complex2.c: -------------------------------------------------------------------------------- 1 | //Complext declarations in C 2 | #include 3 | 4 | typedef void v; 5 | 6 | typedef int i; 7 | 8 | int main() 9 | { 10 | 11 | v fun(i,i); 12 | 13 | fun(4,3); 14 | 15 | return 0; 16 | 17 | 18 | } 19 | 20 | 21 | //v fun(i a,i b) 22 | //{ 23 | // 24 | // i s = 3; //here i is the type int 25 | // float i;//i is a variable here 26 | // printf("%d\n",sizeof(i)); //prints size of a float i 27 | // 28 | // printf("%d",a*b*s); 29 | //} 30 | -------------------------------------------------------------------------------- /C-practice/Const keyword/const.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main() 5 | { 6 | union name { 7 | 8 | int age; 9 | }; 10 | 11 | const union name n; 12 | //n.age=20; age becomes a read only const object 13 | printf("%d",n.age); 14 | 15 | } 16 | 17 | -------------------------------------------------------------------------------- /C-practice/Declarations and initializations/Declaration.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | int a = 20; //a defined before the main function and its usage in main(), not need to declare it 6 | int main() 7 | { 8 | 9 | printf("%d",a); //prints 20 10 | printf("%d",b); //error - b not declared, need to use extern b and declare b; 11 | return 0; 12 | } 13 | 14 | int b =10;//b is used frirst in the main function and then it is defiend afterwards, error 15 | 16 | -------------------------------------------------------------------------------- /C-practice/Experimenting.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | //union u { 6 | // 7 | // int a; 8 | // char c; 9 | // double d; 10 | //}; //size of union prints the maximum size of the data member inside it 11 | // 12 | //struct s{ 13 | // int b; 14 | // char d; 15 | // double f; 16 | //}; 17 | // 18 | int main() 19 | { 20 | 21 | 22 | char c[] = ""; 23 | 24 | printf("%d",sizeof(c)); //size is 2 bytes-1 for char and 1 for NUll character 25 | 26 | float f = 2.650098; 27 | 28 | printf("%.4f",f); 29 | } 30 | 31 | 32 | //union u u1; 33 | //struct s s1; 34 | // 35 | //printf("%d",sizeof(u1)); //prints 8 i.e max size is of double in union 36 | //printf("\n"); 37 | // 38 | //printf("%d",sizeof(s1));//prints 16 39 | //printf("\n"); 40 | // 41 | // 42 | //int arr[10] = {1,2,3,4,5,6,7}; 43 | // 44 | //for(int i=0;i 2 | #include 3 | #include 4 | 5 | 6 | 7 | int main() 8 | { 9 | 10 | // FILE *fp = fopen("a.txt","r");//open the file in write mode 11 | // 12 | // 13 | // char ch[10]; 14 | // fseek(fp,-5L,SEEK_END); 15 | // fgets(ch,5,fp);//ie store 4 items from the 6 digit in file a.txt 16 | // 17 | // /*It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, 18 | // whichever comes first 19 | // */ 20 | // puts(ch); 21 | 22 | //program2 23 | int n; 24 | scanf("%*d",&n);//* symbol after * means. current input is scanned but not stored 25 | printf("%*d",n,n);//will print only 2 ,* after % in printf() means field width 26 | 27 | return 0; 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /C-practice/Memory allocation/Calloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int *p,*q; 7 | p = (int*)calloc(20,sizeof(char)); 8 | //calloc takes 2 args - no of elements, size of each item. It also sets the values to 0 automatically. 9 | 10 | q=(int*)malloc(20); 11 | 12 | printf("%d\n",p[3]);//prints 0 13 | printf("%d\n",q[3]); 14 | } 15 | -------------------------------------------------------------------------------- /C-practice/Memory allocation/Malloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int *p; 7 | p = (int*)malloc(20); 8 | 9 | printf("%u\n",p);//prints some add a 10 | free(p); 11 | printf("%u",p);//prints the same address 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /C-practice/Memory allocation/Realloc.c: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /C-practice/Miscellaneous/CallByValue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | //call by value and call by reference 6 | 7 | int main() 8 | { 9 | int fun(int* ); 10 | int fun1(int* ); 11 | 12 | int i = 3; 13 | 14 | fun(&i); 15 | 16 | printf("%d\t",i); 17 | 18 | fun1(&i); 19 | 20 | printf("%d\t",i); 21 | //no changes will be made to i, it will remain 3 22 | 23 | } 24 | 25 | 26 | int fun(int *i) 27 | { 28 | *i = (*i + 1); 29 | printf("%d\t",*i); 30 | } 31 | 32 | int fun1(int *j) 33 | { 34 | *j = (*j + 1); 35 | printf("%d\t",*j); 36 | } 37 | -------------------------------------------------------------------------------- /C-practice/Miscellaneous/CallingMain.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | int fun(int(*)()); 6 | 7 | int main() 8 | { 9 | 10 | fun(main); 11 | printf("Hi\n"); 12 | return 0; 13 | 14 | } 15 | 16 | //function takes an integer pointer as an argument 17 | int fun(int(*p)()) 18 | { 19 | printf("Hello"); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /C-practice/Miscellaneous/FuncCalls.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int func1(int); 5 | 6 | int main() 7 | { 8 | int k = 35; 9 | func1(k=func1(k=func1(k))); // k becomes 37 10 | // k = func1(k = func1(k = func1(k))); k becomes 38 as the result is stored in k 11 | //k = func1(func1(func1(k))); also outputs 38 12 | 13 | printf("%d",k); 14 | return 0; 15 | } 16 | 17 | int func1(int n) 18 | { 19 | n++; 20 | return n; 21 | } 22 | -------------------------------------------------------------------------------- /C-practice/Miscellaneous/PointerAirthmetic.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | void fun(char**); 6 | 7 | int main() 8 | { 9 | char *arr[] = {"ab","cd","ef","gh"}; 10 | fun(arr); 11 | return 0; 12 | } 13 | 14 | void fun(char **c) 15 | { 16 | char *p; 17 | 18 | p = (c += sizeof(int))[-1]; 19 | 20 | printf("%s",p); 21 | } 22 | -------------------------------------------------------------------------------- /C-practice/Miscellaneous/ReverseRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | int reverse(int n) 6 | { 7 | // if( n > 0) 8 | // { 9 | // printf("%d\n",n); 10 | // 11 | // reverse(--n); 12 | // } 13 | // 14 | 15 | //method2 16 | 17 | if( n < 1) 18 | return 0; 19 | else 20 | printf("%d\n",n); 21 | 22 | n--; 23 | reverse(n); 24 | //but when reverse(--n); 25 | } 26 | 27 | int main() 28 | { 29 | 30 | printf("%u",main); //address of main() is printed 31 | reverse(10); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C-practice/PrimeNumber.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | int Prime(int n,int i) 6 | { 7 | 8 | 9 | // int flag = 1; 10 | // 11 | // if(n==1 || n==0) 12 | // { 13 | // return 0; 14 | // } 15 | // 16 | // for(int i=2; i <= n/2 ; i++) 17 | // { 18 | // if(n%i==0) 19 | // { 20 | // flag = 0; 21 | // 22 | // } 23 | // } 24 | // 25 | // return flag; 26 | 27 | if(i 2 | #include 3 | 4 | //#pragma pack(1) 5 | 6 | //pragma directive indicated that structure should be aligned at address which are multiples of 1 , so all data types begin 7 | //at next immediate address 8 | struct st{ 9 | 10 | double d; 11 | float f;// 8 bytes padded 12 | int data;//4 bytes 13 | char c;// 4 bytes, 3 bytes padded after 1 byte of c 14 | float *fp; // 8bytes 15 | }s; 16 | 17 | 18 | //struct bits{ 19 | // 20 | // long int a : 1; 21 | //}bit; 22 | 23 | 24 | //union u { 25 | // 26 | // double d; 27 | // char a; 28 | // 29 | //} ut; 30 | 31 | 32 | 33 | 34 | struct node{ 35 | 36 | int data; 37 | struct node *ptr; 38 | }; 39 | 40 | 41 | struct emp { 42 | char *name; 43 | int age; 44 | float bs; 45 | }; 46 | int main() 47 | { 48 | 49 | // enum e {MON=-10,TUE,WED=10,THU,FRI,SAT,SUN } val; 50 | // printf("%d %d %d %d %d %d %d\n",MON,TUE,WED,THU,FRI,SAT,SUN); 51 | // //prints -10 -9 10 11 12 13 14 52 | // printf("%d\n",sizeof(val)); 53 | // 54 | // printf("%d",sizeof(ut)); 55 | 56 | // union u ut; 57 | // 58 | // ut.a = 10; 59 | // ut.b = 20; 60 | // ut.c = 1002; 61 | 62 | // printf("%d ", ut.a); 63 | 64 | // printf("%d",sizeof(s)); 65 | 66 | // printf("%d",sizeof(bit)); 67 | 68 | 69 | struct node *p = (struct node*)malloc(sizeof(struct node)); 70 | struct node *q = (struct node*)malloc(sizeof(struct node)); 71 | 72 | printf("%d %d",sizeof(p),sizeof(q)); //will print the size of pointer ie 8 bytes on 64-bit sys 73 | 74 | 75 | struct emp *e=(struct emp*)malloc(sizeof(struct emp)); 76 | struct emp *t = e; 77 | char newname[] = "Anish"; 78 | 79 | 80 | e->name = (char*)malloc(strlen(newname+1)); 81 | strcpy(e->name,newname); 82 | e->age = 25; 83 | 84 | printf("%d %s\n",e->age,e->name); 85 | printf("%d %s",t->age,t->name); 86 | 87 | 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /C-practice/Variable arguments/Stdarg.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | // best example of a function which takes variable arguments is printf() 7 | //the prototype of is is int printf(char const *,...) 8 | void fun(int num,...) 9 | { 10 | va_list ptr;//vah_list is an array which holds the information of the arg list needed by va_arg 11 | va_start(ptr,num); 12 | int c = va_arg(ptr,int); 13 | c = va_arg(ptr,int); 14 | //va_arg used to extract an argument from the args list and 15 | //va_arg used to advance to next argument 16 | // 17 | printf("%d",c); 18 | 19 | 20 | } 21 | 22 | //when dealing with var no of arguments char and unsigned int are promoted to int 23 | //and the float is promoted to double 24 | int main() 25 | { 26 | 27 | fun(20,'A','B','C'); 28 | 29 | 30 | 31 | //prints 66- ascii value of c 32 | return 0; 33 | 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /COPY CONSTRUCTOR/CopyConstructor2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | class Empty { 7 | 8 | int *x; 9 | int y; 10 | public: 11 | Empty() 12 | { 13 | cout<<"Constructor called"< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | class Person{ 8 | 9 | public: 10 | int age; 11 | int *s; 12 | Person(int age,int p) 13 | { 14 | this->age = age; 15 | (this->s) = new int(p); 16 | } 17 | 18 | //copy constructor 19 | Person(const Person &obj) 20 | { 21 | age = obj.age; 22 | s = new int(*obj.s); 23 | 24 | } 25 | 26 | void getdet() 27 | { 28 | cout<<"Age is"<<" : "<age< 2 | 3 | using namespace std; 4 | 5 | //Implementation of Local classes-Classes defined inside a function 6 | 7 | //function prototyping-forward declaration 8 | void getClass(); 9 | 10 | int main(){ 11 | getClass(); 12 | return 0; 13 | 14 | } 15 | 16 | 17 | void getClass() { 18 | class Person { 19 | public: 20 | string name; 21 | int age; 22 | void getdetails() { 23 | 24 | cout<<"Name: "< 2 | 3 | using namespace std; 4 | 5 | // 1) a function can take both its return rype as const , and its arguments as const type 6 | // 2) A function which takes a non-const as argument cannot be called using a const argument, will give error 7 | // 3)But a function which takes a const argument, can be called using both const and non-const arguments. 8 | 9 | int f(const int *x) { 10 | 11 | return *x; 12 | } 13 | 14 | int g(int *x) { 15 | 16 | return *x; 17 | } 18 | 19 | int main() 20 | { 21 | int a=10; 22 | int *x=&a; //non-const pointer 23 | int const *y=&a;//value of y cannot be changed 24 | 25 | 26 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int const x=10; 6 | x=20; //compile time error-const variable values cannot be changed 7 | int y= x+10; 8 | 9 | cout<<"x="< 2 | 3 | //array implementation of Queue-we will use a circular array 4 | 5 | using namespace std; 6 | 7 | 8 | int main() { 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /Data Structures/SORTING/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | #define n 5 7 | 8 | 9 | //BUBBLE SORT function- takes argument as an array(pointer) and the size of array 10 | 11 | //TIME COMPLEXITY-O(n^2) of BUBBLE SORT-nested loops 12 | void BubbleSort(int *arr,int size) { 13 | 14 | for(int i = 0 ; i < size; i++ ) { 15 | for(int j=i+1 ; j < size ; j ++ ) { 16 | 17 | if(arr[i]>arr[j]) { 18 | 19 | swap(arr[i],arr[j]); 20 | } 21 | } 22 | } 23 | 24 | for(int i=0;i>arr[i]; 37 | } 38 | 39 | BubbleSort(arr,n); 40 | 41 | // for(int i=0;iarr[j]) { //for sorting in ascending order 46 | // 47 | // swap(arr[i],arr[j]); 48 | // } 49 | // } 50 | // } 51 | 52 | 53 | 54 | // cout<<"Sorted array is: "< 2 | 3 | using namespace std; 4 | 5 | 6 | #define n 5 7 | //SELECTION SORT in C++ 8 | //TIME COMPLEXITY-O(n^2) of SELCETION SORT-nested loops 9 | //NOTE-The number of swap operations are minimized in general in SELECTION SORT 10 | //Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above. 11 | void SelectionSort(int *arr,int size) { 12 | 13 | for(int i = 0 ; i < size; i++ ) { 14 | int min = i; 15 | 16 | for(int j=i+1 ; j < size ; j ++ ) { 17 | 18 | if(arr[j] < arr[min]) { 19 | 20 | min = j; 21 | swap(arr[i],arr[min]); 22 | 23 | } 24 | 25 | } 26 | } 27 | 28 | for(int i=0;i>arr[i]; 45 | } 46 | 47 | SelectionSort(arr,n); 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Data Structures/SORTING/selectionSort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anishsingh20/Programming-in-Cpp/de5dfecb715ce6ed9a59d54aedc1aab4f06703a3/Data Structures/SORTING/selectionSort.exe -------------------------------------------------------------------------------- /Data Structures/Searching/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | //Linear search program- TIME COMPLEXITY-O(n) 6 | 7 | //one by one match data with array elements , if data matches , return its index , otherwise keep searching and matching 8 | //Linear search is rarely used practically. 9 | 10 | //other search algorithms such as the binary search algorithm and hash tables allow significantly faster searching comparison to Linear search. 11 | int n=5; 12 | int LinearSearch(int *arr,int data) { 13 | 14 | for(int i = 0; i < n ; i++) 15 | { 16 | if(arr[i]==data) 17 | { 18 | return i; 19 | } 20 | 21 | return -1; 22 | 23 | } 24 | 25 | 26 | 27 | } 28 | 29 | int main() { 30 | 31 | 32 | 33 | int data,arr[n]; 34 | cin>>data; 35 | for(int i = 0; i < n ; i++) { 36 | cin>>arr[i]; 37 | 38 | } 39 | 40 | cout< 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | 9 | //function to check whether a given expression has balanced parenthesis or not? 10 | bool checkBalance(string exp) { 11 | 12 | stackS;//defining a char stack 13 | //scanning left to right of the expression 14 | 15 | for(int i=0;i>exp; 68 | 69 | if(checkBalance(exp)) { 70 | cout<<"Balanced expression"< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | //------------------------USING STACK-------------------- takes Time coplexity=O(n),space complexity=O(n) due to space allocated for stack 8 | 9 | //void reverse(string str) { 10 | // stack s; 11 | // 12 | // //push string to stack 13 | // //reading the string char one by one and pusing it to stack 14 | // for(int i=0;i 2 | #include 3 | 4 | 5 | //program to check is a BST is AVL tree or not 6 | //we simply have to check for the balance condition recursively while traversing the tree 7 | 8 | using namespace std; 9 | 10 | struct BSTnode { 11 | 12 | int data,height; 13 | struct BSTnode *left,*right; 14 | }; 15 | 16 | 17 | 18 | int Height(BSTnode *root) 19 | { 20 | if(!root) 21 | return -1; 22 | 23 | else 24 | return max(Height(root->left),Height(root->right)) + 1; 25 | } 26 | 27 | 28 | int isBSTAVL(BSTnode *root) 29 | { 30 | if(!root) 31 | return -1; 32 | 33 | //check a root 34 | if(Height(root->right)-Height(root->left)==2 || abs(Height(root->left)-Height(root->right)) > 1 ) 35 | return 0; 36 | 37 | //then recursively check for left subtree for the balanced conidtion 38 | if(root->left) 39 | return isBSTAVL(root->left); 40 | 41 | //then recursively check for right subtree for balanced condition 42 | if(root->right) 43 | return isBSTAVL(root->right); 44 | 45 | return 1; 46 | 47 | } 48 | 49 | 50 | BSTnode *newNode(int data) 51 | { 52 | BSTnode *temp = new BSTnode(); 53 | 54 | temp->data = data; 55 | 56 | temp->left = temp->right = NULL; 57 | 58 | return temp; 59 | } 60 | 61 | 62 | int main() 63 | { 64 | BSTnode *root=newNode(8); 65 | 66 | root->left = newNode(6); 67 | root->left->right = newNode(7); 68 | // root->right->left = newNode(8); 69 | // root->left->left = newNode(2); 70 | // root->left->right = newNode(5); 71 | // root->right->right = newNode(11); 72 | // root->right->right->right = newNode(12); 73 | 74 | if(!isBSTAVL(root)) 75 | cout<<"BST is not an AVL tree"< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | struct AVLnode { 8 | 9 | int data,height; 10 | struct AVLnode *left,*right; 11 | }; 12 | 13 | 14 | 15 | AVLnode *DoubleLeftRightRotation(AVLnode *X) 16 | { 17 | 18 | X->left = SingleRightRotation(X->left); 19 | 20 | return SingleLeftRotation(X); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Data Structures/Trees/AVL Trees/DoubleRightLeftRotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | struct AVLnode { 7 | 8 | int data,height; 9 | struct AVLnode *left,*right; 10 | }; 11 | 12 | 13 | 14 | AVLnode *DoubleRightLeftRotation(AVLnode *X) 15 | { 16 | X->right = S::SingleLeftRotation(X->right); 17 | 18 | return N::SingleRightRotation(X); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Data Structures/Trees/AVL Trees/FullHeightBalancedTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define n 100 6 | 7 | //Program to generate a full height balanced binary tree where balance factor is atmost 0 for all nodes. 8 | //balance factor(k) = height(left subtree) - height(right subtree) 9 | 10 | 11 | struct Node { 12 | 13 | int data; 14 | struct Node *left,*right; 15 | }; 16 | 17 | 18 | 19 | //nodes will be from 1 to 2^(h+1) - 1. As in a full binary tree max number of nodes can be 2^(h+1) - 1, if we assume height of a tree with 20 | //single node = 0 21 | 22 | //the function takes parameter as height of tree- we will traverse in inorder so as to satisfy the BST property 23 | Node *FullBalancedBST(int h) 24 | { 25 | 26 | static int count=1; 27 | Node *temp = new Node(); 28 | 29 | if(h==-1) 30 | return NULL; 31 | 32 | //recursively fill the left subtree first 33 | temp->left = FullBalancedBST(h-1); 34 | 35 | temp->data = count++; 36 | 37 | //then go to the right subtree 38 | temp->right = FullBalancedBST(h-1); 39 | 40 | return temp; 41 | 42 | }//time complexity = O(n) and Space complexity = O(logn) as stack space consumed is proportional to the height of a recursion tree. 43 | //and in this case it is a FUll binary search tree where height h = logn 44 | 45 | void Inorder(Node *root) 46 | { 47 | if(!root) 48 | return; 49 | 50 | Inorder(root->left); 51 | 52 | cout<data<<" "; 53 | 54 | Inorder(root->right); 55 | } 56 | 57 | int main() 58 | { 59 | 60 | struct Node *root = FullBalancedBST(3); 61 | 62 | Inorder(root); 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Data Structures/Trees/AVL Trees/MinimalAVLTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /*Program to find Minimum number of nodes in an AVL tree of height h i.e generating an MINIMAL AVL tree 6 | 7 | We will utilize the recurrence relation 8 | N(h) = 1+ N(h-1) + N(h-2) are minimum number of nodes in an AVL tree of height h 9 | */ 10 | 11 | 12 | struct AVLnode { 13 | 14 | int data; 15 | struct AVLnode *left,*right; 16 | }; 17 | 18 | 19 | 20 | int count = 1; 21 | 22 | //given height of AVL tree- generate minimal AVL tree i.e AVL tree with minimum number of nodes 23 | AVLnode* GenerateMinimalAVL(int h) 24 | { 25 | 26 | AVLnode *temp = new AVLnode(); 27 | 28 | if( h == 0 ) return NULL; 29 | 30 | 31 | 32 | temp->left = GenerateMinimalAVL(h-1); 33 | 34 | temp->data = count++; 35 | 36 | temp->right = GenerateMinimalAVL(h-2); 37 | 38 | return temp; 39 | 40 | } 41 | 42 | 43 | void Inorder(AVLnode *root) 44 | { 45 | if(!root) 46 | return; 47 | 48 | Inorder(root->left); 49 | 50 | cout<data<<" "; 51 | 52 | Inorder(root->right); 53 | } 54 | 55 | 56 | int main() 57 | { 58 | struct AVLnode *root = GenerateMinimalAVL(2); 59 | 60 | Inorder(root); 61 | 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Data Structures/Trees/AVL Trees/SingleLLRotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /*Program to do Single Left left rotation for converting an unbalaned AVL tree to a balanced AVL Tree when SOME OPERATION such as 3 | INSERTION OR DELETION happens. 4 | */ 5 | 6 | struct AVLnode { 7 | 8 | int data,height; 9 | struct AVLnode *left,*right; 10 | }; 11 | 12 | int height(AVLnode *root) 13 | { 14 | if(!root) 15 | return -1; 16 | 17 | else 18 | return max(height(root->left),height(root->right)) + 1; 19 | } 20 | 21 | AVLnode *SingleleftRotation(AVLnode *X) 22 | { 23 | //we have to make the left child of X as root say(W is the left child of X) and move X as right of W 24 | //then the right child of W should be made the left child of X 25 | //then make X as right child of W 26 | AVLnode *W = X->left; 27 | X->left = W->right; 28 | W->right = X; 29 | 30 | X->height = max(height(X->left),height(X->right)) + 1; 31 | W->height = max(height(W->left), X->height) + 1; 32 | 33 | return W;//new root 34 | 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /Data Structures/Trees/AVL Trees/SingleRRrotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /*Program to do Single right right rotation for converting an unbalaned AVL tree to a balanced AVL Tree when SOME OPERATION such as 6 | INSERTION OR DELETION happens. 7 | */ 8 | 9 | 10 | struct AVLnode { 11 | 12 | int data,height; 13 | struct AVLnode *left,*right; 14 | }; 15 | 16 | int height(AVLnode *root) 17 | { 18 | if(!root) 19 | return -1; 20 | 21 | else 22 | return max(height(root->left),height(root->right)) + 1; 23 | } 24 | 25 | AVLnode *SingleRightRotation(AVLnode *X) 26 | { 27 | //we have to make the right child of X as root say(W is the right child of X) and move X to left of W 28 | //then the left child of W should be made the right child of X 29 | //then make X as left child of W 30 | AVLnode *W = X->right; 31 | X->right = W->left; 32 | W->left = X; 33 | 34 | X->height = max(height(X->left),height(X->right)) + 1; 35 | W->height = max(height(W->right), X->height) + 1; 36 | 37 | return W;//new root 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Data Structures/Trees/BST/BSTwithNkeys.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /*Program to count the number of different BST poossible with 1...n keys = CATALAN NUMBER 6 | 7 | This particular question is an application of CATALAN NUMBER. 8 | 9 | */ 10 | 11 | 12 | int CountBST(int n) 13 | { 14 | if(n<=1) 15 | return 1; 16 | 17 | int sum=0; 18 | 19 | int root,left,right; 20 | for(root=0; root < n ; root++) 21 | { 22 | left = CountBST(root); 23 | right = CountBST(n-root-1); 24 | 25 | sum += left*right; 26 | } 27 | 28 | return sum; 29 | } 30 | //this program simply finds the nth catalan number recursively. 31 | 32 | int main() 33 | { 34 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | struct BSTnode{ 7 | 8 | int data; 9 | struct BSTnode *left,*right; 10 | }; 11 | 12 | BSTnode *newNode(int data) 13 | { 14 | BSTnode *temp = new BSTnode(); 15 | 16 | temp->data = data; 17 | 18 | temp->left = temp->right = NULL; 19 | 20 | return temp; 21 | } 22 | 23 | //Recursive implementation-max node is the right most node in the BST which does not has any right child 24 | BSTnode *maxNode(BSTnode *root) 25 | { 26 | if(!root) return NULL; 27 | 28 | 29 | if(root->right==NULL) 30 | return root; 31 | 32 | else return maxNode(root->right); 33 | } 34 | 35 | 36 | BSTnode *insert(BSTnode *root,int data) 37 | { 38 | 39 | 40 | 41 | 42 | 43 | //base condition-if root is NULL-allocate memory and make node 44 | if(root==NULL) 45 | { 46 | root = new BSTnode(); 47 | root->data = data; 48 | return root; 49 | 50 | } 51 | 52 | else 53 | { 54 | 55 | if(root->data >= data) 56 | root->left = insert(root->left,data); 57 | 58 | 59 | 60 | else 61 | root->right = insert(root->right,data); 62 | 63 | } 64 | 65 | return root; 66 | } 67 | 68 | int main() 69 | { 70 | 71 | BSTnode *root = newNode(7); 72 | 73 | insert(root,3); 74 | insert(root,10); 75 | 76 | insert(root,12); 77 | insert(root,2); 78 | insert(root,1); 79 | 80 | 81 | cout<data; 82 | 83 | 84 | 85 | return 0; 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Trees/DeleteTreePostorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | //program to delete a Binary tree-we have to take care that we first need to delete the child nodes, before deleting the parent nodes 7 | //this can easily be dine using POSTORDER traversal - as in postorder we first traverse to the left and the right subtrees then visit the parent root 8 | 9 | struct BinaryTreeNode{ 10 | int data; 11 | BinaryTreeNode *left; 12 | BinaryTreeNode *right; 13 | }; 14 | 15 | void DeleteTree(struct BinaryTreeNode *root) 16 | { 17 | if(root==NULL) 18 | { 19 | 20 | return; 21 | } 22 | 23 | if(root) 24 | { 25 | DeleteTree(root->left); 26 | DeleteTree(root->right); 27 | 28 | free(root); 29 | } 30 | } 31 | 32 | 33 | void PreOrderRec(struct BinaryTreeNode *root) 34 | { 35 | if(!root) 36 | { 37 | 38 | return; 39 | } 40 | 41 | if(root) 42 | { 43 | cout<data<<" "; 44 | PreOrderRec(root->left); 45 | PreOrderRec(root->right); 46 | } 47 | 48 | 49 | } 50 | 51 | 52 | 53 | int main() 54 | { 55 | struct BinaryTreeNode *root = new BinaryTreeNode(); 56 | struct BinaryTreeNode *r1 = new BinaryTreeNode(); 57 | struct BinaryTreeNode *r2 = new BinaryTreeNode(); 58 | struct BinaryTreeNode *r3 = new BinaryTreeNode(); 59 | struct BinaryTreeNode *r4 = new BinaryTreeNode(); 60 | 61 | root->data = 10; 62 | r1->data = 2; 63 | r2->data = 15; 64 | r3->data =4; 65 | r4->data = 5; 66 | 67 | root->left = r1; 68 | root->right = NULL; 69 | 70 | r1->left = r2; 71 | r2->right = r3; 72 | 73 | r3->right = r4; 74 | r3->left = NULL; 75 | 76 | r4->left = r4->right = NULL; 77 | 78 | PreOrderRec(root); 79 | 80 | DeleteTree(root); 81 | 82 | 83 | } 84 | 85 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Trees/LevelOrderLineByLine.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct node{ 7 | 8 | int data; 9 | struct node *left,*right; 10 | }; 11 | 12 | node *newNode(int data) 13 | { 14 | node *temp = new node(); 15 | temp->data = data; 16 | 17 | temp->left = temp->right = NULL; 18 | } 19 | 20 | void PrintLevelLinebyLine(node *root) 21 | { 22 | queueq; 23 | 24 | if(!root) return ; 25 | 26 | q.push(root); 27 | q.push(NULL); //marker for completion of a level 28 | while(!q.empty()) 29 | { 30 | node *temp = q.front(); 31 | q.pop(); 32 | 33 | if(temp) 34 | { 35 | cout<data<<" "; 36 | 37 | if(temp->left) q.push(temp->left); 38 | 39 | if(temp->right) q.push(temp->right); 40 | } 41 | 42 | //if a level is completed 43 | else if(temp==NULL) 44 | { 45 | if(!q.empty()) q.push(NULL); 46 | 47 | //end the line and go to the next line-once a level is finished 48 | cout<left = newNode(2); 61 | root->right = newNode(3); 62 | root->left->left = newNode(4); 63 | root->left->right = newNode(5); 64 | root->right->left = newNode(6); 65 | root->right->right = newNode(7); 66 | 67 | PrintLevelLinebyLine(root); 68 | 69 | } 70 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Trees/NthPreorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct node { 6 | int data; 7 | struct node *left,*right; 8 | }; 9 | 10 | 11 | void nthPreorder(node *root,int n) 12 | { 13 | if(!root) return; 14 | static int k = 0; 15 | node *kthnode; 16 | 17 | if( ++k == n) 18 | { 19 | cout<data; 20 | return; 21 | } 22 | 23 | if(root->left) 24 | nthPreorder(root->left,n); 25 | 26 | if(root->right) 27 | nthPreorder(root->right,n); 28 | 29 | 30 | 31 | } 32 | 33 | node* newNode(int item) 34 | { 35 | node* temp = new node; 36 | temp->data = item; 37 | temp->left = temp->right = NULL; 38 | 39 | return temp; 40 | } 41 | 42 | void Preorder(node *root) 43 | { 44 | if(root) 45 | { 46 | cout<data<<" "; 47 | 48 | Preorder(root->left); 49 | 50 | Preorder(root->right); 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | 57 | struct node *root = newNode(19); 58 | 59 | root->left = newNode(7); 60 | root->right = newNode(21); 61 | 62 | root->left->left = newNode(3); 63 | 64 | root->right->right = newNode(24); 65 | 66 | cout<<"preorder traversal is "< 2 | 3 | //IMPLEMENTATION OF FINDING HEIGHT OF BINARY TREE - height is the longest path from the root of the tree to the deepest node(leaf) 4 | 5 | using namespace std; 6 | 7 | 8 | struct BinaryTreeNode{ 9 | int data; 10 | BinaryTreeNode *left; 11 | BinaryTreeNode *right; 12 | }; 13 | 14 | 15 | 16 | int height(struct BinaryTreeNode *root) 17 | { 18 | if(root) 19 | { 20 | return (1 + max( height(root->right) , height(root->left) ); 21 | } 22 | 23 | else { 24 | return 0; 25 | } 26 | } 27 | 28 | 29 | 30 | void TopView(struct BinaryTreeNode *root) 31 | { 32 | if(!root) return; 33 | 34 | 35 | 36 | 37 | if(root) 38 | { 39 | //heights of left and right subtree 40 | int hl = height(root->left); 41 | 42 | int hr = height(root->right); 43 | cout<data<<" "; 44 | 45 | if(hl >= hr) TopView(root->left); 46 | 47 | else TopView(root->right); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Trees/ReverseInorderUsingMorrisTraversal.cpp: -------------------------------------------------------------------------------- 1 | //algorithm to find reverse inorder traversal using morris traversal based on inorder successor of current node 2 | 3 | void MorrisReverseInorder(Node *root) 4 | { 5 | 6 | if(!root) return ; 7 | 8 | Node *curr,*Insuccessor; 9 | 10 | curr=root; 11 | 12 | while(curr) 13 | { 14 | //case 1 if curr has no rightchild then visit current and move to left child 15 | if(curr->right==NULL) 16 | { 17 | cout<data<<" "; 18 | curr = curr->left; 19 | } 20 | 21 | else 22 | { 23 | //find the inorder successor of current node i.e left most node in right subtree or right child itself 24 | Insuccessor = curr->right; 25 | 26 | while(Insuccessor->left!=NULL && Insuccessor->left!=curr) 27 | Insuccessor = Insuccessor->left; 28 | 29 | //if the left of inorder successor is NULL 30 | if(Insuccessor->left==NULL) 31 | { 32 | //then connect left link to current node 33 | Insuccessor->left = curr; 34 | 35 | //move current to right child 36 | curr = curr->right; 37 | } 38 | 39 | //otherwise inorder successor's left is not NULL and already left is linked with current node 40 | elsex 41 | { 42 | Insuccessor->left=NULL; 43 | 44 | //visiting the current node 45 | cout<data<<" "; 46 | 47 | curr = curr->left; 48 | } 49 | } 50 | } 51 | 52 | 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Data Structures/Trees/Binary Trees/RightView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | //right view is the view of the binary tree where we can only see the right most nodes at each level. 8 | 9 | struct node{ 10 | 11 | int data; 12 | node *left,*right; 13 | }; 14 | 15 | 16 | void RightView(node *root) 17 | { 18 | node *temp; 19 | if(!root) 20 | return; 21 | 22 | queueq; 23 | 24 | q.push(root); 25 | 26 | while(!q.empty()) 27 | { 28 | temp = q.front(); 29 | q.pop(); 30 | 31 | 32 | 33 | 34 | cout<data<<" "; 35 | 36 | //pusing only the right child of current node 37 | if(temp->right) 38 | q.push(temp->right); 39 | 40 | 41 | //if the current node has no right child, the left child is the only node 42 | if(!temp->right) 43 | cout<left->data<<" "; 44 | 45 | 46 | } 47 | } 48 | 49 | 50 | node *newNode(int data) 51 | { 52 | node *temp = new node(); 53 | temp->data = data; 54 | 55 | return temp; 56 | } 57 | 58 | int main() 59 | { 60 | // node *root = newNode(1); 61 | // 62 | // root->left = newNode(2); 63 | // 64 | // root->right = newNode(3); 65 | // 66 | // root->left->left = newNode(4); 67 | // root->left->right = newNode(5); 68 | // root->right->left = newNode(6); 69 | // root->right->right = newNode(7); 70 | // root->right->right->left = newNode(8); 71 | 72 | 73 | node* root = newNode(10); 74 | root->left = newNode(2); 75 | root->right = newNode(3); 76 | root->left->left = newNode(7); 77 | root->left->right = newNode(8); 78 | root->right->right = newNode(15); 79 | root->right->left = newNode(12); 80 | root->right->right->left = newNode(14); 81 | 82 | 83 | 84 | RightView(root); 85 | 86 | 87 | } 88 | 89 | -------------------------------------------------------------------------------- /Data Structures/Trees/Generic N-Ary Trees/NumChildren.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //PROGRAM TO FIND NO OF CHILD NODES FOR A NODE IN A GENERIC TREE 5 | using namespace std; 6 | 7 | struct TreeNode{ 8 | int data; 9 | struct TreeNode *firstChild; 10 | struct TreeNode *nextSibling; 11 | }; 12 | 13 | 14 | 15 | //simply move to the first child and then keep counting till we have next siblings of that node 16 | int NumChild(struct TreeNode *root) 17 | { 18 | int count = 0; 19 | //first move to the firstchild 20 | 21 | root = root->firstChild; 22 | 23 | //now keep counting until we have nextsiblings of first child 24 | while(root) 25 | { 26 | count++; 27 | root = root->nextSibling; 28 | 29 | } 30 | 31 | return count; 32 | } 33 | //TIME COMPLEXITY = O(N) 34 | 35 | 36 | int main() 37 | { 38 | 39 | struct TreeNode *root= new TreeNode(); 40 | struct TreeNode *n1= new TreeNode(); 41 | struct TreeNode *n2= new TreeNode(); 42 | struct TreeNode *n3= new TreeNode(); 43 | struct TreeNode *n4= new TreeNode(); 44 | struct TreeNode *n5= new TreeNode(); 45 | 46 | root->data=1; 47 | n1->data=2; 48 | n2->data=3; 49 | n3->data=4; 50 | n4->data=5; 51 | n5->data = 6; 52 | 53 | root->firstChild = n1; 54 | 55 | n1->nextSibling = n2; 56 | 57 | n2->nextSibling = n3; 58 | 59 | n2->firstChild = n5; 60 | 61 | n1->firstChild = n4; 62 | 63 | 64 | cout< 2 | #include 3 | 4 | //PROGRAM TO FIND NUMBER OF SIBLINGS OF A NODE IN A GENERIC TREE 5 | 6 | using namespace std; 7 | 8 | struct TreeNode{ 9 | int data; 10 | struct TreeNode *firstChild; 11 | struct TreeNode *nextSibling; 12 | }; 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | int numSiblings(TreeNode *root) 23 | { 24 | 25 | int count = 0; 26 | 27 | while(root) 28 | { 29 | 30 | count++; 31 | 32 | 33 | 34 | root = root->nextSibling; 35 | } 36 | 37 | return count; 38 | } 39 | 40 | 41 | 42 | //simply first go to the first child , and then keep counting all the nextSiblings of current node 43 | int numChildren(TreeNode *root) 44 | { 45 | int count = 0; 46 | 47 | root = root->firstChild; 48 | 49 | while(root) 50 | { 51 | count++; 52 | root=root->nextSibling; 53 | } 54 | 55 | return count; 56 | } 57 | 58 | int main() 59 | { 60 | 61 | struct TreeNode *root= new TreeNode(); 62 | struct TreeNode *n1= new TreeNode(); 63 | struct TreeNode *n2= new TreeNode(); 64 | struct TreeNode *n3= new TreeNode(); 65 | struct TreeNode *n4= new TreeNode(); 66 | struct TreeNode *n5= new TreeNode(); 67 | 68 | root->data=1; 69 | n1->data=2; 70 | n2->data=3; 71 | n3->data=4; 72 | n4->data=5; 73 | n5->data = 6; 74 | 75 | root->firstChild = n1; 76 | 77 | n1->nextSibling = n2; 78 | 79 | n2->nextSibling = n3; 80 | 81 | n2->firstChild = n5; 82 | 83 | n1->firstChild = n4; 84 | 85 | 86 | cout< 2 | #include 3 | 4 | //program to find equivalent subarrays 5 | 6 | using namespace std; 7 | 8 | int maxCount(int arr[],int size) 9 | { 10 | int count = 0 ; 11 | sets; 12 | setsub;//to store subarrays 13 | for(int i = 0 ; i < size ; i++) 14 | { 15 | s.insert(arr[i]); 16 | } 17 | 18 | int dis = s.size(); 19 | 20 | for(int i = 0 ; i < size; i++) 21 | { 22 | 23 | for(int j = i ; j < size;j++) 24 | { 25 | sub.insert(arr[j]); 26 | if(sub.size()==dis) 27 | count++; 28 | } 29 | 30 | //clearing the subarray after one complete check 31 | sub.erase(sub.begin(),sub.end()); 32 | 33 | } 34 | cout< 2 | 3 | //Program to demonstrate Recursive approaches to fidn pow(x,n) with different time complexities 4 | //First to solve any problem by recursion we need to define and calculate a recurrence relation or recursion defination 5 | //Space complexity of a recursive program is direclty proportional to the height/depth of the recursion tree 6 | 7 | 8 | //Method-1 9 | long long int Pow(int x,int n) 10 | { 11 | //base condition-state where recursion ends and return 1-leaf of recursion tree 12 | if(n==0) 13 | return 1; 14 | 15 | return x*Pow(x,n-1); 16 | } //Time complexity = O(n) = linear , but very high SPACE COMPLEXITY due to very large recursion tree proportional to n 17 | //So the stack space required to store the state of function calls is proportional to n 18 | 19 | //Method-2 , more efficient, LESSER SPACE COMPLEXITY due to lesser funcition calls states stored in stack 20 | long long int Pow1(int x,int n) 21 | { 22 | //base condition-state where recursion ends and return 1-leaf of recursion tree 23 | if(n==0) 24 | return 1; 25 | 26 | //if n is even power 27 | if(n%2==0) 28 | { 29 | long long int y = Pow1(x,n/2); 30 | return y*y; 31 | } 32 | 33 | //if x is odd 34 | else 35 | { 36 | return x*Pow1(x,n-1); 37 | } 38 | pow 39 | } 40 | 41 | using namespace std; 42 | 43 | int main() 44 | { 45 | 46 | cout< 2 | 3 | 4 | using namespace std; 5 | /*longest common subsequence problem- 6 | 1)Brute force - T(n) = O(n*2^n) 7 | 8 | 2)recursion - T(n) = O(2^n)- has overlapping subproblems which are computed repetedly. 9 | 10 | 3)DP = T(n) = O(n*n) -Most efficient 11 | */ 12 | 13 | 14 | 15 | //DP solution-efficient)By making a 2-D table which contains the length of subsequence- 16 | int LCS_DP(string &a,string &b,int m,int n) 17 | { 18 | int L[m+1][n+1]; //a 2-d table 19 | 20 | for(int i = 0 ; i <= m ; i++) 21 | { 22 | for(int j = 0 ; j <= n;j++) 23 | { 24 | if(i==0 || j==0) 25 | L[i][j] = 0; 26 | 27 | //if same char found-increase the length by 1 28 | else if(a[i-1]==b[j-1]) 29 | L[i][j] = L[i-1][j-1] + 1; 30 | 31 | else L[i][j] = max(L[i-1][j],L[i][j-1]); 32 | 33 | } 34 | } 35 | 36 | //max length stored in last index 37 | return L[m][n]; 38 | } 39 | //T(n) = O(mn) which is very efficient 40 | 41 | 42 | 43 | 44 | //recrsive implementation 45 | int LCS(string &a,string &b,int n,int m) 46 | { 47 | 48 | 49 | //base case when we reach start of strings 50 | if(m==0 || n==0) 51 | return 0; 52 | 53 | //if found common chars 54 | else if(a[n-1]==b[m-1]) 55 | return 1 + LCS(a,b,n-1,m-1); 56 | 57 | //if not common seq found 58 | else 59 | return max(LCS(a,b,n-1,m),LCS(a,b,n,m-1)); 60 | 61 | 62 | 63 | 64 | 65 | 66 | } //T(n) = O(2^n) exponential algorithm-and so a string of length n has 2^n different possible sub-seq. 67 | 68 | 69 | int main() 70 | { 71 | string a = "cbbd"; 72 | string b = "dbbc"; 73 | 74 | int n = a.size(); 75 | int m = b.size(); 76 | 77 | cout< 2 | #include 3 | 4 | //program to find longest repeated substring 5 | 6 | using namespace std; 7 | 8 | string LongestRepeatedSubstr(string s) 9 | { 10 | int size = s.length(); 11 | string sub; 12 | mapm; 13 | for(int i = 0 ; i < size ; i++) 14 | { 15 | sub = ""; 16 | for(int j = 1 ; j <= size-i ; j++) 17 | { 18 | sub = s.substr(i,j); 19 | 20 | //if substring found again, simply increase the count; 21 | if(m.find(sub)==m.end()) 22 | { 23 | m[sub] = 1; 24 | } 25 | 26 | 27 | //otherwise,if not found insert it in map with count as 1 28 | else m[sub]++; 29 | } 30 | 31 | } 32 | 33 | map::iterator it; 34 | int max = 0; 35 | string str="\0"; 36 | for(it = m.begin();it!=m.end();it++) 37 | { 38 | 39 | if((it->first).length()>max && it->second > 1) 40 | { 41 | max = (it->first).length(); 42 | str = it->first; 43 | } 44 | } 45 | 46 | return str; 47 | 48 | 49 | } 50 | 51 | int main() 52 | { 53 | string str = "abcpqrabpqpq"; 54 | 55 | cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | //longest repeating subsequence 8 | string LRS(string a,int m) 9 | { 10 | int table[m+1][m+1]; 11 | 12 | for (int i=0; i<=m; i++) 13 | for (int j=0; j<=m; j++) 14 | table[i][j] = 0; 15 | 16 | for(int i = 1 ; i <= m;i++) 17 | { 18 | for(int j = 1 ; j<= m;j++) 19 | { 20 | if(i==0||j==0) 21 | table[i][j] = 0; 22 | 23 | else if(a[i-1]==a[j-1] && i!=j) 24 | table[i][j] = table[i-1][j-1] + 1; 25 | 26 | else table[i][j] = max(table[i-1][j],table[i][j-1]); 27 | } 28 | } 29 | 30 | 31 | 32 | int i = m,j=m; 33 | string lrs= " "; 34 | while(i>0 && j>0) 35 | { 36 | if(table[i][j]==table[i-1][j-1]+1) 37 | { 38 | lrs = lrs + a[i-1]; 39 | 40 | i--; 41 | j--; 42 | 43 | } 44 | 45 | else if(table[i][j] == table[i-1][j]) 46 | i--; 47 | 48 | else 49 | j--; 50 | } 51 | 52 | reverse(lrs.begin(),lrs.end()); 53 | return lrs; 54 | } 55 | 56 | 57 | int main() 58 | { 59 | 60 | 61 | string s1 = "AABEBCDD"; 62 | int len = s1.length(); 63 | 64 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | 8 | bool CheckUnique(string s, int start,int end) 9 | { 10 | seta; 11 | 12 | for(int i = start ; i < end ; i++) 13 | { 14 | //if item already found in set return false 15 | if( a.find(s[i]) != a.end()) return false; 16 | 17 | else a.insert(s[i]); 18 | } 19 | 20 | return true; 21 | 22 | } 23 | 24 | 25 | //brute force-checking all possible sub strings, and checking if they are unique 26 | int lenOfSubstring(string s) 27 | { 28 | int n = s.size(); 29 | int len = 0 ; 30 | for(int i = 0 ; i < n ; i++) 31 | { 32 | for(int j = i+1 ; j <= n ; j++) 33 | { 34 | if(CheckUnique(s,i,j)) len = max(len,j-i); 35 | } 36 | 37 | 38 | } 39 | 40 | return len; 41 | 42 | } 43 | //T(n) = O(n*n*n)-inefficient solution- 44 | 45 | 46 | //using sliding window concept. 47 | int lengthOfLongestSubstring(string s) { 48 | 49 | seta; 50 | 51 | int i = 0,j = 0 ; 52 | int len = 0; 53 | int n = s.size(); 54 | while(i < n && j < n) 55 | { 56 | //if set does not containes a char, we simply insert it 57 | if(a.find(s[j]) == a.end()) 58 | { 59 | 60 | a.insert(s[j++]); 61 | 62 | len = max(len,j-i); 63 | } 64 | 65 | //if already exists, then remove a item from set 66 | else 67 | { 68 | a.erase(s[i++]); 69 | } 70 | 71 | } 72 | 73 | return len; 74 | 75 | }//T(n) = O(2n),S(n) = O(n) 76 | 77 | 78 | int main() 79 | { 80 | 81 | 82 | cout< 2 | 3 | using namespace std; 4 | 5 | 6 | 7 | //Using Dp 8 | int MaxSumDp(int arr[],int size) 9 | { 10 | int dp[size]; 11 | 12 | //for case when first item is negetive 13 | dp[0] = arr[0] > 0 ? arr[0] : 0; 14 | dp[1] = max(arr[0],arr[1]); 15 | int maxSum = arr[0]; 16 | 17 | for(int i = 2 ; i < size ; i++) 18 | { 19 | dp[i] = max(dp[i-1],dp[i-2]+arr[i]); 20 | } 21 | 22 | for(int i = 0 ; i < size ; i++) 23 | { 24 | if(maxSum < dp[i]) 25 | { 26 | maxSum = dp[i]; 27 | } 28 | } 29 | 30 | return maxSum; 31 | } 32 | //T(n) = O(n), space = O(n) for the aux array 33 | 34 | 35 | 36 | //Iterative solution 37 | int MaxSum(int arr[],int size) 38 | { 39 | int mSum = 0,curSum = 0; 40 | for(int i = 0 ; i < size; i++) 41 | { 42 | curSum = 0; 43 | for(int j = i ; j < size ; j+=2) 44 | { 45 | curSum += arr[j]; 46 | 47 | if(curSum > mSum) 48 | mSum = curSum; 49 | } 50 | } 51 | 52 | return mSum; 53 | }//T(n) = O(n*n) , and space = O(1) 54 | 55 | 56 | //int MaxSumSimple(int arr[],int size) 57 | //{ 58 | // int curSum = arr[0] ; 59 | // int mSum = INT_MIN; 60 | //// 61 | // for(int i = 2 ; i < size ; i++) 62 | // { 63 | // curSum = max(arr[i]+curSum,arr[i-1]); 64 | // 65 | // mSum = max(mSum,curSum); 66 | // } 67 | // 68 | // return mSum; 69 | // 70 | // 71 | //} 72 | 73 | int main() 74 | { 75 | int arr[] = {1,2,3,6,7}; 76 | int size = sizeof(arr)/sizeof(arr[0]); 77 | cout< 2 | 3 | using namespace std; 4 | 5 | //program for finding maximum in minimum window of sie 1 to n(size of array) 6 | 7 | //Brute force-O(n*n*n) considering each window one by one. 8 | 9 | 10 | void MaxInMinWindow(int arr[],int size) 11 | { 12 | 13 | //window i starting from 1 to n 14 | for(int i = 1 ; i <= size ; i++) 15 | { 16 | int MaxofMin = INT_MIN; 17 | 18 | for(int j = 0 ; j <= size-i ; j++ ) 19 | { 20 | //minimum in current window 21 | int minInWin = arr[j]; 22 | for(int k = 1 ; k < i ;k++) 23 | { 24 | //minimum of current window 25 | if(arr[j+k] < minInWin) 26 | minInWin = arr[j+k]; 27 | } 28 | 29 | //updating max of minimum window 30 | if(minInWin > MaxofMin) 31 | MaxofMin = minInWin; 32 | } 33 | 34 | cout< 2 | 3 | 4 | //Program to find modular exponent using recursion- 5 | //it is (x^n % m) , i.e the remainder left after x raised to some n is divided by a positive number M 6 | using namespace std; 7 | 8 | /* x^n can be written as = x^n/2 * x^n/2 when n = even 9 | x^n can be written as = x . x^n-1 for odd n; 10 | using these recurrence relations we will find x^n mod M 11 | 12 | also (a*b) mod M = { (a mod M) * (b mod M)} mod M 13 | 14 | */ 15 | 16 | 17 | int ModExpo(int x, int n , int M) 18 | { 19 | //base terminating condition 20 | if(n==0) 21 | return 1; 22 | 23 | //when n is even 24 | else if(n%2==0) 25 | { 26 | int y = ModExpo(x,n/2,M); 27 | 28 | return (y*y)%M; 29 | 30 | } 31 | 32 | //when n is odd 33 | else 34 | { 35 | return ( ( x%M)*ModExpo(x,n-1,M) )% M; 36 | } 37 | } 38 | 39 | //TIme complexity = O(logn) , as T(n) = T(n/2) + c for n = even 40 | //for n=odd , T(n) = T(n-1) + c2, so upper bound we consider T(n) = T(n/2) + C , 41 | //on solving the above recurrence relation we get T(N) = O(logn) 42 | 43 | int main() 44 | { 45 | 46 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | string longestPalindrome(string s) { 8 | 9 | string rev = s; 10 | int m = s.size(); 11 | int n = rev.size(); 12 | reverse(rev.begin(),rev.end()); 13 | 14 | int L[m+1][n+1]; //a 2-d table 15 | 16 | for(int i = 0 ; i <= m ; i++) 17 | { 18 | for(int j = 0 ; j <= n ;j++) 19 | { 20 | if(i==0 || j==0) 21 | L[i][j] = 0; 22 | 23 | //if same char found-increase the length by 1 24 | else if(s[i-1] == rev[j-1]) 25 | L[i][j] = L[i-1][j-1] + 1; 26 | 27 | else L[i][j] = L[i-1][j-1]; 28 | 29 | } 30 | } 31 | 32 | int len = L[m][n]; 33 | 34 | string LPS(len+1,'\0'); 35 | 36 | int i = 0 ,j = 0; 37 | while(i < m && j < n ) 38 | { 39 | if(s[i]==rev[j]) 40 | { 41 | LPS[len-1] = s[i]; 42 | i++; j++; len--; 43 | } 44 | 45 | else if(L[i+1][j] > L[i][j+1] ) i++; 46 | 47 | else j++; 48 | } 49 | 50 | return LPS; 51 | 52 | } 53 | //T(n) = O(n*n) efficient,similar to printing LCS 54 | 55 | 56 | int main() 57 | { 58 | 59 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | //Program to print the LCS using DP 7 | 8 | 9 | //DP solution-efficient)By making a 2-D table which contains the length of subsequence- 10 | void PrintLCS(string &a,string &b,int m,int n) 11 | { 12 | int L[m+1][n+1]; //a 2-d table 13 | 14 | for(int i = 0 ; i <= m ; i++) 15 | { 16 | for(int j = 0 ; j <= n;j++) 17 | { 18 | if(i==0 || j==0) 19 | L[i][j] = 0; 20 | 21 | //if same char found-increase the length by 1 22 | else if(a[i-1]==b[j-1]) 23 | L[i][j] = L[i-1][j-1] + 1; 24 | 25 | else L[i][j] = max(L[i-1][j],L[i][j-1]); 26 | 27 | } 28 | } 29 | 30 | //max length stored in last index 31 | int LCSlen = L[m][n]; 32 | 33 | //getting the length of LCS 34 | //making the array to store the common letters 35 | string LCS(LCSlen+1,'\0'); 36 | 37 | int i = m , j = n; 38 | 39 | while(i > 0 && j >0) 40 | { 41 | if(a[i-1]==b[j-1]) 42 | { 43 | LCS[LCSlen-1] = a[i-1]; 44 | i--; j--; LCSlen--; 45 | } 46 | 47 | //go in direction of larger value 48 | if(L[i-1][j] > L[i][j-1]) 49 | i-- ; 50 | 51 | else j--; 52 | 53 | 54 | } 55 | 56 | 57 | cout< 2 | 3 | using namespace std; 4 | 5 | long long int F[30]; 6 | 7 | 8 | long long int factorial(int n) 9 | { 10 | if(n==0) return 0; 11 | if(n==1) return 1; 12 | 13 | 14 | //if result is stored in array-simply return it 15 | if(F[n]!= -1) 16 | { 17 | return F[n]; 18 | 19 | } 20 | 21 | //otherwise first calculate result recursively and store it in array 22 | 23 | F[n] = n*factorial(n-1); 24 | return F[n]; 25 | 26 | } //as efficient as simple recursive implementation or factorial program 27 | 28 | 29 | int main() 30 | { 31 | for(int i=0;i<20;i++) 32 | { 33 | F[i] = -1; 34 | } 35 | 36 | cout< 2 | 3 | /*PROGRAM TO USE RECURSION WITH MEMOIZATION TO IMPROVE TIME COMPLEXITY OF RECURSIVE FINONACCI SEQUENCE PROGRAM- 4 | In order to improve the time complexity of which are inefficient when using recursion and for higher values of n, we can use DP and memoization technique to 5 | store the results of the subproblems and state of recursive calls in some data structure (say array) and simly return them instead of 6 | redundantly calculating the same function calls. 7 | */ 8 | 9 | long long int F[51]; 10 | 11 | long long int Fibonacci(int n) 12 | { 13 | //if result is stored in memory simply return it 14 | if(F[n] != -1) 15 | { 16 | return F[n]; 17 | } 18 | 19 | //otherwise simply calculate the result and store it in memory 20 | 21 | F[n] = ( Fibonacci(n-1) + Fibonacci(n-2) ); 22 | 23 | return F[n]; 24 | 25 | 26 | } 27 | //TIME COMPLEXITY = O(N), Extra space = O(N) 28 | 29 | 30 | 31 | using namespace std; 32 | 33 | int main() 34 | { 35 | 36 | for(int i=0;i<51;i++) 37 | { 38 | F[i] = -1; 39 | } 40 | 41 | F[0] = 0 , F[1]=1; 42 | 43 | long long int result = Fibonacci(50); 44 | 45 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | //Program to find the starting and ending index of subarray whose sum equals K 7 | 8 | 9 | void subarraySum(vector& nums, int k) { 10 | 11 | int count = 0 ; 12 | 13 | for(int i = 0 ; i < nums.size(); i++) 14 | { 15 | int sum = 0 ; 16 | for(int j = i ; j < nums.size(); j++) 17 | { 18 | sum += nums[j]; //the cumalative sums of each subarray 19 | if(sum == k) 20 | { 21 | cout< v; 37 | 38 | v.push_back(1); 39 | v.push_back(1); 40 | v.push_back(1); 41 | v.push_back(2); 42 | 43 | subarraySum(v,3); 44 | 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /Dynamic Programming/UglyNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //UGLY NUMBERS program-finding Nth sequence of ugly number 6 | 7 | //METHOD-1 BRUTE FORCE APPROACH 8 | 9 | //function which divides a numeber a by greatest divisible power fo b 10 | int greatestDivide(int a, int b) 11 | { 12 | while(a%b==0) 13 | a=a/b; 14 | 15 | return a; 16 | } 17 | 18 | 19 | 20 | //function to check if a number is UGLY number or not 21 | int CheckUgly(int n) 22 | { 23 | n = greatestDivide(n,2); 24 | n = greatestDivide(n,3); 25 | n = greatestDivide(n,5); 26 | 27 | return (n==1) ? 1 : 0; 28 | 29 | } //when we finally get 1 this means it is a ugly number 30 | 31 | 32 | int getNthUglyNo(int n) 33 | { 34 | 35 | int i=1;//ugly number sequence 36 | int count = 1; //ugly number count 37 | 38 | while(n > count) 39 | { 40 | i++; 41 | if(CheckUgly(i)) 42 | { 43 | count++; 44 | } 45 | 46 | 47 | } 48 | 49 | return i; 50 | 51 | }//TIME COMPLEXITY = O(n) , Space complexity = O(1) 52 | 53 | 54 | 55 | int main() 56 | { 57 | 58 | 59 | cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /*Finding longest length of palindromic subsequence using LCS 8 | 1)Simply make a function to find LCS of 2 strings using DP 9 | 2) Use function LCS as a subroutine call in another function LPS which simply reverses the string 10 | and passes both of them as arguments in LCS subroutine. 11 | 12 | As LCS of the reverse of a string and that string will give us LPS 13 | 14 | */ 15 | 16 | //Naive recursive approach to find LCS 17 | int LCS(string a,string reva,int n,int m) 18 | { 19 | //base case 20 | if(n==0 || m==0) 21 | return 0; 22 | 23 | else if(a[n-1]==reva[m-1]) 24 | return 1 + LCS(a,reva,n-1,m-1); 25 | 26 | else return max(LCS(a,reva,n-1,m),LCS(a,reva,n,m-1)); 27 | } 28 | 29 | 30 | int LCS_DP(string &a,string &b) 31 | { 32 | int m = a.size(); 33 | int n = b.size(); 34 | int L[m+1][n+1]; //a 2-d table 35 | 36 | for(int i = 0 ; i <= m ; i++) 37 | { 38 | for(int j = 0 ; j <= n;j++) 39 | { 40 | if(i==0 || j==0) 41 | L[i][j] = 0; 42 | 43 | //if same char found-increase the length by 1 44 | else if(a[i-1]==b[j-1]) 45 | L[i][j] = L[i-1][j-1] + 1; 46 | 47 | else L[i][j] = max(L[i-1][j],L[i][j-1]); 48 | 49 | } 50 | } 51 | 52 | //max length stored in last index 53 | return L[m][n]; 54 | } 55 | //T(n) = O(mn) which is very efficient 56 | 57 | 58 | 59 | //function to find length of longest palindromic subseq where we reverse the string and pass it to LCS function 60 | int LPS(string a) 61 | { 62 | string rev = a; 63 | reverse(rev.begin(),rev.end()); 64 | 65 | return LCS_DP(a,rev); 66 | } 67 | //T(n) = O(n*n) quadratic , very efficnet 68 | 69 | 70 | 71 | 72 | int main() 73 | { 74 | string a = "cbbd"; 75 | 76 | cout< 2 | 3 | using namespace std; 4 | 5 | 6 | //program to find maximum subarray sum whose size equals k 7 | 8 | int maxSum(int arr[],int size,int k) 9 | { 10 | int Max = 0,curMax; 11 | for(int i = 0 ; i < (size-k) ; i++) 12 | { 13 | 14 | curMax = 0; 15 | for(int j = i ; j <= k ; j++) 16 | { 17 | curMax += arr[j]; 18 | 19 | if(curMax > Max) 20 | Max = curMax; 21 | } 22 | 23 | } 24 | 25 | return Max; 26 | } 27 | 28 | int minSum(int arr[],int size,int k) 29 | { 30 | int Min = INT_MAX,curMin; 31 | for(int i = 0 ; i <= (size-k) ; i++) 32 | { 33 | 34 | curMin = 0; 35 | for(int j = i ; j < i+k ; j++) 36 | { 37 | curMin += arr[j]; 38 | 39 | if(curMin < Min) 40 | Min = curMin; 41 | } 42 | 43 | } 44 | 45 | return Min; 46 | } 47 | 48 | 49 | int main() 50 | { 51 | int arr[] = {3,4,6,7,-10}; 52 | int size = sizeof(arr)/sizeof(arr[0]); 53 | cout< 2 | #include 3 | 4 | 5 | //FUNCTIONS WHICH CAN THROW EXCEPTIONS 6 | 7 | using namespace std; 8 | 9 | 10 | //function which can throw int or char or runtime error exceptions 11 | void test() throw(const char *,int, runtime_error) { 12 | 13 | 14 | throw runtime_error("Runtime error occured"); 15 | throw 20; 16 | //can throw multiple exceptions inside the function, but will only catch the first defined throwed exception 17 | 18 | } 19 | 20 | int main() { 21 | 22 | try 23 | { 24 | //calling the exception throwing function 25 | test() ; 26 | } 27 | 28 | 29 | catch(int err) 30 | { 31 | cout< 2 | #include 3 | 4 | 5 | //CATCHING MULTIPLE EXPECTIONS Based on type of Exception occured 6 | 7 | using namespace std; 8 | 9 | 10 | 11 | 12 | int main() 13 | { 14 | try { 15 | 16 | throw runtime_error("Runtime error occured"); 17 | } 18 | 19 | //if integer exception occurs this catch block is called 20 | catch(int err) { 21 | 22 | cout<<"Integer Error occured: "< 2 | #include 3 | 4 | using namespace std; 5 | 6 | //Program to show Nested try-catch blocks and re-throwing exceptions 7 | 8 | 9 | int main() 10 | { 11 | 12 | 13 | try { 14 | 15 | //throw("Char error occured");-if in parent try block we throw something , then the child try block is not executed 16 | 17 | try 18 | { 19 | throw ("Character error occured"); 20 | } 21 | 22 | catch(const char *err) 23 | { 24 | cout<"<"< 2 | 3 | 4 | //EXPECTION HANDLING IN CPP 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | int a,b; 10 | 11 | cin>>a; 12 | cin>>b; 13 | 14 | try{ 15 | if(b==0) { 16 | throw runtime_error("Denominator is 0"); 17 | } 18 | 19 | else { 20 | int c = a/b; 21 | cout<<"Product is : "< 2 | #include 3 | 4 | 5 | using namespace std; 6 | //creating custom user defined exception classes 7 | 8 | //Overspeed class which inherits from exception class 9 | class OverSpeed : public exception 10 | { 11 | public: 12 | int speed ; 13 | OverSpeed() 14 | { 15 | speed=0; 16 | } 17 | //inherits what() of exception class 18 | const char* what() 19 | { 20 | return "Please slow down, Overspeedying is dangerous."; 21 | 22 | } 23 | 24 | void getSpeed() 25 | { 26 | cout<<"Now the speed is: "<speed = speed; 32 | } 33 | 34 | };//created a custom exception class 35 | 36 | 37 | 38 | //class in which exception is throwed 39 | class Car { 40 | 41 | public: 42 | int speed ; 43 | //constructor 44 | Car() 45 | { 46 | speed=0; 47 | } 48 | 49 | void getSpeed() 50 | { 51 | cout<<"The speed is:"<= 150) { 64 | 65 | OverSpeed obj; 66 | 67 | 68 | 69 | obj.setSpeed(speed); 70 | 71 | throw obj; //will throw object of exception class OverSpeed 72 | 73 | } 74 | } 75 | } 76 | 77 | 78 | }; 79 | 80 | 81 | 82 | 83 | int main() 84 | { 85 | Car c; 86 | 87 | try { 88 | 89 | c.acclerate(); 90 | 91 | } 92 | catch(OverSpeed obj) 93 | { 94 | 95 | obj.getSpeed(); 96 | cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | //Program to appned data to a file and also reading and writing data to and from file using fstream 8 | 9 | 10 | int main() 11 | { 12 | fstream file("anish.txt", ios::in | ios::out | ios::app); //setting read, write and append modes of ios class 13 | //append will create a new file, if the file being opened does not exists 14 | 15 | if(!file.is_open()) 16 | { 17 | cout<<"File not found"< 2 | #include 3 | #include 4 | #include 5 | 6 | //program to read and write to a Binary File using get() and put() function 7 | 8 | using namespace std; 9 | int main() 10 | { 11 | fstream file; 12 | file.open("anish.bin",ios::binary| ios::in | ios::out | ios::trunc); 13 | 14 | if(!file.is_open()) 15 | { 16 | cout<<"Error, opening file"< 2 | #include 3 | 4 | //Program on File handling and opening and closing connections to a file stream 5 | using namespace std; 6 | 7 | 8 | int main() 9 | { 10 | //creating an object of class fstream to read or write to a file 11 | fstream file; 12 | file.open("anish.txt",ios::in | ios::out | ios::trunc); 13 | 14 | /*trunc is used in case if a file is not already existing, then it will create a new file for us, but if the file is already existing then 15 | it will simply remove the contents of the file, and create a new copy 16 | */ 17 | 18 | if(!file.is_open()) 19 | { 20 | cout<<"Error!, file not opened"< 2 | #include 3 | #include 4 | 5 | 6 | //program to read and write to a binary file using read() and write() methods 7 | 8 | using namespace std; 9 | 10 | class Person{ 11 | 12 | int age; 13 | char name[80]; 14 | 15 | public: 16 | Person() { 17 | strcpy(name,"noname"); 18 | age=0; 19 | } 20 | 21 | Person(const char *name, int age) 22 | { 23 | strcpy(this->name ,name); 24 | this->age = age; 25 | } 26 | 27 | 28 | void introduce() 29 | { 30 | cout<<"The name is "< 2 | #include 3 | 4 | using namespace std; 5 | 6 | //reading data from a file using ifstream class 7 | 8 | 9 | int main() 10 | { 11 | //creating an object of class ifstream 12 | ifstream file("anish.txt"); 13 | 14 | if(!file.is_open()) 15 | { 16 | cout<<"File not found"< 2 | #include 3 | 4 | //Program on File handling and opening and closing connections to a file stream 5 | using namespace std; 6 | 7 | //writing data to a file using oftream class object simply like a stream opt 8 | 9 | 10 | int main() 11 | { 12 | ofstream file("anish.txt"); //opeing connection to file using object of oftream class 13 | 14 | if(!file.is_open()) 15 | { 16 | cout<<"File not found"< 3 | #include 4 | 5 | using namespace std; 6 | 7 | void display(); //function prototype 8 | 9 | class Human { 10 | private: //private attr of the class 11 | int age; 12 | int salary; 13 | string name; 14 | public: 15 | Human(int iage,int isal,string iname) { 16 | age=iage; 17 | salary=isal; 18 | name=iname; 19 | } 20 | void tell(){ 21 | cout<name<<","<<"salary : "<salary<<", "<<"age:"<age< 2 | 3 | using namespace std; 4 | 5 | //demonstrates that const functions of a class can be overloaded using const type object of class 6 | 7 | class Person { 8 | 9 | public: 10 | int x=10;//now vlue of x is fixed and constant, and cannot be changed 11 | //during initialization the value of a const variable is fixed. 12 | 13 | void intro() const { 14 | cout<<"This is const intro"< 2 | 3 | //example program to show overriding of base class methods in derived class- 4 | 5 | //when methods in base class and in derived class have same signatures i.e same name, same return type and same no of args, then 6 | //the base class method is overidden by the derived class method-i.e when called using the derived class object, the derived class method will be called not base class. 7 | 8 | using namespace std; 9 | 10 | 11 | class Person { 12 | public: 13 | void intro() { 14 | cout<<"hello I am a person"<intro(); //derived class method is called , not base class . Although derived class has access to base class method too, but it is overidden 35 | 36 | cout<<"\n"; 37 | //to access the Base class overloaded method 38 | //use 39 | a->Person::intro(); 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /General Programs/ABCDPyramid.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | int main() 8 | { 9 | int n; 10 | 11 | 12 | cout<<"Enter the limit"<>n; 14 | 15 | char ch[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; 16 | 17 | for(int i = 0 ; i < n ; i++ ) 18 | { 19 | 20 | for(int j = 0 ; j < i ; j++) 21 | { 22 | 23 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | bool isAutomorphic(int n) 7 | { 8 | int sq = (n*n); 9 | int count = 0; 10 | int nn = n; 11 | //counting number of digits of n 12 | while(nn) 13 | { 14 | count++; 15 | nn /= 10; 16 | } 17 | int dig = pow(10,count); 18 | 19 | int d = (sq % dig); 20 | if(d==n) return true; 21 | 22 | else return false; 23 | } 24 | 25 | 26 | void nAutomorphic(int n) 27 | { 28 | for(int i = 1 ; i <= n; i++) 29 | { 30 | if(isAutomorphic(i)) cout< 2 | 3 | using namespace std; 4 | 5 | /*Program to find binomial coefficient C(n,k) i.e n c K-combination 6 | 7 | C(n,k) = n! / (n-k)! . k! = fact(n) / fact(n-k)*fact(k) 8 | 9 | 10 | 11 | */ 12 | 13 | int fact(int n) 14 | { 15 | if(n<=1) 16 | return n; 17 | 18 | else 19 | return n*fact(n-1); 20 | } //Time complexity = O(n) , S(n) = O(n) required by recursion call stack 21 | 22 | 23 | //function to find the binomial coefficient 24 | int BinCoeff(int n,int k) 25 | { 26 | if(n==k) 27 | return 1; 28 | if(k==1) 29 | return n; 30 | 31 | 32 | return ( fact(n) / (fact(n-k)*fact(k)) ) ; 33 | 34 | 35 | }//Time complexity of this method is O(n*k) , space = O(n) required by stack space 36 | 37 | 38 | 39 | //Method-2 Efficinet solution to find binomial coefficient 40 | 41 | int binomEfficient(int n,int k) 42 | { 43 | int res = 1; 44 | 45 | if(n==k) 46 | return 1; 47 | if(k==1) 48 | return n; 49 | 50 | //if k > n-k then k = n-k as // Since C(n, k) = C(n, n-k) 51 | if( k > n-k) 52 | k = n-k; 53 | 54 | //calculating C(n,k) = n!/ (n-k)! * k! 55 | for(int i = 0 ; i < k ; i++) 56 | { 57 | res *= (n-i); 58 | 59 | res /= (i+1); 60 | } 61 | 62 | return res; 63 | 64 | } //Time complexity = O(k) and aux space = O(1) 65 | 66 | 67 | int main() 68 | { 69 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | /*Program to print N-Bonacci numbers. 7 | when N=2 , then it becomes Fibonacci, ie sum of previous 2 numbers, 8 | when N = 3 the series becomes Tri-bonacci, i.e the next number is the sum of previous 3 numbers 9 | eg. N =3 , 0 0 1 1 2 4 7 13 24 .. .. 10 | 11 | */ 12 | 13 | 14 | // Function to print bonacci series 15 | void BonacciSeries(long n, int m) 16 | { 17 | 18 | // Assuming m > n. 19 | int a[m] = { 0 }; 20 | a[n - 1] = 1; 21 | a[n] = 1; 22 | 23 | // Uses sliding window 24 | for (int i = n + 1; i < m; i++) 25 | a[i] = 2 * a[i - 1] - a[i - n - 1]; 26 | 27 | // Printing result 28 | for (int i = 0; i < m; i++) 29 | cout << a[i] << " "; 30 | } 31 | //Time complexity = O(M), Space complexity = O(M) 32 | 33 | 34 | int main() 35 | { 36 | BonacciSeries(2,10);//fibonacci series 37 | cout< 2 | //example to represent call by value and call by reference of function calling 3 | 4 | using namespace std; 5 | 6 | //In call by value, a copy of actual(args which are passed when func is called) 7 | // arguments is passed to formal(args when defined a func) arguments of the called function and any change made to the 8 | //formal arguments in the called function have no effect on the values of actual arguments in the calling function. 9 | int SwapByVal(int a, int b) { 10 | 11 | int temp=a; 12 | a=b; 13 | b=temp; 14 | return (a,b); 15 | } 16 | 17 | 18 | //in call by reference we pass the location(address) of the actual arguments as formal arguments when calling function. So when a function is defined 19 | // we pass pointers as formal arguments as using the pointers we can easily indirectly manipulte the values of the actual(passed) arguments from within the func using their address 20 | int SwapByRef(int *a, int *b) { 21 | 22 | int temp = *a; 23 | *a=*b; 24 | *b=temp; 25 | 26 | return (*a,*b); 27 | } 28 | 29 | 30 | int main () { 31 | 32 | int a=10,b=20; 33 | 34 | SwapByVal(a,b); 35 | cout<<"a is : "< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | /*Program to find Ceiling and floor in an unsorted array 8 | Algorithm- 9 | The idea is to traverse array and keep track of two distances with respect to x. 10 | 1) Minimum distance of element greater than or equal to x. 11 | 2) Minimum distance of element smaller than or equal to x. 12 | Finally print elements with minimum distances. 13 | 14 | 15 | */ 16 | int f=0 ,c=0; 17 | 18 | void floorAndCeil(int *arr,int key, int n) 19 | { 20 | 21 | 22 | 23 | // Distances of current floor and ceiling 24 | int fDist = INT_MAX, cDist = INT_MAX; 25 | 26 | for (int i=0; i= key && cDist > (arr[i] - key)) 31 | { 32 | c = arr[i]; 33 | cDist = arr[i] - key; 34 | } 35 | 36 | // If current element is closer than 37 | // previous floor. 38 | if (arr[i] <= key && fDist > (key - arr[i])) 39 | { 40 | f = arr[i]; 41 | fDist = key - arr[i]; 42 | } 43 | } 44 | 45 | 46 | }//Time complexity = O(n) and space complexity = O(1) 47 | 48 | 49 | int main() 50 | { 51 | int arr[ ] = {9,1,23,2,10,8}; 52 | 53 | int size = sizeof(arr)/sizeof(arr[0]); 54 | 55 | floorAndCeil(arr,20,size-1); 56 | 57 | cout<<"Floor is: "< 2 | 3 | 4 | using namespace std; 5 | 6 | int fun(int n,int m) 7 | { 8 | int sum = n + m; 9 | int s = sum; 10 | int c1 = 0,c2=0; 11 | int nn = n; 12 | while(s /= 10) 13 | { 14 | c1++; 15 | 16 | 17 | } 18 | 19 | while(nn /= 10) 20 | { 21 | c2++; 22 | 23 | } 24 | 25 | if(c1==c2) return sum; 26 | 27 | else return n ; 28 | } 29 | 30 | int main() 31 | { 32 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | //Recrsive program to find Factorial of a number 7 | int factorial(int n) 8 | { 9 | // if(n==0) return 0; 10 | 11 | 12 | if(n==1) return 1; 13 | 14 | //otherwise, recursively find factorial of n* factorial(n-1) 15 | else 16 | return n*factorial(n-1); 17 | 18 | 19 | 20 | } 21 | 22 | 23 | int main() 24 | { 25 | 26 | cout< 2 | 3 | using namespace std; 4 | 5 | //printing the fibonacci sequence 6 | //next number p(n+1) = p(n) + p(n-1) 7 | 8 | #define ll long long 9 | 10 | 11 | //construct a recusion tree to better understand this concept- REcursive implementation is very inefficient for Fibonacci sequence and is an Exponential time algorithm-O(2^n) 12 | ll FibonacciRec(int n) 13 | { 14 | if (n==1 || n==2) 15 | { 16 | return 1; 17 | } 18 | 19 | else { 20 | 21 | return FibonacciRec(n-1) + FibonacciRec(n-2); 22 | } 23 | 24 | } 25 | /*Time comlexity eqn = T(n-1) + T(n-2) + O(1) , on solving the recurrence relation we get O(2^n) 26 | //What this means is, the time taken to calculate fib(n) is equal to the sum of time taken to calculate subproblems fib(n-1) and fib(n-2). 27 | This also includes the constant time to perform the previous addition-but the tight upper bound complexity is O((1.1680)^n) . 28 | */ 29 | 30 | int fibonacci(int n) { 31 | long long int a=0,b=1,c=0; 32 | 33 | for(int i=1 ; i < n ; i++) { 34 | 35 | 36 | c = a+b; 37 | a=b; 38 | b=c; 39 | 40 | //or b=a and then a=c 41 | // cout< 2 | 3 | using namespace std; 4 | 5 | 6 | void findBin(int num) 7 | { 8 | int bin; 9 | if(num==0) return ; 10 | 11 | if(num > 0) 12 | { 13 | 14 | bin = num%2; //can take values either 0 or 1 15 | 16 | //recursively find remainder of num which is halved in each iteration until it is < 0 17 | findBin(num/2); 18 | 19 | //print bin value in postorder 20 | cout<=2 ;i--) 31 | { 32 | findBin(i); 33 | cout<<" "; 34 | } 35 | } 36 | 37 | int main() 38 | { 39 | //findBin(3); 40 | 41 | PrintBinary(6); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /General Programs/FindingLargestUsingRecursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | int findLargest(int *arr,int low,int high ) { 7 | 8 | int max; 9 | //if array has size 1 10 | if(low==high) { 11 | return arr[low]; 12 | } 13 | 14 | else { 15 | max = findLargest(arr,low+1,high); 16 | 17 | if(arr[low]>max) { 18 | return arr[low]; 19 | } 20 | else { 21 | return max; 22 | } 23 | 24 | } 25 | 26 | 27 | } 28 | 29 | 30 | int main() { 31 | 32 | int arr[5]={1,2,3,4,10}; 33 | 34 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | 8 | enum flag{ 9 | const1,const2,const3,const4,const5 10 | }; 11 | 12 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | 10 | 11 | 12 | int main () { 13 | 14 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | //program to find whether a year is leap year or not. 8 | 9 | bool leapOrNot(long int year) 10 | { 11 | //if divisible by 4 12 | if(year % 4==0) 13 | return 1; 14 | 15 | //if it is divisible by 100, and not divisible by 400, then not a leap year 16 | if(year%100==0) 17 | { 18 | if(year%400==0) 19 | return 1; 20 | } 21 | 22 | return 0; 23 | } 24 | 25 | 26 | 27 | 28 | int main() 29 | { 30 | cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | long MedianDiff(int *v,int size) 10 | { 11 | vectors;//to store the differences 12 | int i = 0 ; 13 | int j = size-1; 14 | 15 | while(i i) 19 | { 20 | s.push_back(abs(v[i]-v[j--])); 21 | } 22 | 23 | j = size-1; 24 | i++; 25 | } 26 | 27 | //sorting the vector of differences to find the median 28 | stable_sort(s.begin(),s.end()); 29 | 30 | 31 | int start = 0; 32 | int end = s.size()-1; 33 | int mid = start + (end-start)/2; 34 | 35 | return s[mid]; 36 | 37 | } 38 | 39 | int main() 40 | { 41 | int v[] = {1,3,2,4}; 42 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | //the 2 arrays have equal sizes 7 | int MedianInUnion(vector &v1,vector&v2) 8 | { 9 | int i = v1.size()-1,j=v2.size()-1; 10 | int k = i + j -1 ; 11 | 12 | 13 | 14 | while(i>=0 && j>=0) 15 | { 16 | 17 | v1[k--] = (v1[i] >= v2[j]) ? v1[i--] : v2[j--]; 18 | 19 | } 20 | 21 | while(j>=0) 22 | v1[k--] = v2[j--]; 23 | 24 | 25 | int start = 0; 26 | int end = k; 27 | 28 | int mid = start + (end-start)/2; 29 | for(int i = start; i < end; i++) 30 | { 31 | cout<v1; 43 | vectorv2; 44 | 45 | v1.push_back(3); 46 | v1.push_back(2); 47 | v1.push_back(5); 48 | v1.push_back(1); 49 | 50 | v2.push_back(9); 51 | v2.push_back(7); 52 | v2.push_back(6); 53 | v2.push_back(10); 54 | 55 | MedianInUnion(v1,v2); 56 | } 57 | -------------------------------------------------------------------------------- /General Programs/MultiplyBy2usingleftshift.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int x; 6 | scanf("%d",&x); 7 | printf("%d",(x<<1)); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /General Programs/NeonNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | /*Program to find NEON NUMBER- A neon number is a nunber if the sum of digits of the square of the number n equals itself. 7 | 8 | example-9 , sq(9) = 81, 8+1 = 9 9 | */ 10 | 11 | bool NeonNumber(int n) 12 | { 13 | int sum=0; 14 | int sq = (n*n); //square of number 15 | int digit; 16 | 17 | //finding digits from the square and adding them up 18 | while(sq != 0) 19 | { 20 | int digit = sq%10; 21 | sq = sq /10; 22 | sum += digit; 23 | 24 | 25 | 26 | } 27 | 28 | //if the sum of digits equals the number itself then it is a neon number 29 | if(sum == n) 30 | { 31 | return true; 32 | } 33 | 34 | return false; 35 | 36 | 37 | 38 | } 39 | 40 | 41 | int main() 42 | { 43 | cout< 3 | 4 | int main() 5 | { 6 | int x; 7 | scanf("%d",&x); 8 | printf("%d",(x&1)); 9 | 10 | } 11 | 12 | -------------------------------------------------------------------------------- /General Programs/Palindrome2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | //Method-1 :Iterative method 8 | 9 | void Palindrome(string s) { 10 | 11 | int start = 0 ; 12 | 13 | int end = (s.length() - 1); 14 | 15 | 16 | while(start <= end) 17 | { 18 | if(s[start]==s[end]) 19 | { 20 | start++; 21 | end--; 22 | } 23 | 24 | //if the left and right values don't match , simply break out of while loop and test for base condition 25 | else { 26 | break; 27 | } 28 | 29 | } 30 | 31 | if(start < end) { 32 | 33 | cout<<"Not a palindrome"<&p) 48 | { 49 | 50 | 51 | 52 | //pushing contents of string to stack 53 | for(int i=0 ; i < s.length() ; i++) //O(n) 54 | { 55 | p.push(s[i]); //O(1) 56 | 57 | } 58 | 59 | //comparing the expression and top of stack 60 | // for(int i = 0 ; i < s.length() ; i++) 61 | // { 62 | // if(s[i] == p.top()) 63 | // { 64 | // 65 | // p.pop(); 66 | // 67 | // } 68 | // } 69 | 70 | int i=0; 71 | while( i < s.length() && s[i]==p.top()) //O(n) 72 | { 73 | p.pop(); //O(1) 74 | i++; 75 | 76 | } 77 | 78 | if(p.empty()) { 79 | cout<<"Palindrome string."<c; 92 | string s; 93 | 94 | getline(cin,s); 95 | 96 | 97 | PalindromeStack(s,c); 98 | 99 | 100 | 101 | return 0; 102 | } 103 | -------------------------------------------------------------------------------- /General Programs/PerfectNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | /*Program to find PERFECT NUMBER- a perfect number is a number whose factors leaving itself when added equals to the number itself. 8 | 9 | eg-6, its factors= 1,2,3 = 3+2+1=6 , 28 , factors(28) = 1,2,4,7,14 = 28 10 | 11 | to check if a number is a perfect number or not 12 | */ 13 | 14 | 15 | bool PerfectNumber( long int n) 16 | { 17 | long int factors=1; 18 | long int sum = 0; 19 | 20 | while(n > factors) 21 | { 22 | //if n is divisible by factors 23 | if(n%factors==0) 24 | { 25 | sum += factors; 26 | 27 | } 28 | 29 | //otherwise simply increment and again check 30 | factors++; 31 | } 32 | 33 | if(sum==n) 34 | { 35 | return true; 36 | } 37 | 38 | return false; 39 | 40 | } 41 | 42 | 43 | //function to find all the Perfect numbers till a range 44 | void PerfectNumbersInRange(int range) 45 | { 46 | int i=1; 47 | while(i<=range) 48 | { 49 | if(PerfectNumber(i)) 50 | { 51 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int a=10; 7 | int *ptr=&a; 8 | cout<<"Initially a: "<>*ptr; //input value which is indirectly manipulated 10 | cout<<"Using pointer manipulation, a becomes: "< 2 | 3 | using namespace std; 4 | //function to check whether a number is prime or not 5 | 6 | bool Isprime(int n) { 7 | 8 | //prime number- a number which is only divisible by itself and 1 9 | //The definition of a prime number is a positive integer that has exactly two positive divisors-which is 1 and the num itself. 10 | //However, 1 only has one positive divisor (1 itself), so it is not prime 11 | if(n <= 0) { 12 | 13 | 14 | cout<<"Enter a valid integer"< i) { 37 | // 38 | // if(n%i!=0) { 39 | // 40 | // return Isprime(n,++i); 41 | // 42 | // 43 | // } 44 | // 45 | // else { 46 | // cout<<"Not a prime"< 2 | 3 | using namespace std; 4 | 5 | //Recursive program to find if a number is prime number or not 6 | 7 | int PrimeRec(int n,int i=2) 8 | { 9 | //will recur until i < n and check for the condition defined inside 10 | if( n > i) 11 | { 12 | if(n%i!=0) 13 | { 14 | 15 | return PrimeRec(n,i++); 16 | 17 | 18 | } 19 | //case when n is divisible by i-//base condition 20 | else 21 | return 0; 22 | 23 | } 24 | 25 | //control comes here when above n > i becomes false 26 | return 1; 27 | 28 | 29 | } //TIME COMPLEXITY - O(n) 30 | 31 | 32 | int main() 33 | { 34 | 35 | cout< 2 | 3 | int CountSet(int n) 4 | { 5 | int count = 0; 6 | while(n) 7 | { 8 | if(n & 1) 9 | count ++; 10 | 11 | n = n >> 1; 12 | } 13 | 14 | return count; 15 | } 16 | 17 | int RangeQuery(int l,int r) 18 | { 19 | int count= 0 ; 20 | for(int i = l ; i <= r;i++) 21 | { 22 | if(CountSet(i)<=3) 23 | count++; 24 | } 25 | 26 | return count; 27 | } 28 | 29 | using namespace std; 30 | int main() 31 | { 32 | //code 33 | int t; 34 | 35 | cin>>t; 36 | for(int i = 0 ; i < t;i++) 37 | { 38 | int q; 39 | cin>>q; 40 | for(int j=0; j < q;j++ ) 41 | { 42 | int l,r; 43 | cin>>l>>r; 44 | 45 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | //this function returns the new size of the array after removing val 8 | int RemoveItem(int *nums,int val,int size) 9 | { 10 | 11 | int count=0; 12 | for(int i = 0 ; i < size; i++) 13 | { 14 | if(nums[i] != val) 15 | { 16 | nums[count++] = nums[i]; 17 | } 18 | 19 | 20 | } 21 | 22 | return count; 23 | } 24 | 25 | 26 | 27 | 28 | int main() 29 | { 30 | int arr[] = {1,2,3,3,5,2}; 31 | 32 | 33 | int size = (sizeof(arr)/sizeof(arr[0])); 34 | 35 | //ns is the new updated size of the array after removing the items 36 | int ns = RemoveItem(arr,2,size); 37 | 38 | for(int i = 0 ; i < ns ; i++) 39 | { 40 | cout< 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | 8 | 9 | //function to check if a number n is prime or not- 10 | bool isPrime(long n,int i=2) 11 | { 12 | if(n==1) 13 | return false; 14 | 15 | if(n > i) 16 | { 17 | if(n%i==0) 18 | return false; 19 | 20 | if(n%i!=0) 21 | { 22 | return isPrime(n,++i); 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | 29 | 30 | 31 | //function to store all numbers from 2 till n in a vector, and print only prime in this rang in reverse order 32 | void ReversePrime(long n) 33 | { 34 | vectorv; 35 | //vector to store the prime numbers 36 | int count = 0; 37 | if(!isPrime(n)) 38 | { 39 | cout<<"Not a prime number"<::reverse_iterator it; 49 | 50 | for(it = v.rbegin();it!=v.rend();++it) 51 | { 52 | //if numbers in vector are prime, then print them 53 | 54 | if(isPrime(*it)) 55 | { 56 | cout<<*it<<" "; 57 | count++; 58 | 59 | } 60 | 61 | 62 | 63 | } 64 | cout< 2 | #include 3 | 4 | //recursive program to find reverse of a string 5 | 6 | using namespace std; 7 | 8 | string ReverseRec(string str,int i,int j) 9 | { 10 | 11 | 12 | 13 | //base condition-terminating condition -recursion stops here 14 | if(i>j) return str; //oor when i==j 15 | 16 | else 17 | { 18 | //otherwise simply swap the characters until above base condition is rached i.e i>j 19 | swap(str[i],str[j]); 20 | 21 | return ReverseRec(str,i+1,j-1); 22 | } 23 | 24 | 25 | 26 | 27 | } 28 | 29 | 30 | int main() 31 | { 32 | string name ; 33 | name= "anish singh walia"; 34 | cout< 2 | 3 | using namespace std; 4 | 5 | string reverseVowels(string s) { 6 | int i = 0 ; 7 | int j = s.size()-1; 8 | 9 | 10 | 11 | while(i 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | using namespace std; 8 | 9 | //program to reverse Words of a sentence 10 | 11 | 12 | void ReverseWords(string &s) 13 | { 14 | int start = 0; 15 | int i = 0; 16 | 17 | //to remove spaces in the starting 18 | while( s[i] == ' ') s.erase(i, 1); 19 | 20 | 21 | reverse(s.begin(), s.end()); 22 | 23 | 24 | 25 | int size = s.size(); 26 | for(i = 0; i < size - 1; i++){ 27 | 28 | //removing empty spaces 29 | if( s[i] == ' '){ 30 | if( i == start ){ 31 | s.erase(i--,1); 32 | size--; 33 | } 34 | else{ 35 | reverse(s.begin()+start, s.begin()+i); 36 | start = i+1; 37 | } 38 | } 39 | } 40 | 41 | reverse(s.begin() + start, s.end()); 42 | cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /*Program to shuffle an array of size 2n, into format a1 b1 a2 b2 a3 b3 a4 b4 etc without using extra memory. 8 | This problem is similar to the queue interleaving problem- eg 1 2 3 4 5 6 7 8 = 1 5 2 6 3 7 4 8. 9 | 10 | 1)Using divide and conquer 11 | 2) using extra space -using queue interleaving solution 12 | */ 13 | 14 | void ShuffleArray(int *arr,int l , int h) 15 | { 16 | //finding mid index 17 | int mid = l + (h-l)/2; //mid index 18 | int prev= l +(mid-l)/2;// 19 | 20 | //base case 21 | if(l==h) return; 22 | 23 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | cout< 2 | #include 3 | #include 4 | 5 | 6 | using namespace std; 7 | 8 | //sorting a string in cpp 9 | 10 | 11 | int main() 12 | { 13 | string s = "anishwal"; 14 | 15 | //sort function to sort a string 16 | sort(s.begin(),s.end()); 17 | 18 | cout< 2 | 3 | using namespace std; 4 | 5 | void fun(int *x) { 6 | 7 | 8 | 9 | cout<<&x; 10 | } 11 | 12 | //void fun(int y[]) { 13 | // 14 | // cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | //program to find number of subarrays whose sum equals K 7 | 8 | //brute force appraoch 9 | //int subarraySum(vector& nums, int k) { 10 | // 11 | // 12 | // int count = 0 ; 13 | // for(int i = 0 ; i < nums.size() ; i++) 14 | // { 15 | // for(int j = i+1 ; j < nums.size(); j++) 16 | // { 17 | // int sum = 0 ; 18 | // for(int m = i ; m < j ; m++) 19 | // { 20 | // sum += nums[m]; 21 | // 22 | // if(sum == k) 23 | // count++; 24 | // } 25 | // } 26 | // 27 | // } 28 | // 29 | // return count; 30 | //} 31 | 32 | int subarraySum(vector& nums, int k) { 33 | 34 | int count = 0 ; 35 | 36 | for(int i = 0 ; i < nums.size(); i++) 37 | { 38 | int sum = 0 ; 39 | for(int j = i ; j < nums.size(); j++) 40 | { 41 | sum += nums[j]; 42 | if(sum == k) 43 | count++; 44 | } 45 | } 46 | 47 | return count; 48 | } 49 | //T(n) = O(n*n),space = O(1) 50 | 51 | int main() 52 | { 53 | vector v; 54 | 55 | v.push_back(1); 56 | v.push_back(1); 57 | v.push_back(1); 58 | v.push_back(2); 59 | 60 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | void substr(char *t,char *s,int pos,int len) 7 | { 8 | t[0] = '\0'; 9 | 10 | 11 | 12 | strncat(t,s+pos,len); 13 | } 14 | 15 | int main() 16 | { 17 | char s[] = "aaanish Singh"; 18 | char t[25]; 19 | 20 | substr(t,s,1,3); 21 | 22 | printf("%s",t); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /General Programs/TaylorSeries.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //program to find e^x using taylor series- 6 | 7 | 8 | //this program for larger values of y, appriximates e^x 9 | float exp(float x,int y) 10 | { 11 | float p,s; int i; 12 | 13 | for(s = 1 ,p=1,i=1; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | 9 | char *ptr; 10 | char name[100]; 11 | //arrays are always autmoatically passed by reference 12 | 13 | ptr = name; //ptr now stores address of name array, array's label itself acts as an address of the array 14 | int countv=0,countc=0; 15 | 16 | //will use the pointer to do all the ops, as char pointer and char array act as same thing 17 | 18 | gets(ptr);//reading the char 19 | 20 | for(int i=0;ptr[i]!='\0';i++) 21 | { 22 | 23 | if(isalpha(ptr[i])) { //only check for alphabets 24 | 25 | if(ptr[i]=='a'|| ptr[i]=='e' || ptr[i]=='i' || ptr[i]=='o' || ptr[i] =='u') { 26 | 27 | countv++; 28 | } 29 | else { 30 | countc++; 31 | } 32 | } 33 | } 34 | cout<<"The number of vowels are: "< 2 | #include 3 | 4 | /*Program demonstarting the XOR relation a XOR b = c, then to find sq(a) XOR sq(b) = c, then we can find b = sqrt( sq(a) XOR b ) 5 | eg- 11*11 XOR 12*12 = 233, then sqrt(11*11 XOR 233) = 12 6 | */ 7 | using namespace std; 8 | 9 | 10 | 11 | 12 | int XORops(int a,int c) 13 | { 14 | int sq = (a*a); 15 | 16 | int pro = (sq ^ c); 17 | 18 | return sqrt(pro); 19 | } 20 | 21 | 22 | int main() 23 | { 24 | cout< 2 | 3 | using namespace std;//assignning std to global namespace 4 | 5 | 6 | int main() { 7 | 8 | int mat[3][3],n,m; 9 | 10 | cout<<"Enter the order of matrix"<>n; 12 | cin>>m; 13 | 14 | cout<<"Enter the elements of matrix"<>mat[i][j]; 19 | } 20 | } 21 | 22 | 23 | cout<<"matrix is= "< 2 | #include 3 | #include //to use the strlen(char) function 4 | 5 | //implementing it using a C type string 6 | 7 | using namespace std; 8 | 9 | int palindrome(char *a) 10 | { 11 | int i=0; 12 | int j = strlen(a)-1; 13 | while(i<=j && a[i]==a[j]) { 14 | //true condition , simply change i and j indices 15 | i++; 16 | j--; 17 | } 18 | 19 | 20 | if(ij || exp[i]!=exp[j]) 42 | return false; 43 | 44 | 45 | if(exp[i]==exp[j]) 46 | return true; 47 | 48 | //otherwise simply keep checking for same digits by incrementing i and decrementing j 49 | if(i<=j) 50 | { 51 | return PalindromeRec(exp,i++,j--); 52 | } 53 | 54 | 55 | }//Time complexity = O(n), spcae complexity = O(n), for recursive call stack 56 | 57 | int main() { 58 | 59 | // palindrome("nitin"); 60 | // palindrome("anish"); 61 | 62 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | string reverse(string name) { 8 | 9 | 10 | 11 | int i=0; 12 | int j = name.size()-1; 13 | 14 | 15 | 16 | while(i<=j) { 17 | 18 | swap(name[i],name[j]); //swapping 19 | i++; 20 | j--; 21 | 22 | 23 | 24 | } 25 | 26 | 27 | return name; 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | } 37 | 38 | 39 | int main() { 40 | 41 | string name; 42 | getline(cin,name); 43 | cout<<"Reversed string is : "< 2 | 3 | using namespace std; 4 | 5 | 6 | //a function to print the size in bits 7 | //int size() 8 | //{ 9 | // int a = 1; 10 | // int size = 1; 11 | // while(a<<=1) 12 | // size++; 13 | // return size; 14 | //} 15 | 16 | 17 | int main () { 18 | 19 | long double a; 20 | 21 | //Idea is to calculate the address difference between two consecutive variables which are laid out continiously in memory 22 | //- the difference would be the size of that variable type 23 | 24 | cout<<"Address of a :"<<&a< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | //Program to demonstarte how to overload a generic function with a normal function-called Explicit specialization 8 | 9 | template void display(T x) 10 | { 11 | cout<<"Generic function called,x = "< void display (int x) 18 | { 19 | 20 | cout<<"Normal function called,x = "< 2 | 3 | using namespace std; 4 | 5 | 6 | //EXPLICIT SPECIALIZATION for generic classes 7 | 8 | 9 | 10 | //class which can work for any data type 11 | template class Info{ 12 | 13 | T x; 14 | 15 | public: 16 | Info(T x) 17 | { 18 | this->x = x; 19 | } 20 | 21 | 22 | void display() 23 | { 24 | cout<<"Generic class displays,x = "< class Info { 34 | 35 | int x; 36 | 37 | public: 38 | Info(int x) 39 | { 40 | this->x = x; 41 | } 42 | 43 | 44 | void display() 45 | { 46 | cout<<"The product is: "< obj1("anish"); 56 | 57 | Info obj2(2); 58 | 59 | Info obj3(34.22); 60 | 61 | 62 | obj2.display(); 63 | 64 | obj1.display(); 65 | 66 | obj3.display(); 67 | 68 | return 0; 69 | 70 | } 71 | -------------------------------------------------------------------------------- /Generic Programming/GenericClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | //Generic classes-classes which can work wiht multiple different datatypes 7 | 8 | template class Info{ 9 | 10 | t1 x; 11 | t2 y; 12 | 13 | int counter; 14 | 15 | public: 16 | //constructor declaration 17 | Info(t1 x , t2 y,int z) 18 | { 19 | this->x = x; 20 | 21 | this->y = y; 22 | 23 | counter=z; 24 | } 25 | 26 | 27 | void display() 28 | { 29 | cout< obj1(20,"anish",100); 42 | 43 | Info obj2(10.22,9.998,200); 44 | 45 | obj1.display(); 46 | 47 | obj2.display(); 48 | 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /Generic Programming/GenericClassDefaultArguments.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | //program to demonstrate how to pass default template arguments for a generic class 7 | 8 | 9 | template class Person{ 10 | 11 | t1 age; 12 | t2 name; 13 | 14 | public: 15 | Person(t1 age,t2 name) 16 | { 17 | this->age = age; 18 | this->name = name; 19 | } 20 | 21 | 22 | void introduce() 23 | { 24 | cout<<"The age is: "< obj1(20,"anish"); 35 | 36 | Person obj2(20.0099,"anish singh"); 37 | 38 | Person obj3("anish walia",25); 39 | 40 | 41 | obj1.introduce(); 42 | 43 | obj2.introduce(); 44 | 45 | obj3.introduce(); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Generic Programming/GenericFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | /*GENERIC finctions and template keyword to generate a general data type- 8 | Generic functions are functions which can operate on any type of data as argument which is passed at compile time. 9 | And to make a generic data type in cpp we use templates 10 | */ 11 | 12 | 13 | //making a generic data type T 14 | template 15 | 16 | void display(T x) 17 | { 18 | cout< 2 | 3 | using namespace std; 4 | 5 | //Program to demonstrate how to overload a generic function, like any normal function based on different number and type of arguents 6 | 7 | 8 | template void display(T x) 9 | { 10 | cout<<"Genric function with 1 argument called"< void display(t1 x, t2 y) 19 | { 20 | cout<<"generic function with 2 arguments called"< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | //Templates are an example of Compile time polymorphism-The compiler during compile time generates a different instances of the generic function for different data types 8 | //using which the generic function is called. And all the local variables inside that generic function will have a separate copy for every different data type called in function . 9 | 10 | template void fun(T x) 11 | { 12 | static int y = 0; 13 | 14 | cout<<++y< 2 | 3 | 4 | using namespace std; 5 | 6 | //inline namespaces- are simply nested namespaces which behave like their parent namespace member 7 | 8 | 9 | namespace AppVersion{ 10 | 11 | namespace Version1{ 12 | 13 | void display() 14 | { 15 | cout<<"This is version 1"< 2 | 3 | using namespace std; 4 | 5 | 6 | //Nested namespaces- we can nest a namesapce inside another namespace 7 | 8 | namespace parent { 9 | 10 | int x ; 11 | 12 | namespace child{ 13 | 14 | //overriding x 15 | int x=100; 16 | void display() 17 | { 18 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | //Un-named or anynymous namespaces. A namespcae which has no name. Each program/file has its own un-named namespace by default, and these unnamed namsapces are loacl 7 | //to a file and cannot span multiple files. We can also generate nested unnamed namespaces and also nest unnamed namesapces inside named namesapces or vice versa 8 | 9 | 10 | namespace { 11 | 12 | 13 | int factorial(int n) 14 | { 15 | 16 | if(n<=1) 17 | return n; 18 | 19 | else return n*factorial(n-1); 20 | } 21 | 22 | 23 | //nesting named namesapce inside an un-named namesapce 24 | namespace b{ 25 | 26 | int x; 27 | void fact() 28 | { 29 | cout< 2 | 3 | using namespace std; 4 | 5 | 6 | //A program/file can have multipe namespaces and each namesapce can be redefined multiple times 7 | 8 | namespace a { 9 | 10 | int x; 11 | void intro() 12 | { 13 | cout<<"Hi,! this is namespace a,and value of x = "< 2 | using namespace std; 3 | 4 | //Nested classes-classes defined inside a class 5 | 6 | 7 | class Person { 8 | public: 9 | string name; 10 | 11 | class Anish { 12 | public: 13 | string address; 14 | string city; 15 | string country; 16 | 17 | 18 | 19 | 20 | }; 21 | //we need to define object of nested class to access its members inside Parent class 22 | 23 | Anish a; //object created 24 | void getadd() 25 | { 26 | cout<<"Name: "< 2 | 3 | using namespace std; 4 | 5 | class human{ 6 | 7 | public: 8 | 9 | string name; 10 | void introduce(); 11 | 12 | 13 | }; 14 | 15 | 16 | //scope resolution operator-used to define the class methods outside the class 17 | void human :: introduce() 18 | { 19 | cout<<"Hello"<<" " <name="Mrinal"; 31 | obj2->introduce(); 32 | cout< 2 | 3 | 4 | //defining iperator function as a friend function of class which needs to be passed an reference to the class object to 5 | //access the class members 6 | 7 | 8 | //overloading short hand operators 9 | 10 | using namespace std; 11 | 12 | 13 | 14 | 15 | class Marks { 16 | int mark; 17 | public: 18 | Marks() { 19 | mark=0; 20 | } 21 | 22 | Marks(int m) { 23 | mark=m; 24 | } 25 | 26 | void getmark() { 27 | cout<<"Marks are: "< 2 | 3 | using namespace std; 4 | 5 | //overloading INCREMENT AND DECREMENT OPERATORS in CPP in POSTFIX form- we need to pass and argumene to the operator function 6 | 7 | // --x; means first decrement , then do something -this is prefix form 8 | 9 | // ++,-- are UNARY operators as they are performed on a single operand 10 | 11 | 12 | 13 | class Marks { 14 | int mark; 15 | public: 16 | Marks() { 17 | mark=0; 18 | } 19 | 20 | Marks(int m) { 21 | mark=m; 22 | } 23 | 24 | void getMark() { 25 | cout<<"Marks are: "< 2 | 3 | //overloading INCREMENT AND DECREMENT OPERATORS in CPP in PREFIX form 4 | 5 | // --x; means first decrement , then do something -this is prefix form 6 | 7 | // ++,-- are UNARY operators as they are performed on a single operand 8 | 9 | using namespace std; 10 | 11 | 12 | 13 | 14 | class Marks { 15 | int mark; 16 | public: 17 | Marks() { 18 | mark=0; 19 | } 20 | 21 | Marks(int m) { 22 | mark=m; 23 | } 24 | 25 | void getmark() { 26 | cout<<"Marks are: "< 2 | 3 | using namespace std; 4 | //operator overlaoding example 5 | 6 | class marks { 7 | 8 | public: 9 | marks() { 10 | intmark=0; 11 | extmark=0; 12 | } 13 | 14 | marks(int im,int em){ 15 | intmark=im; 16 | extmark=em; 17 | } 18 | 19 | int intmark; 20 | int extmark; 21 | void display(); 22 | 23 | //defining a operator function which return an object of type class marks 24 | //overloading the + operator method which takes argument as a object and returns an obj 25 | //now here I can overload any operator and inside the function implement any opeartion using any operator 26 | 27 | //let's overload '=' operator 28 | marks operator+(marks m) { 29 | marks temp; // a temperarory object 30 | temp.intmark= intmark + m.intmark; 31 | temp.extmark = extmark + m.extmark; 32 | return temp; 33 | } 34 | }; 35 | 36 | void marks::display() { 37 | cout<<"Internal Marks are: "< 2 | 3 | using namespace std; 4 | 5 | class Person { 6 | public : 7 | Person() { 8 | cout<<"Constructor of base class"< 2 | 3 | using namespace std; 4 | 5 | int main () { 6 | 7 | int *ptr,**ptr2, a=10; 8 | ptr=&a;//ptr stores address of a 9 | ptr2=&ptr; //ptr2 stores address of ptr, *ptr now print value at ptr 10 | //-ptr++; 11 | 12 | cout<<"Address of a "<<&a< 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int a=10; 7 | int *ptr=&a; //ptr refers a and stores its mem address 8 | 9 | cout< 2 | 3 | using namespace std; 4 | 5 | //POINTERS TO POINTERS 6 | 7 | int main() { 8 | 9 | int x=10; 10 | 11 | int *p=&x; //stores address of x; 12 | 13 | int **p1=&p;//stores or points/refers to address of p 14 | int ***p2=&p1;//stores and points/refers to address of p1 15 | 16 | cout<<&x< 2 | 3 | 4 | using namespace std; 5 | 6 | 7 | int main() 8 | { 9 | int arr[3][4] = { 10 | {1,2,4}, 11 | {2,3,4} , 12 | {5,6,7} }; 13 | 14 | 15 | cout< 2 | 3 | //POINTER AIRTHEMETIC - Only addition and substraction possible 4 | //TYPECASTING in POINTERS 5 | 6 | //SOME BASICS OF POINTERS 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | 12 | int a = 1025; 13 | //a is laid out in this way in memory 14 | // 00000000(Byte-4) 00000000(Byte-3) 00000100(Byte-2) 00000001(Byte-1) 15 | int* p; 16 | p=&a; //p stores address of 1 byte of a in memory , so p stores address of Byte-1 17 | cout< 2 | 3 | using namespace std; 4 | 5 | /*GENERIC POINTER or VOID POINTER 6 | 7 | it is a type of pointer which does not correspond to a particular datatype 8 | 1)A void pointer has no type 9 | 2)A void pointer cannot be dereferenced as it does not correspond and map to any datatype 10 | 3)Also void pointers do not allow pointer airthmetic 11 | 4)Void pointers can point to any memory chunk 12 | 5)Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. 13 | 14 | */ 15 | 16 | int main() { 17 | 18 | int a=100; 19 | int *p = &a; //base address of a 20 | 21 | void *p1; 22 | 23 | 24 | p1 = p; 25 | 26 | cout< 2 | #include 3 | using namespace std; 4 | 5 | 6 | int main() { 7 | 8 | int arr[5],*ptr; 9 | 10 | cout<<*&arr< 2 | 3 | using namespace std; 4 | 5 | 6 | //a function to print the size in bits 7 | //int size() 8 | //{ 9 | // int a = 1; 10 | // int size = 1; 11 | // while(a<<=1) 12 | // size++; 13 | // return size; 14 | //} 15 | 16 | 17 | int main () { 18 | 19 | long double a; 20 | 21 | //Idea is to calculate the address difference between two consecutive variables- the difference would be the size of that variable type 22 | 23 | cout<<"Address of a :"<<&a< 2 | 3 | using namespace std; 4 | //CONDITIONAL COMPILATION MACROS 5 | 6 | #define WIN 1 7 | #define LIN 1 8 | #define MAC 3 9 | 10 | 11 | #define OS MAC 12 | int main() 13 | { 14 | 15 | 16 | #if OS == WIN 17 | cout<<"Windows OS macro"< 2 | 3 | using namespace std; 4 | 5 | 6 | //macro which finds the greater of 2 numbers 7 | #define MAX(a,b) ((a 2 | 3 | //PROGRAM TO SHOW DIFFERENT PRE-DEFINED C++ PRE-PROCESSORS AND LINE DIRECTIVE 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | 10 | cout<<"The line number is:"<<__LINE__< 2 | 3 | 4 | //the below defined macros are called object like macros 5 | #define ANISH "anish" 6 | 7 | #define ONE 1 8 | #define TWO ONE+ONE 9 | #define THREE TWO+ONE 10 | 11 | 12 | 13 | using namespace std; 14 | 15 | 16 | //MACRO- its is simply a fragment of code with a name 17 | //Object like macro in cpp 18 | 19 | 20 | 21 | int main() 22 | { 23 | cout< 2 | 3 | //using ifdef and ifndef macros in cpp 4 | 5 | /* 1) ifdef= if a macro is defined then do something 6 | 2) ifndef = if macro is not defined then do something 7 | */ 8 | 9 | using namespace std; 10 | 11 | #define ANISH 1 12 | 13 | int main() 14 | { 15 | #ifdef ANISH 16 | cout<<"ANISH macro is defined"< 2 | using namespace std; 3 | 4 | #include "MyInfoCLass.cpp" 5 | 6 | 7 | /*program to demonstrate the usage of #include pre-processor directive in CPP to include and load custom build source files(classes) 8 | 9 | Pre-processor- is simply a software of a small program which run before the compilation of the program 10 | Pre-processor directive-: using a diretive we can tell a the compiler to compile certain parts of our program based on our instruction 11 | */ 12 | 13 | 14 | 15 | int main() 16 | { 17 | Person Anish(20,"Anish"); 18 | 19 | Anish.getInfo(); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /PrivateInheritence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Person { 7 | public : 8 | string name; 9 | display(string iname) { 10 | name=iname; 11 | } 12 | }; 13 | 14 | //private inheritence-now the base class members act as private member on derived class-not accessible outside the class 15 | class Student : private Person { 16 | public: 17 | Person :: name; //becomes public 18 | Person::display; 19 | setName() { 20 | cout< 2 | 3 | 4 | using namespace std; 5 | 6 | //when we use a referece to refer to a variable, changes made to the reference var is reflected in referred var and vice versa is also true i.e 7 | //changes made to the referred var makes changes in the reference variable too. 8 | 9 | int main() 10 | { 11 | int x = 20; 12 | 13 | int &ref = x; //now ref and x both have same addresses 14 | 15 | cout<<"Address of ref is "<<&ref<<", and address of x "<<&x<<" are same."< 2 | 3 | using namespace std; 4 | 5 | 6 | /* 7 | Templates are expended at compiler time. This is like macros. The difference is, compiler does type checking before template expansion. 8 | The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class. 9 | */ 10 | 11 | 12 | template 13 | 14 | T Swap(T *a, T *b) { 15 | 16 | T temp = *a; 17 | *a=*b; 18 | *b=temp; 19 | } 20 | 21 | template 22 | 23 | T max(T a, T b , T c) { 24 | 25 | if(a > b && a > c) return a; 26 | 27 | if(b>a && b>c) return b; 28 | 29 | if(c>a && c>b) return c; 30 | } 31 | 32 | 33 | int main () 34 | { 35 | // int a=10,b=20; 36 | // string a1 = "Anish", b1 = "mrinal"; 37 | // 38 | // //call by reference 39 | // Swap(&a,&b); 40 | // 41 | // cout<<"a :"<(10,12,100); 50 | cout<('a','b','z'); 52 | 53 | 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /StaticClass.cpp: -------------------------------------------------------------------------------- 1 | //static variable and static member methods 2 | #include 3 | 4 | 5 | using namespace std; 6 | 7 | class Human { 8 | public: 9 | static int scount;//cannot be defined inside a class 10 | int count=0; 11 | //constructor 12 | Human() { 13 | scount++; 14 | count++; 15 | cout<<"Number of static humans"<<" "< 2 | 3 | using namespace std; 4 | void display(); //function prototyping 5 | 6 | int main() 7 | { 8 | display(); 9 | display(); 10 | display(); 11 | display(); 12 | display(); 13 | } 14 | 15 | void display(){ 16 | static int counter=0;//a variable which is initialized only once at the start of execution of program, 1 copy is maintained 17 | int count=0; 18 | cout<<"Function called"<<" "<< ++counter<<" "<<"Times"< 2 | // use of this keyword- 3 | 4 | using namespace std; 5 | 6 | //this pointer in cpp is used to refer to invoke a object or store address of a class object 7 | //this pointer - can be used by a 0bject to point/refer and access its own address. 8 | 9 | class Person { 10 | 11 | private: 12 | int age; 13 | public: 14 | 15 | void setAge(int age) { 16 | 17 | this->age = age;//this used to access the address of object, so that compiler cannot 18 | //be confused 19 | //this variale used to retrive the objects's age variable 20 | 21 | 22 | } 23 | void getage() { 24 | cout<<"My age is "<setAge(20)< 2 | 3 | using namespace std; 4 | 5 | //Virtual destructors 6 | 7 | class Person { 8 | public: 9 | Person(){ 10 | cout<<"Person called"< 2 | 3 | using namespace std; 4 | 5 | //inheritence of virtual method attributes, and virtual functions and hierarchy of class 6 | 7 | class Person { 8 | public: 9 | virtual void intro() { 10 | cout<<"Hi I am a person"<intro(); //function of derived class will be executed 38 | 39 | } 40 | 41 | 42 | int main() 43 | { 44 | 45 | Person *p1,*p2; 46 | Anish a; 47 | Mrinal m; 48 | p1=&a; // pointer p1 of type Person refers the derived(Anish class) object 49 | p2=&m; //pointer p2 of type Person refers to the derived class of Anish ie Mrinal 50 | 51 | p1->intro(); 52 | p2->intro(); 53 | 54 | // getIntro(p); //person class method called 55 | getIntro(&a); // Anish class overridden function called 56 | getIntro(&m); // Mrinal class overridden function called 57 | 58 | //without declaring a virtual base class function,the 3 above all function calls would return "Hi I am a person" i.e method of base class due 59 | //to static binding-binding during compiletime 60 | 61 | 62 | 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /VirtualFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //RUNTIME POLYMORPHISM - Virtual functions are used to achieve runtime polymorphism. It is achieved by function overriding(re-defination) 3 | // of base class method which is re-defined in a derived class. 4 | 5 | //Then a pointer of type base class is created which refers to derived class object 6 | //and the base method is called , which actually executes the derived class version 7 | //method. 8 | //Dynamic binding is done i.e during runtime 9 | 10 | using namespace std; 11 | 12 | class Person { 13 | public: 14 | //does runtime binding of intro() based on the type of object is used to invoke the method 15 | void virtual intro() { 16 | cout<<"Hello I am a Person"<intro();//intro() method of class Anish called 51 | p2->intro();//intro() method of class Mrinal called 52 | // a.intro(); 53 | // getIntro(a);//without virtual base function , it would have printed the base method value 54 | // getIntro(m); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /basic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class human{ 6 | 7 | public: 8 | 9 | string name; 10 | void introduce(); 11 | 12 | 13 | }; 14 | 15 | 16 | //scope resolution operator-used to define the class methods outside the class 17 | void human :: introduce() 18 | { 19 | cout<<"Hello"<<" " <name="Mrinal"; 31 | obj2->introduce(); 32 | cout< 2 | 3 | using namespace std; 4 | 5 | class Human { 6 | string name; 7 | 8 | }; 9 | 10 | string Human :: name="Anish"; 11 | 12 | 13 | int main() 14 | { 15 | Human anish; 16 | anish.name; 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /constClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //const objects and const member functions 6 | 7 | class Person { 8 | public: 9 | //const class data member 10 | const int age=20;//has to be initialized, when declared, cannot be initialized inside a constructor 11 | string name; 12 | //constructor 13 | Person(int iage,string iname){ 14 | 15 | // age=iage; initializing const data age using constructor produces error 16 | 17 | name = iname; 18 | } 19 | 20 | void getage() const { 21 | 22 | cout<<"My age is-"< 3 | 4 | using namespace std; 5 | 6 | 7 | class human 8 | { 9 | public: 10 | human() { 11 | age=10; 12 | name="Anish"; 13 | cout<<"Default Constructor is called"<>age; 30 | return age; 31 | 32 | } 33 | string getName() 34 | { 35 | 36 | cin>>name; 37 | return name; 38 | 39 | }*/ 40 | 41 | private: 42 | int age; 43 | string name; 44 | 45 | 46 | }; 47 | 48 | 49 | int main() { 50 | human obj;//constructor is called as soon as an object is created 51 | //default constructor called 52 | obj.introduce(); 53 | 54 | human obj2;//arguments passed to the object 55 | //constructor overloaded 56 | 57 | obj2.introduce(); 58 | } 59 | -------------------------------------------------------------------------------- /constructors.cpp: -------------------------------------------------------------------------------- 1 | //constructors example 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | class human 8 | { 9 | public: 10 | human() { 11 | int age=10; 12 | string name="Anish"; 13 | cout<<"Constructor is called"<>age; 24 | return age; 25 | 26 | } 27 | string getName() 28 | { 29 | 30 | cin>>name; 31 | return name; 32 | 33 | } 34 | 35 | 36 | int age; 37 | string name; 38 | 39 | 40 | }; 41 | 42 | class anish : private human { 43 | public: 44 | human::age; 45 | human::name; 46 | anish () { 47 | cout<<"Anish constructor called"<introduce(); 61 | anish A; 62 | A.intro(20,"anish"); 63 | } 64 | -------------------------------------------------------------------------------- /constructors.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anishsingh20/Programming-in-Cpp/de5dfecb715ce6ed9a59d54aedc1aab4f06703a3/constructors.exe -------------------------------------------------------------------------------- /defaultConstructor.cpp: -------------------------------------------------------------------------------- 1 | //constructors example 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | class human 8 | { 9 | public: 10 | 11 | //default values of the constructor params 12 | human(int iage=19,string iname="Mrinal") { 13 | age=iage; 14 | name=iname; 15 | cout<<"Object created with default constructor values"<>age; 26 | return age; 27 | 28 | } 29 | string getName() 30 | { 31 | 32 | cin>>name; 33 | return name; 34 | 35 | }*/ 36 | 37 | private: 38 | int age; 39 | string name; 40 | 41 | 42 | }; 43 | 44 | 45 | int main() { 46 | human obj;//constructor is called as soon as an object is created 47 | obj.introduce(); 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /destructor.cpp: -------------------------------------------------------------------------------- 1 | //constructors example 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | class human 8 | { 9 | public: 10 | human() { //constructor 11 | age=20; 12 | name="Anish"; 13 | cout<<"Default Constructor is called"<introduce(); 45 | 46 | //deallocating the memory allocated to the object 47 | delete obj; 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /friendClass.cpp: -------------------------------------------------------------------------------- 1 | //friend class 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void display(); //function prototype 8 | 9 | class Human { 10 | private: //private attr of the class 11 | int age; 12 | int salary; 13 | string name; 14 | public: 15 | Human(int iage,int isal,string iname) { 16 | age=iage; 17 | salary=isal; 18 | name=iname; 19 | } 20 | void tell(){ 21 | cout<name<<","<<"salary : "<salary<<", "<<"age:"<age<display(obj); 50 | 51 | return 0; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /memoryDeallocationusingDestructor.cpp: -------------------------------------------------------------------------------- 1 | //destructor example 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | class human 9 | { 10 | public: 11 | human(int iage,string iname) { //constructor 12 | 13 | //pointers to a memory location/dynamic memory allocation 14 | name = new string; 15 | age = new int; 16 | 17 | *age = iage; //assigning value to the pointers 18 | *name= iname; 19 | 20 | 21 | 22 | 23 | cout<<"Default Constructor is called"<introduce(); 60 | 61 | //deallocating the memory allocated to the object 62 | delete obj; 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /multipleInheritence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class father { 6 | public: 7 | int height; 8 | father(int ht) { 9 | height=ht; 10 | 11 | cout<<"Father constructor called"< 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Shape { 7 | 8 | //all public members will now be protected members of subclass 9 | public: 10 | int side; 11 | int getArea(); 12 | int volume(); 13 | }; 14 | 15 | 16 | //Protected inheritence-public and protected members of parent class act as protected members of child class-i.e accessible only inside the subclass 17 | class square : private Shape { 18 | public: 19 | 20 | //constructor 21 | square(int a) { 22 | side=a; 23 | } 24 | 25 | 26 | //inherited from Shape(base) class 27 | void getArea() { 28 | 29 | cout<<"Area is: "<getArea(); 45 | s->volume(); 46 | s->perm(); 47 | } 48 | -------------------------------------------------------------------------------- /publicInheritence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Shape { 7 | 8 | 9 | 10 | public: 11 | int side; 12 | int getArea(); 13 | int volume(); 14 | }; 15 | 16 | 17 | //PUBLIC inheritence-public members of parent class act as public members of child class 2) Protected member of parent class, as protected member of child class 18 | 19 | class square : protected Shape { 20 | public: 21 | //constructor 22 | square(int a) { 23 | side=a; 24 | } 25 | 26 | 27 | //inherited from Shape(base) class 28 | void getArea() { 29 | 30 | cout<<"Area is: "< 2 | 3 | using namespace std; 4 | 5 | 6 | class Person{ 7 | 8 | int x; 9 | 10 | public: 11 | Person() { 12 | x = 0; 13 | } 14 | 15 | int fun() 16 | { 17 | return this->x; 18 | 19 | } 20 | 21 | 22 | //this pointer is unavailable for static member functions, as static members function can be called without using class object. 23 | //works fine 24 | void fun2() 25 | { 26 | cout<<"member function"<fun(); 28 | } 29 | 30 | //static member function 31 | static void fun3(Person &obj); 32 | 33 | }; 34 | 35 | 36 | //static member function can be defined outside class and don't need an object to called. 37 | 38 | void Person::fun3(Person &obj) 39 | { 40 | cout<<"static member function"<fun(); //produces error 43 | 44 | 45 | //works fine 46 | cout< 2 | 3 | using namespace std; 4 | 5 | /* destructor and this pointer- 6 | 7 | 'delete this' inside a destructor or any member function 8 | only works for objects created using new keyword. 9 | 10 | */ 11 | class Person{ 12 | 13 | int x; 14 | 15 | public: 16 | Person() { 17 | 18 | cout<<"Constructor called"<destroy(); 41 | 42 | 43 | 44 | 45 | } 46 | --------------------------------------------------------------------------------