├── Sort ├── Heap_Sort │ ├── README.md │ └── heap-sort.cpp ├── Radix_Sort │ └── README.md ├── Bubble_Sort │ ├── README.md │ └── bubble.c ├── Merge_Sort │ ├── README.md │ └── MergeSort.cpp ├── Quick_Sort │ ├── README.md │ └── quickSort.cpp ├── Topological Sort │ ├── README.md │ └── Topological_sort.cpp ├── Selecton_Sort │ ├── Selection_Sort.c │ └── README.md ├── README.md └── Insertion_Sort │ ├── InsertionSort.cpp │ └── README.md ├── Search ├── Jump_Search │ └── README.md ├── Exponential_Search │ └── README.md ├── Interpolation_Search │ └── README.md ├── Linear_Search │ ├── README.md │ └── linear.c ├── README.md └── Binary_Search │ ├── README.md │ └── binary.c ├── _config.yml ├── .gitignore ├── IntroToOOP ├── a.out ├── classTest │ ├── a.out │ ├── sample1.cpp │ ├── sample5.cpp │ ├── sample2.cpp │ ├── sample4.c │ ├── sample6.cpp │ ├── sample3.cpp │ ├── sample7.cpp │ └── README.md ├── inheritance │ ├── a.out │ ├── single.o │ ├── multiple.out │ ├── multiple.cpp │ ├── multilevel.cpp │ ├── hierarchical.cpp │ ├── single.cpp │ └── hybrid.cpp ├── vector.cpp ├── funOver.cpp ├── classTemplate.cpp ├── dynAlloc.cpp ├── friend.cpp ├── tempAdd.cpp ├── IntroToOOPS.cpp ├── abstract.cpp ├── dynamicObject.cpp ├── class1.cpp ├── dynamicArray.cpp ├── opOver.cpp ├── virtual.cpp ├── fc.cpp ├── opOverUnary.cpp ├── copy.cpp ├── template.cpp ├── incrementOver.cpp ├── tryCatch.cpp ├── Intro.md └── README.md ├── reviseC ├── TAT1 │ ├── ques4 │ ├── ques4.o │ ├── ques2.c │ ├── ques5.c │ ├── ques3.cpp │ ├── ques1.cpp │ ├── ques4.cpp │ └── README.md ├── ReviseStruct │ ├── a.out │ ├── ques3.c │ ├── ques4.c │ ├── ques1.c │ ├── ques2.c │ ├── ques5.c │ └── README.md ├── ReviseLoops │ ├── ques2.c │ ├── ques1.c │ ├── ques5.c │ ├── ques3.c │ ├── ques4.c │ ├── ques6.c │ └── README.md ├── ReviseConditional │ ├── ques3.c │ ├── ques2.c │ ├── ques5.c │ ├── ques1.c │ ├── ques4.c │ └── README.md ├── findsin.c ├── si.c ├── sum1l.c ├── findSumSeries.c ├── factorial.c ├── sumDig.c ├── armstrong.c ├── vowels.c ├── fibonacci.c ├── prime.c ├── sumOfElements.c ├── iptillo.c ├── palindrom.c ├── arrayDup.c ├── arrayip.c ├── ArrayReversal.c ├── DOB.c ├── ReviseArrays │ ├── ques2.c │ ├── ques4.c │ ├── ques3.c │ ├── ques1.c │ ├── ques5.c │ └── README.md ├── ans1.c ├── arraySum.c ├── ansPrime.c ├── ans2.c ├── arrayAsString.c ├── ques4.c └── README.md ├── pointersInC ├── pointer.c ├── swapUsingPointer.c ├── callloc.c ├── malloc.c ├── PointToArray.c └── README.md ├── LICENSE ├── README.md ├── Structures ├── nstruct.c ├── struct.c ├── structinfunVal.c ├── structinfun.c ├── README.md └── practiseStruct.c └── CODE_OF_CONDUCT.md /Sort/Heap_Sort/README.md: -------------------------------------------------------------------------------- 1 | Content -------------------------------------------------------------------------------- /Sort/Radix_Sort/README.md: -------------------------------------------------------------------------------- 1 | Content -------------------------------------------------------------------------------- /Search/Jump_Search/README.md: -------------------------------------------------------------------------------- 1 | Content -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /Search/Exponential_Search/README.md: -------------------------------------------------------------------------------- 1 | Content -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .idea 3 | *.out 4 | *.o -------------------------------------------------------------------------------- /Search/Interpolation_Search/README.md: -------------------------------------------------------------------------------- 1 | Content -------------------------------------------------------------------------------- /IntroToOOP/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/IntroToOOP/a.out -------------------------------------------------------------------------------- /reviseC/TAT1/ques4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/reviseC/TAT1/ques4 -------------------------------------------------------------------------------- /Sort/Bubble_Sort/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort 2 | 3 | ## [Bubble Sort C implementation](bubble.c) -------------------------------------------------------------------------------- /reviseC/TAT1/ques4.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/reviseC/TAT1/ques4.o -------------------------------------------------------------------------------- /IntroToOOP/classTest/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/IntroToOOP/classTest/a.out -------------------------------------------------------------------------------- /Sort/Merge_Sort/README.md: -------------------------------------------------------------------------------- 1 | # Merge Sort 2 | 3 | ## [Merge Sort C++ implementation](Merge_Sort.cpp) 4 | -------------------------------------------------------------------------------- /reviseC/ReviseStruct/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/reviseC/ReviseStruct/a.out -------------------------------------------------------------------------------- /IntroToOOP/inheritance/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/IntroToOOP/inheritance/a.out -------------------------------------------------------------------------------- /Sort/Quick_Sort/README.md: -------------------------------------------------------------------------------- 1 | # Quick Sort 2 | 3 | ## [Quick Sort C++ implementation](QuickSort.cpp)Content 4 | -------------------------------------------------------------------------------- /IntroToOOP/inheritance/single.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/IntroToOOP/inheritance/single.o -------------------------------------------------------------------------------- /IntroToOOP/inheritance/multiple.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MadhavBahl/OOPS/HEAD/IntroToOOP/inheritance/multiple.out -------------------------------------------------------------------------------- /Sort/Topological Sort/README.md: -------------------------------------------------------------------------------- 1 | # Topological Sort 2 | Advanced Sorting 3 | 4 | # Input format 5 | n=no. of vertices , m input edges 6 | 7 | 6 6 <- n,m 8 | 5 2 <-u,v edge from u to v 9 | 5 0 <-u,v 10 | 4 0 .. 11 | 4 1 .. 12 | 2 3 .. 13 | 3 1 <-u,v 14 | 15 | 16 | ## [Topological Sort Implementation](TopologicalSort.cpp) 17 | -------------------------------------------------------------------------------- /IntroToOOP/vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main () { 6 | vector random; 7 | int n; 8 | cout<<"Enter the value of n: "; 9 | cin>>n; 10 | for(int i=0;i 6 | int main () { 7 | int n,i,j; 8 | scanf("%d", &n); 9 | for (i=1;i<=n;i++) { 10 | for(j=n;j>=i;j--) 11 | printf("*"); 12 | printf("\n"); 13 | } 14 | } -------------------------------------------------------------------------------- /reviseC/ReviseConditional/ques3.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 3 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | int main () { 7 | int x,y,z,numt,nume,amt; 8 | scanf("%d %d %d", &x, &y, &z); 9 | z *= 6; 10 | numt = z/40; 11 | nume = z%40; 12 | amt = numt*x + nume*y; 13 | printf("%d", amt); 14 | } -------------------------------------------------------------------------------- /pointersInC/pointer.c: -------------------------------------------------------------------------------- 1 | /* ==================== */ 2 | /* ===== Pointers ===== */ 3 | /* ==================== */ 4 | #include 5 | int main() { 6 | int a=5,b=10,**temp; 7 | int *P; 8 | P=&a; 9 | temp=&P; 10 | printf("\naddress of a = value of P: %u",P); 11 | printf("\naddress of P: %u",temp); 12 | printf("\nValue of a: %d",a); 13 | printf("\nValue of *P: %d",*P); 14 | //printf("\nValue of *a: %d",*a); 15 | } 16 | -------------------------------------------------------------------------------- /IntroToOOP/funOver.cpp: -------------------------------------------------------------------------------- 1 | /* =========================== */ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Example 1 7 | int square (int x) { 8 | return x*x; 9 | } 10 | double square (double x) { 11 | return x*x; 12 | } 13 | char* square (char x) { 14 | return "No Square For Characters"; 15 | } 16 | 17 | int main () { 18 | cout< the element does not exist 9 | ``` 10 | 11 | ## [Linear Search C implementation](linear.c) -------------------------------------------------------------------------------- /reviseC/findsin.c: -------------------------------------------------------------------------------- 1 | /* ========================= */ 2 | /* ===== Find sin(1/x) ===== */ 3 | /* ========================= */ 4 | 5 | #include 6 | #include 7 | 8 | int main() { 9 | float x,res; 10 | printf("Enter the value of x: "); 11 | scanf("%f",&x); 12 | if(x == 0 ) printf("x should not be equal to 0"); 13 | else { 14 | res=1/x; 15 | res=sin(res); 16 | printf("The value of sin(1/x) = %0.4f",res); 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /IntroToOOP/classTemplate.cpp: -------------------------------------------------------------------------------- 1 | /* ================================================================ */ 2 | /* ===== A template to return the maximum of 3 given elements ===== */ 3 | /* ================================================================ */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | template 9 | class sum { 10 | T a,b; 11 | public: 12 | void add() { 13 | cout<<"Sum is: "<< a+b; 14 | } 15 | }; 16 | 17 | int main () { 18 | sum 19 | } -------------------------------------------------------------------------------- /IntroToOOP/dynAlloc.cpp: -------------------------------------------------------------------------------- 1 | /* ==================================================================== */ 2 | /* ===== A simple program to show use of new and delete operators ===== */ 3 | /* ==================================================================== */ 4 | 5 | #include 6 | using namespace std; 7 | int main () { 8 | double *ptr = NULL; 9 | ptr = new double; 10 | *ptr = 123.4212; 11 | cout<< "Value of ptr: " << *ptr<< endl; 12 | delete ptr; 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Search/README.md: -------------------------------------------------------------------------------- 1 | # Searching Algorithms 2 | In computer science, a search algorithm is any algorithm which solves the Search problem, namely, to retrieve information stored within some data structure, or calculated in the search space of a problem domain. 3 | 4 | ### Some commonly used searching algorithms 5 | 1. [Linear Search](./Linear_Search)
6 | 2. [Binary Search](./Binary_Search) 7 | 3. [Jump Search]() 8 | 4. [Interpolation Search]() 9 | 5. [Exponential Search]() 10 | 11 | [Go Back](./..){: .btn} 12 | -------------------------------------------------------------------------------- /reviseC/ReviseConditional/ques2.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 2 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | int main () { 7 | int num,sq,sum=0; 8 | scanf("%d", &num); 9 | 10 | while( num > 0 ) { 11 | sq = (num%10); 12 | sum += sq*sq; 13 | num = num/10; 14 | } 15 | 16 | if ( sum%10 == 0 ) printf("Valid"); 17 | else printf("Invalid"); 18 | return 0; 19 | } -------------------------------------------------------------------------------- /reviseC/ReviseLoops/ques1.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 1 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | int main() { 7 | int n,i,j; 8 | scanf("%d", &n); 9 | for(i=1;i<=n;i++) { 10 | for(j=1;j<=n;j++) { 11 | if(j 6 | 7 | int euclid (int a, int b) { 8 | int r; 9 | r=a%b; 10 | while(r != 0) { 11 | a=b; 12 | b=r; 13 | r=a%b; 14 | } 15 | return b; 16 | } 17 | 18 | int main () { 19 | int a,b,gcd; 20 | scanf("%d %d", &a, &b); 21 | gcd = euclid(a,b); 22 | printf("The GCD of these two numbers is: %d\n", gcd); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /reviseC/si.c: -------------------------------------------------------------------------------- 1 | /* =============================================== */ 2 | /* ===== Program to calculate Simple Intrest ===== */ 3 | /* =============================================== */ 4 | #include 5 | int main() { 6 | float p,r,t,si; 7 | printf("Enter the principle amount: "); 8 | scanf("%f",&p); 9 | printf("Enter the Rate of intrest: "); 10 | scanf("%f",&r); 11 | printf("Enter the Time period: "); 12 | scanf("%f",&t); 13 | si=p*r*t/100; 14 | printf("The simple initrest is: %0.2f",si); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /reviseC/sum1l.c: -------------------------------------------------------------------------------- 1 | /* ======================================= */ 2 | /* ===== Sum of first and last digit ===== */ 3 | /* ======================================= */ 4 | 5 | #include 6 | 7 | int main() { 8 | int num,temp,rem,sum=0; 9 | printf("Enter the number: "); 10 | scanf("%d",&num); 11 | sum += num%10; 12 | while(num > 0) { 13 | rem = num%10; 14 | num = num/10; 15 | if(num == 0) 16 | sum+=rem; 17 | } 18 | printf("Sum of first and last digit(s) is: %d",sum); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /reviseC/ReviseConditional/ques5.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 4 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | int main () { 7 | char chr; 8 | scanf("%c", &chr); 9 | if ((chr>=65 && chr<=90) || (chr >= 97 && chr <= 122)) 10 | printf("You have entered an alphabet"); 11 | else if ( chr >= 48 && chr <= 57) 12 | printf("You have entered a digit"); 13 | else 14 | printf("You have entered a special character"); 15 | 16 | } -------------------------------------------------------------------------------- /reviseC/ReviseConditional/ques1.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 1 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | int main () { 7 | float billAmt, buyDay, payDay, finalAmt; 8 | scanf("%f", &billAmt); 9 | scanf("%f", &buyDay); 10 | scanf("%f", &payDay); 11 | 12 | if(payDay <= buyDay + 10) { 13 | finalAmt = billAmt - (0.02 * billAmt); 14 | } else { 15 | finalAmt = billAmt; 16 | } 17 | 18 | printf("%0.2f", finalAmt); 19 | } 20 | -------------------------------------------------------------------------------- /reviseC/findSumSeries.c: -------------------------------------------------------------------------------- 1 | /* ============================================================= */ 2 | /* ===== Sum of series 15+25+35+45+55+........+n5. n <= 50 ===== */ 3 | /* ============================================================= */ 4 | #include 5 | int main() { 6 | int i,n,sum=0; 7 | printf("Enter a number (n<50): "); 8 | scanf("%d",&n); 9 | if(!(n>0 && n<50)){ 10 | printf("Invalid Input!"); 11 | return 0; 12 | } 13 | for(i=1;i<=n;i++) 14 | sum+=10*i+5; 15 | printf("The sum is: %d",sum); 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Search/Binary_Search/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search 2 | 3 | ## Algoithm 4 | ```c 5 | STEP 1: Sort the given array in ascendinig order (if descendinig, then change accordingly the 3b and 3c steps) 6 | STEP 2: Compare x with the middle element, 7 | STEP 3a: if x matches with middle element, we return the mid index. 8 | STEP 3b: Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. 9 | STEP 3c: Else (x is smaller) recur for the left half. 10 | ``` 11 | 12 | ## [Binary Search C implementation](binary.c) 13 | -------------------------------------------------------------------------------- /reviseC/ReviseLoops/ques5.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 5 ===== */ 3 | /* ========================================= */ 4 | 5 | /* 6 | Algorithm: We use a nested loop to print such patterns. 7 | i goes from 1 to n 8 | j goes from 1 to i 9 | each iteration of j prints **$ 10 | */ 11 | 12 | #include 13 | int main () { 14 | int n,i,j; 15 | scanf("%d", &n); 16 | 17 | for(i=1;i<=n;i++) { 18 | for (j=1;j<=i;j++) 19 | printf("**$"); 20 | printf("\n"); 21 | } 22 | } -------------------------------------------------------------------------------- /reviseC/factorial.c: -------------------------------------------------------------------------------- 1 | /* =========================================================== */ 2 | /* ===== Program to find the factorial of a given number ===== */ 3 | /* =========================================================== */ 4 | 5 | #include 6 | int factorial(int n); 7 | int main() { 8 | int n,fact; 9 | printf("Enter the number: "); 10 | scanf("%d",&n); 11 | fact = factorial(n); 12 | printf("The factorial of the given number is: %d\n", fact); 13 | return 0; 14 | } 15 | int factorial(int n) { 16 | if(n>1) return n*factorial(n-1); 17 | else return 1; 18 | } -------------------------------------------------------------------------------- /reviseC/sumDig.c: -------------------------------------------------------------------------------- 1 | /* ============================================================== */ 2 | /* ===== Sum of digits of a positive integer less than 1000 ===== */ 3 | /* ============================================================== */ 4 | #include 5 | int main() { 6 | int num,sum=0; 7 | printf("Enter the number: "); 8 | scanf("%d",&num); 9 | if(n>1000){ 10 | printf("Invalid Input!"); 11 | return 0; 12 | } 13 | while(num>0) { 14 | sum+= num%10; 15 | num=num/10; 16 | } 17 | printf("Sum of digits is: %d\n",sum); 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Sort/Selecton_Sort/Selection_Sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n; 5 | scanf("%d",&n); 6 | int a[n], min, temp; 7 | for (int i = 0; i < n; ++i) 8 | { 9 | scanf("%d",&a[i]); 10 | } 11 | for (int i = 0; i < n-1; ++i) 12 | { 13 | min = i; 14 | for (int j = i+1; j < n; ++j) 15 | { 16 | if (a[min] > a[j]) 17 | { 18 | min = j; 19 | } 20 | } 21 | if (min != i) 22 | { 23 | temp = a[min]; 24 | a[min] = a[i]; 25 | a[i] = temp; 26 | } 27 | } 28 | for (int i = 0; i < n; ++i) 29 | { 30 | printf("%d ",a[i]); 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /reviseC/TAT1/ques5.c: -------------------------------------------------------------------------------- 1 | /* ===================================== */ 2 | /* ===== Solution to TAT problem 5 ===== */ 3 | /* ===================================== */ 4 | 5 | #include 6 | 7 | int fibonacci(int n) { 8 | int fibo; 9 | if (n==0) { 10 | fibo = 0; 11 | } else if (n==1) { 12 | fibo = 1; 13 | } else { 14 | fibo = fibonacci(n-1) + fibonacci(n-2); 15 | 16 | } 17 | return fibo; 18 | } 19 | 20 | int main () { 21 | int n,i; 22 | scanf("%d", &n); 23 | for (i=0;i 6 | int main () { 7 | char cadre; 8 | scanf("%c", &cadre); 9 | if (cadre == 'A' || cadre == 'a') 10 | printf("10%%"); 11 | else if (cadre == 'B' || cadre == 'b') 12 | printf("8%%"); 13 | else if (cadre == 'C' || cadre == 'c') 14 | printf("6%%"); 15 | else if (cadre == 'D' || cadre == 'd') 16 | printf("5%%"); 17 | else 18 | printf("Invalid input"); 19 | } -------------------------------------------------------------------------------- /IntroToOOP/friend.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* ============================================== */ 3 | /* ===== Sample program for friend function ===== */ 4 | /* ============================================== */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | class student { 10 | int rollno; 11 | friend void getStud (student &s); 12 | }; 13 | 14 | void getStud (student &s) { 15 | cout<< endl<< "Please enter the roll number: "; 16 | cin>> s.rollno; 17 | cout<< "The roll number is: "< 6 | #include 7 | 8 | void reverse(char word[30], int l); 9 | 10 | int main () { 11 | char word[30]; 12 | int len; 13 | scanf("%s", word); 14 | len = strlen(word); 15 | reverse(word, len-1); 16 | } 17 | 18 | void reverse(char word[], int l) { 19 | if (l==0) { 20 | printf("%c", word[l]); 21 | } else if (l>0) { 22 | printf("%c", word[l]); 23 | reverse(word, l-1); 24 | } 25 | } -------------------------------------------------------------------------------- /IntroToOOP/classTest/sample1.cpp: -------------------------------------------------------------------------------- 1 | /* ======================================== */ 2 | /* ===== Solution to sample problem 1 ===== */ 3 | /* ======================================== */ 4 | 5 | 6 | #include 7 | using namespace std; 8 | #include 9 | class card 10 | { 11 | char value; 12 | string suite; 13 | public: 14 | //Function to read the input values 15 | void read(); 16 | //Check if the value in the two cards are same 17 | bool check_value(card); 18 | //Check if the suite in the two cards are same 19 | bool check_suite(card); 20 | //Print the color of the suite of the card 21 | void print_color_suite(); 22 | }; 23 | -------------------------------------------------------------------------------- /IntroToOOP/tempAdd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template 5 | T add(T a, T b) { 6 | return a+b; 7 | } 8 | 9 | int main () { 10 | // Code for integer 11 | int x1, y1, z1; 12 | cout<<"Enter the value of 1st integer: "; cin>>x1; 13 | cout<<"Enter the value of 2st integer: "; cin>>y1; 14 | z1 = add(x1, y1); 15 | cout<<"Sum is: "<>x2; 19 | cout<<"Enter the value of 2st character: "; cin>>y2; 20 | z2 = add(x2, y2); 21 | cout<<"Sum is: "< 5 | using namespace std; 6 | 7 | class calc { 8 | private: 9 | int a; 10 | int b; 11 | public: 12 | void input() { 13 | cout<<"\nEnter the value of a: "; cin>>a; 14 | cout<<"Enter the value of b: "; cin>>b; 15 | } 16 | void sum() { 17 | cout<<"Sum of "< 6 | using namespace std; 7 | 8 | class Base { 9 | private: 10 | int a; 11 | public: 12 | virtual void print() = 0; 13 | int getA() { 14 | return a; 15 | } 16 | }; 17 | 18 | class Derived { 19 | private: 20 | int b; 21 | public: 22 | void print() { 23 | cout<<"The function was called from the Derived class\n"; 24 | } 25 | }; 26 | 27 | int main () { 28 | Derived d; 29 | d.print(); 30 | return 0; 31 | } -------------------------------------------------------------------------------- /reviseC/armstrong.c: -------------------------------------------------------------------------------- 1 | /* ============================ */ 2 | /* ===== Armstrong number ===== */ 3 | /* ============================ */ 4 | 5 | #include 6 | 7 | int main() { 8 | int num,sum=0,temp,rem; 9 | printf("Enter the number: "); 10 | scanf("%d",&num); 11 | temp = num; 12 | while(temp > 0) { 13 | rem = temp%10; 14 | sum += rem*rem*rem; 15 | temp /= 10; 16 | } 17 | //printf("Sum is: %d",sum); 18 | if(sum == num) { 19 | printf("Yes, the given number is an armstrong number!"); 20 | } else { 21 | printf("No, the given number is not an armstrong number!"); 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /IntroToOOP/dynamicObject.cpp: -------------------------------------------------------------------------------- 1 | /* =============================================================== */ 2 | /* ===== A simple program for dynamically allocating objects ===== */ 3 | /* =============================================================== */ 4 | 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | class test { 11 | public: 12 | test() { 13 | cout<<"Constructor was called!!"< 3 | The most-used orders are numerical order and lexicographical order.
4 | 5 | ### Some commonly used sortinig algorithms 6 | 7 | 1. [Selection Sort]() 8 | 2. [Bubble Sort](bubble.c)
9 | `Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.` 10 | 3. [Insertion Sort]() 11 | 4. [Quick Sort]() 12 | 5. [Merge Sort]() 13 | 6. [Heap Sort]() 14 | 7. [Radix Sort]() 15 | 8. [Topological Sort]() 16 | It is Used in Graphs. 17 | [Go Back](./..){: .btn} 18 | -------------------------------------------------------------------------------- /reviseC/vowels.c: -------------------------------------------------------------------------------- 1 | /* ============================================ */ 2 | /* ===== Number of vowels in a given line ===== */ 3 | /* ============================================ */ 4 | #include 5 | #include 6 | int main() { 7 | int i,len,count=0; 8 | char line[100]; 9 | printf("Enter a sentence: "); 10 | gets(line); 11 | len=strlen(line); 12 | for(i=0;i 6 | void printFib(int n); 7 | int main() { 8 | int n; 9 | printf("Enter the number: "); 10 | scanf("%d",&n); 11 | printFib(n); 12 | return 0; 13 | } 14 | void printFib(int n) { 15 | int a1=1,a2=1,a3=1,i; 16 | for(i=1;i<=n;i++) { 17 | if(i<3) a3=1; 18 | else { 19 | a3=a2+a1; 20 | a1=a2; 21 | a2=a3; 22 | } 23 | printf("\na%d = %d",i,a3); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /reviseC/prime.c: -------------------------------------------------------------------------------- 1 | /* =========================================================== */ 2 | /* ===== Program to find the factorial of a given number ===== */ 3 | /* =========================================================== */ 4 | 5 | #include 6 | void chkPrime(int n); 7 | int main() { 8 | int n; 9 | printf("Enter the number: "); 10 | scanf("%d",&n); 11 | chkPrime(n); 12 | return 0; 13 | } 14 | void chkPrime(int n) { 15 | int i,flag = 0; 16 | for(i=2;i<=n/2;i++) { 17 | if(n%i == 0){ 18 | flag = 1; 19 | break; 20 | } 21 | } 22 | if(flag == 1) printf("The given number is not prime\n"); 23 | else printf("The given number is prime\n"); 24 | } 25 | -------------------------------------------------------------------------------- /reviseC/sumOfElements.c: -------------------------------------------------------------------------------- 1 | /* ================================================================ */ 2 | /* ===== Program to find the sum of elements in a given array ===== */ 3 | /* ================================================================ */ 4 | #include 5 | int main() { 6 | int a[100],n,i,sum=0; 7 | printf("A progam to find the sum of all the elements in Array"); 8 | printf("\nEnter the number of elements in the array: "); 9 | scanf("%d",&n); 10 | printf("Enter the elements of the array: \n"); 11 | for(i=0;i 6 | using namespace std; 7 | 8 | void rshr (int arr[], int n, int m); 9 | 10 | int main () { 11 | int i, m, n, ele[100]; 12 | cin>>n; 13 | for(i=0;i>ele[i]; 15 | } 16 | cin>>m; 17 | rshr(ele, n, m); 18 | return 0; 19 | } 20 | 21 | void rshr (int arr[], int n, int m) { 22 | int i, tempArr[100]; 23 | for (i=0;i 5 | int main() { 6 | int num,min=99999,max=0,avg=0,count=0; 7 | for(int i=0;;i++) { 8 | printf("Enter a positive number: "); 9 | scanf("%d",&num); 10 | if(num<1) break; 11 | avg += num; 12 | count++; 13 | if(min>num) min=num; 14 | if(max0) avg=avg/count; 17 | printf("Minimum of the given numbers is: %d\n",min); 18 | printf("Maximum of the given numbers is: %d\n",max); 19 | printf("Average of the given numbers is: %d\n",avg); 20 | } -------------------------------------------------------------------------------- /pointersInC/swapUsingPointer.c: -------------------------------------------------------------------------------- 1 | /* ================================================== */ 2 | /* ===== Function to swap values using pointers ===== */ 3 | /* ================================================== */ 4 | #include 5 | void swap(int *,int *); 6 | 7 | int main() { 8 | int a,b; 9 | printf("Enter the first number: "); 10 | scanf("%d",&a); 11 | printf("Enter the second number: "); 12 | scanf("%d",&b); 13 | printf("\nBefore SWAP: a=%d, b=%d",a,b); 14 | swap(&a,&b); 15 | printf("\nAfter SWAP: a=%d, b=%d",a,b); 16 | return 0; 17 | } 18 | 19 | void swap(int *x, int *y) { 20 | int temp; 21 | temp = *x; 22 | *x = *y; 23 | *y = temp; 24 | printf("\nIn SWAP: a=%d, b=%d",*x,*y); 25 | } 26 | -------------------------------------------------------------------------------- /reviseC/palindrom.c: -------------------------------------------------------------------------------- 1 | /* ============================================ */ 2 | /* ===== To check for a palindrome number ===== */ 3 | /* ============================================ */ 4 | #include 5 | int main() { 6 | int count,j,i=0,num,numArr[100],flag=1; 7 | printf("Enter the number: "); 8 | scanf("%d",&num); 9 | while(num>0) { 10 | numArr[i]=num%10; 11 | num=num/10; 12 | i++; 13 | } 14 | count=i; 15 | for(i=0,j=count-1;i 6 | using namespace std; 7 | 8 | class abc { 9 | int dataVar1, dataVar2; 10 | public: 11 | void add(int a, int b) // Inline Function -- Member function defined inside the class 12 | { 13 | cout< 6 | #include 7 | 8 | using namespace std; 9 | int main () { 10 | int num; 11 | cout<<"Enter the number of elements"; 12 | cin >> num; 13 | int *ptr; 14 | 15 | ptr = new int[num]; 16 | 17 | cout<<"Enter the numbers: \n"; 18 | for(int i=0; i> *(ptr+i); 21 | } 22 | cout<<"You entered: "< 15 | int main() { 16 | int n,i,j; 17 | scanf("%d", &n); 18 | for (i=1;i<=n;i++) { 19 | for (j=1;j<=n-i;j++) 20 | printf(" "); 21 | for (j=1;j<=2*i-1;j++) 22 | printf("*"); 23 | printf("\n"); 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /reviseC/ReviseStruct/ques4.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 4 ===== */ 3 | /* ========================================= */ 4 | 5 | #include 6 | 7 | void convertBase(int n) { 8 | char newNum[10], sample[4] = {'A','B','C','D'}; 9 | int rem,count=0; 10 | while(n>0) { 11 | rem = n%14; 12 | if(rem<10) { 13 | newNum[count] = rem+48; 14 | count++; 15 | } else { 16 | newNum[count] = sample[rem%10]; 17 | count++; 18 | } 19 | n=n/14; 20 | } 21 | for(int i=count-1;i>=0;i--) { 22 | printf("%c", newNum[i]); 23 | } 24 | } 25 | 26 | int main () { 27 | int num; 28 | scanf("%d", &num); 29 | convertBase(num); 30 | return 0; 31 | } -------------------------------------------------------------------------------- /reviseC/arrayDup.c: -------------------------------------------------------------------------------- 1 | /* ====================================================== */ 2 | /* ===== Program to duplicate the elements of array ===== */ 3 | /* ====================================================== */ 4 | #include 5 | int main() { 6 | int a[100],b[100],n,i; 7 | printf("A program to copy the elements of one array to another"); 8 | printf("\nEnter the number of elements in the array: "); 9 | scanf("%d",&n); 10 | printf("Enter the elements of the array: \n"); 11 | for(i=0;i 6 | #include 7 | using namespace std; 8 | 9 | long int sum_pow(int n, int m=0); 10 | 11 | int main() 12 | { 13 | long int sum,n,m; 14 | cin>>n>>m; 15 | if(m<0) 16 | cout<<"Invalid input"; 17 | else 18 | { 19 | if(m!=0) 20 | sum=sum_pow(n, m); 21 | else 22 | sum=sum_pow(n); 23 | cout< 5 | int main() { 6 | int i,r,c,j,A[100][100]; 7 | printf("Enter the number of rows: "); 8 | scanf("%d",&r); 9 | printf("Enter the number of columms: "); 10 | scanf("%d",&c); 11 | printf("Enter the %d values: \n",r*c); 12 | for(i=0;i 15 | int main () { 16 | int n,i,j; 17 | scanf("%d", &n); 18 | for (i=1;i<=n;i++) { 19 | for (j=1;j<=i-1;j++) 20 | printf(" "); 21 | for (j=1;j<=(n+1)-i;j++) 22 | if ( j%2 == 0 ) printf("1 "); 23 | else printf("0 "); 24 | printf("\n"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /reviseC/ArrayReversal.c: -------------------------------------------------------------------------------- 1 | /* ====================================== */ 2 | /* ===== Program toreverse an array ===== */ 3 | /* ====================================== */ 4 | #include 5 | int main() { 6 | int temp,a[100],j,n,i; 7 | printf("A program to copy the elements of one array to another"); 8 | printf("\nEnter the number of elements in the array: "); 9 | scanf("%d",&n); 10 | printf("Enter the elements of the array: \n"); 11 | for(i=0;i 8 | 9 | int findSum(int temp) { 10 | int rem,sum=0; 11 | while(temp > 0) { 12 | rem = temp%10; 13 | sum += rem; 14 | temp /= 10; 15 | } 16 | if(sum<10) 17 | return sum; 18 | else 19 | return findSum(sum); 20 | } 21 | 22 | int main() { 23 | int sum,num,splNum; 24 | printf("Enter the DOB(in DDMMYYYY): "); 25 | scanf("%d",&num); 26 | if(num<1000000) { 27 | return printf("INVALID INPUT!!!!!\nEnter the DOB in DDMMYYYY"); 28 | } 29 | splNum = findSum(num); 30 | printf("The special number is: %d",splNum); 31 | } 32 | -------------------------------------------------------------------------------- /Sort/Bubble_Sort/bubble.c: -------------------------------------------------------------------------------- 1 | /* ================================= */ 2 | /* ===== Bubble Sort Algorithm ===== */ 3 | /* ================================= */ 4 | 5 | #include 6 | int main() { 7 | int n,arr[100],i,j,temp; 8 | printf("Enter the number of elements in the array: "); 9 | scanf("%d",&n); 10 | printf("Enter the Elements: \n"); 11 | for(i=0;iarr[j]) { 21 | temp = arr[i]; 22 | arr[i]=arr[j]; 23 | arr[j]= temp; 24 | } 25 | printf("\nSorted Array Is: "); 26 | for(i=0;i 2 | using namespace std; 3 | 4 | class A { 5 | int m1; 6 | int m2; 7 | public: 8 | void getA () { 9 | cout<<"Enter the values: "<>m1>>m2; 11 | } 12 | void printA () { 13 | cout< 6 | #include 7 | 8 | int main() { 9 | int num, i, *ptr, sum=0; 10 | printf("Enter number of elements: "); 11 | scanf("%d", &num); 12 | 13 | ptr = (int*)calloc(num, sizeof(int)); 14 | 15 | if(ptr == NULL) { 16 | printf("Error! memory not allocated."); 17 | return 0; 18 | } 19 | 20 | printf("Enter the elements of array(separated by space): "); 21 | for(i=0;i 6 | #include 7 | 8 | int main() { 9 | int num, i, *ptr, sum=0; 10 | printf("Enter number of elements: "); 11 | scanf("%d", &num); 12 | 13 | ptr = (int*)malloc(num * sizeof(int)); 14 | 15 | if(ptr == NULL) { 16 | printf("Error! memory not allocated."); 17 | return 0; 18 | } 19 | 20 | printf("Enter the elements of array(separated by space): "); 21 | for(i=0;i 6 | #include 7 | int main () { 8 | char str[100]; 9 | int count=0,letrs[40],i,len; 10 | // Take the input 11 | scanf("%[^\n]s", str); 12 | // counting the words and the length of longest word 13 | len = strlen(str); 14 | letrs[count] = 0; 15 | for(i=0;i max) { 27 | max = letrs[i]; 28 | } 29 | } 30 | printf("%d\n", count+1); 31 | printf("%d", max); 32 | } -------------------------------------------------------------------------------- /reviseC/ans1.c: -------------------------------------------------------------------------------- 1 | /* ====================================================================================================== */ 2 | /* ===== 3 | Question: Write a program which reads a single letter of alphabet. If it is a lowercase between 4 | ’a’ and ’g’, the program prints out the alphabet in uppercase form. If it is anything 5 | else, the program should print out uppercase ’X’. 6 | ===== */ 7 | /* ====================================================================================================== */ 8 | 9 | #include 10 | void main() { 11 | char ip; 12 | printf("Enter a character: "); 13 | scanf("%c",&ip); 14 | if((int)(ip) >= 97 && (int)(ip) <= 103) { 15 | printf("Output: %c",ip-32); 16 | } else { 17 | printf("Ouput: X"); 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Search/Linear_Search/linear.c: -------------------------------------------------------------------------------- 1 | /* =================================== */ 2 | /* ===== Linear search algorithm ===== */ 3 | /* =================================== */ 4 | 5 | #include 6 | 7 | int main() { 8 | int arr[100],n,i,x,pos=-1; 9 | printf("Enter the number of elements in the array: "); 10 | scanf("%d",&n); 11 | printf("Enter the Elements: \n"); 12 | for(i=0;i 2 | int main() { 3 | int gradeList[8] = {92,85,75,88,79,54,34,96}; 4 | int *myGrades = gradeList; 5 | printf("1st element of gradelist using array index: %d\n",gradeList[0]); 6 | printf("1st element of gradelist using pointer: %d\n",*myGrades); 7 | printf("2nd element of gradelist using array index: %d\n", *(myGrades + 1)); 8 | printf("2nd element of gradelist using pointer: %d\n", myGrades[1]); 9 | printf("3rd element of gradelist using array index: %d\n", *(myGrades + 2)); 10 | printf("3rd element of gradelist using pointer: %d\n", myGrades[2]); 11 | printf("4th element of gradelist using array index: %d\n", *(myGrades + 3)); 12 | printf("4th element of gradelist using pointer %d\n", myGrades[3]); 13 | printf("5th element of gradelist using array index: %d\n", *(myGrades + 4)); 14 | printf("5th element of gradelist using pointer: %d\n", myGrades[4]); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /IntroToOOP/virtual.cpp: -------------------------------------------------------------------------------- 1 | /* ======================================== */ 2 | /* ===== Example of virtual functions ===== */ 3 | /* ======================================== */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Base { 9 | private: 10 | int a; 11 | public: 12 | virtual void print () { 13 | cout<<"This is from base class"<print(); 42 | B = &da; 43 | B->print(); 44 | B = &db; 45 | B->print(); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /IntroToOOP/inheritance/multiple.cpp: -------------------------------------------------------------------------------- 1 | /* =================================================== */ 2 | /* ===== Sample program for multiple inheritance ===== */ 3 | /* =================================================== */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | class A { 9 | public: 10 | int a; 11 | protected: 12 | float x; 13 | }; 14 | 15 | class B { 16 | public: 17 | int b; 18 | }; 19 | 20 | class C: public A, public B { 21 | public: 22 | int c; 23 | }; 24 | 25 | int main () { 26 | // Make instance of class C 27 | C subclass; 28 | // Read the values of a,b and c 29 | cout<<"\nEnter the value of a: "; cin>>subclass.a; 30 | cout<<"Enter the value of b: "; cin>>subclass.b; 31 | cout<<"Enter the value of c: "; cin>>subclass.c; 32 | // Print the values 33 | cout<<"\nThe value of a is: "< 6 | using namespace std; 7 | 8 | class A { 9 | public: 10 | int a; 11 | protected: 12 | float x; 13 | }; 14 | 15 | class B: public A { 16 | public: 17 | int b; 18 | }; 19 | 20 | class C: public B { 21 | public: 22 | int c; 23 | }; 24 | 25 | int main () { 26 | // Make instance of class C 27 | C subclass; 28 | // Read the values of a,b and c 29 | cout<<"\nEnter the value of a: "; cin>>subclass.a; 30 | cout<<"Enter the value of b: "; cin>>subclass.b; 31 | cout<<"Enter the value of c: "; cin>>subclass.c; 32 | // Print the values 33 | cout<<"\nThe value of a is: "< 6 | using namespace std; 7 | 8 | class employee { 9 | private: 10 | char name[25]; 11 | char empId[10]; 12 | int age; 13 | public: 14 | void readVal(); 15 | void dispVal(); 16 | }; 17 | 18 | void employee::readVal() { 19 | cin>>name; 20 | cin>>empId; 21 | cin>>age; 22 | } 23 | 24 | void employee::dispVal() { 25 | if (age < 18) { 26 | throw 10; 27 | } else if (age > 50) { 28 | throw 'a'; 29 | } 30 | cout< 5 | int main() { 6 | int i,r,c,j,A[100][100],B[100][100],sum[100][100]; 7 | printf("Enter the number of rows: "); 8 | scanf("%d",&r); 9 | printf("Enter the number of columms: "); 10 | scanf("%d",&c); 11 | printf("Enter the %d Elements of matrix A: \n",r*c); 12 | for(i=0;i 8 | int main() { 9 | int prime[100]; 10 | int i,j,count=0,flag=1; 11 | for(i=2;i<=100;i++) { 12 | flag=1; 13 | for(j=2;j<=i/2;j++) { 14 | if(i%j == 0) { 15 | flag=0; 16 | j=i/2; 17 | } 18 | } 19 | 20 | if(flag == 1) { 21 | prime[count] = i; 22 | count++; 23 | } 24 | } 25 | 26 | printf("\n The prime numbers are: "); 27 | for(i=0;i 10 | void main() { 11 | float num[4]; 12 | int i,max,min; 13 | printf("Enter the 4 numbers separated by space: "); 14 | for(i=0;i<4;i++) { 15 | scanf("%f",&num[i]); 16 | } 17 | 18 | min=0; 19 | max=0; 20 | for(i=0;i<4;i++) { 21 | if(num[min]>num[i]) min=i; 22 | if(num[max] 6 | using namespace std; 7 | 8 | class square; 9 | class rectangle { 10 | int w,h; 11 | public: 12 | rectangle (int wid=1, int hgt=1) { 13 | h = hgt; 14 | w = wid; 15 | } 16 | void display () { 17 | cout<<"Area of rectangle: "< 6 | #include 7 | 8 | void convertCase(char *x) { 9 | if(islower(*x)) { 10 | *x = *x - 32; 11 | } else { 12 | *x = *x + 32; 13 | } 14 | } 15 | 16 | int main () { 17 | char mat[50][50]; 18 | int i,j,n; 19 | // Input the matrix 20 | scanf("%d", &n); 21 | for (i=0;i 6 | using namespace std; 7 | int main () { 8 | int i,temp,j,n,arr[50]; 9 | cin>>n; 10 | for (i=0;i>arr[i]; 12 | } 13 | 14 | // Solution Method --1 15 | /* int min = arr[0]; 16 | for (i=0;iarr[i]) 18 | min = arr[i]; 19 | } 20 | 21 | int secondMin = arr[1]; 22 | for (i=0;imin && arr[i] 6 | using namespace std; 7 | 8 | class sample { 9 | int a; 10 | float b; 11 | public: 12 | void getVal () { 13 | cout<<"Enter the values: "; 14 | cout<<"\n int a = "; cin>>a; 15 | cout<<" float b = "; cin>>b; 16 | } 17 | void printVal () { 18 | cout<<"Printing the values: "; 19 | cout<<"\n int a = "< 6 | 7 | // Function to exit the program if not equal 8 | void notEqual(void) { 9 | printf("Not same"); 10 | exit(0); 11 | } 12 | 13 | int main () { 14 | int n, mat[50][50],elem,i,j; 15 | // Input the matrix 16 | scanf("%d", &n); 17 | for (i=0;i 6 | #include 7 | 8 | struct players { 9 | char name[50]; 10 | int age,size; 11 | }; 12 | 13 | void findCompanion(struct players x[], char p[], int n) { 14 | int i,j, num; 15 | // Find the enetered plpayer 16 | for (i=0;i 6 | int main () { 7 | // Declare the variables 8 | int n,arr[100],i,count=0,mid[100]; 9 | // Input the numbers 10 | scanf("%d", &n); 11 | for (i=0;i arr[i]) { 18 | mid[count] = arr[i]; 19 | count++; 20 | } 21 | } else if (i == n-1) { 22 | if (arr[i-1] < arr[i]) { 23 | mid[count] = arr[i]; 24 | count++; 25 | } 26 | } else { 27 | if(arr[i] > arr[i-1] && arr[i] < arr[i+1]) { 28 | mid[count] = arr[i]; 29 | count++; 30 | } 31 | } 32 | } 33 | if (count == 0) 34 | printf("No number has mid property"); 35 | else 36 | for(i=0;i 6 | 7 | struct salesmen { 8 | char name[50]; 9 | int sales[5]; 10 | }; 11 | 12 | int findBestSP(struct salesmen x[], int n) { 13 | int total[50],i,j; 14 | // Find the total sales by each salesman 15 | for(i=0;i total[max]) 25 | max = i; 26 | } 27 | // Return the index of best SP 28 | return max; 29 | } 30 | 31 | int main () { 32 | int n,i,best; 33 | scanf("%d", &n); 34 | struct salesmen sp[n]; 35 | // Input the details of every salesperson 36 | for(i=0;i 6 | #include 7 | int main () { 8 | int n,i,j,k,count=0,temp=1; 9 | char dict[50][15],lexico[50][15]; 10 | // Input phase 11 | scanf("%d", &n); 12 | for(i=0;idict[i][k]) { 21 | temp = 0; 22 | j=n; 23 | k=n; 24 | } else if (dict[j][k] < dict[i][k]) { 25 | temp = 1; 26 | k=n; 27 | } 28 | } 29 | 30 | } 31 | if(temp == 1) { 32 | strcpy(lexico[count], dict[i]); 33 | count++; 34 | } 35 | } 36 | strcpy(lexico[count], dict[i]); 37 | printf("Hello\n"); 38 | for(i=0;i 6 | using namespace std; 7 | 8 | template 9 | 10 | T findMax(T a, T b, T c) { 11 | T Max = a; 12 | if (b>Max) Max = b; 13 | if (c>Max) Max = c; 14 | return Max; 15 | } 16 | 17 | int main () { 18 | int a,b,c; 19 | cout<<"Enter the first number: "; cin>>a; 20 | cout<<"Enter the second number: "; cin>>b; 21 | cout<<"Enter the third number: "; cin>>c; 22 | int Max = findMax(a,b,c); 23 | cout<<"The maximum number is: "<>x; 27 | cout<<"Enter the second float: "; cin>>y; 28 | cout<<"Enter the third float: "; cin>>z; 29 | float Maxf = findMax(x,y,z); 30 | cout<<"The maximum float is: "<>p; 34 | cout<<"Enter the second string: "; cin>>q; 35 | cout<<"Enter the third string: "; cin>>r; 36 | string Maxs = findMax(p,q,r); 37 | cout<<"The maximum string is: "< 6 | #include 7 | 8 | struct Books { 9 | char title[50]; 10 | char author[50]; 11 | char subject[100]; 12 | int book_id; 13 | }; 14 | 15 | int main() { 16 | 17 | // Declare 2 instances of structure books 18 | struct Books book[100]; 19 | int n,i; 20 | printf("Enter the number of books: "); 21 | scanf("%d",&n); 22 | 23 | // Enter the details of all books 24 | for(i=0;i 6 | using namespace std; 7 | 8 | class A { 9 | public: 10 | int a; 11 | protected: 12 | float x; 13 | }; 14 | 15 | class B: public A { 16 | public: 17 | int b; 18 | }; 19 | 20 | class C: public A { 21 | public: 22 | int c; 23 | }; 24 | 25 | class D: public A { 26 | public: 27 | int d; 28 | }; 29 | 30 | int main () { 31 | // Make instance of class B, C, D 32 | B b; 33 | C c; 34 | D d; 35 | // Read the values of a,b and c 36 | cout<<"Enter the value of B->b: "; cin>>b.b; 37 | cout<<"Enter the value of C->c: "; cin>>c.c; 38 | cout<<"Enter the value of D->d: "; cin>>d.d; 39 | cout<<"Enter the value of B->a: "; cin>>b.a; 40 | cout<<"Enter the value of C->a: "; cin>>c.a; 41 | cout<<"Enter the value of D->a: "; cin>>d.a; 42 | // Print the values 43 | cout<<"\nThe value of B->b is: "<c is: "<d is: "<a is: "<a is: "<a is: "< 5 | #include 6 | 7 | int main() { 8 | 9 | int n; 10 | char name[20]; 11 | printf("Enter your name: "); 12 | scanf("%s",name); 13 | 14 | /* ===== 1. Strlen ===== */ 15 | 16 | printf("Your name is: %s",name); 17 | n=strlen(name); 18 | printf("\nString length: %d",n); 19 | 20 | /* ===== 2. Strrev ===== */ 21 | 22 | // strrev(name); 23 | // printf("\nReversed name: %s",name); 24 | 25 | /* ===== 3. Strcpy: **initial values of a are overwritten ===== */ 26 | 27 | char a[20] = { 'a','b','c','\0'}; 28 | strcpy(a,name); 29 | printf("\nString a: %s",a); 30 | 31 | /* ===== 4. Strcat ===== */ 32 | 33 | char b[20]; 34 | printf("\nEnter the second string: "); 35 | scanf("%s",b); 36 | strcat(a,b); 37 | printf("Complete Concatenated string is: %s",a); 38 | strncat(a,b,1); 39 | printf("\nPartial concatenated string is: %s", a); 40 | 41 | /* ===== 5. Strncmp: **returns ascii difference between two strings ===== */ 42 | /* ===== Stricmp: case insensitive comparison ===== */ 43 | n=strncmp(a,b,2); 44 | if(n==0) printf("\nBoth a and b are equal"); 45 | else printf("\nBoth a and b are not equal"); 46 | } 47 | -------------------------------------------------------------------------------- /IntroToOOP/classTest/sample4.c: -------------------------------------------------------------------------------- 1 | /* ======================================== */ 2 | /* ===== Solution to sample problem 4 ===== */ 3 | /* ======================================== */ 4 | 5 | #include 6 | #include 7 | 8 | int main () { 9 | // Declare the variables and input the values 10 | int n,i,j,k,flag, count; 11 | char ip[100][20], name[100][20]; 12 | scanf("%d", &n); 13 | for(i=0;i 5 | #include 6 | 7 | struct Books { 8 | char title[50]; 9 | char author[50]; 10 | char subject[100]; 11 | int book_id; 12 | }; 13 | 14 | int main() { 15 | 16 | // Declare 2 instances of structure books 17 | struct Books book1,book2; 18 | 19 | // Enter the details of both books 20 | printf("Enter the title of book 1: "); 21 | gets(book1.title); 22 | printf("Enter the author of book 1: "); 23 | gets(book1.author); 24 | printf("Enter the subject of book 1: "); 25 | gets(book1.subject); 26 | book1.book_id = 10293; 27 | 28 | printf("Enter the title of book 2: "); 29 | gets(book2.title); 30 | printf("Enter the author of book 2: "); 31 | gets(book2.author); 32 | printf("Enter the subject of book 2: "); 33 | gets(book2.subject); 34 | book2.book_id = 10341; 35 | 36 | // Print the details of both books 37 | printf("\nTitle of book 1: %s",book1.title); 38 | printf("\nAuthor of book 1: %s",book1.author); 39 | printf("\nSubject of book 1: %s",book1.subject); 40 | 41 | printf("\nTitle of book 2: %s",book2.title); 42 | printf("\nAuthor of book 2: %s",book2.author); 43 | printf("\nSubject of book 2: %s",book2.subject); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /IntroToOOP/inheritance/single.cpp: -------------------------------------------------------------------------------- 1 | /* ================================================= */ 2 | /* ===== Sample program for single inheritance ===== */ 3 | /* ================================================= */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | // Base Class 9 | class parent { 10 | protected: 11 | int age; 12 | int gender; 13 | public: 14 | float propertySize; 15 | void getPrivate (); 16 | void getProp (); 17 | }; 18 | 19 | void parent::getPrivate () { 20 | cout<<"\n\t\t Getting Protected Info"; 21 | cout<<"\nEnter the age: "; cin>>age; 22 | cout<<"\nEnter the gender: "; cin>>gender; 23 | } 24 | 25 | void parent::getProp() { 26 | cout<<"\n\t\t Getting Public Info"; 27 | cout<<"\nEnter the inherited property size: "; 28 | cin>>propertySize; 29 | } 30 | 31 | class child: public parent { 32 | private: 33 | int newProp; 34 | public: 35 | void getNewProp () { 36 | cout<<"\n\t\t Getting new property"; 37 | cout<<"\nEnter the new property size: "; 38 | cin>>newProp; 39 | } 40 | }; 41 | 42 | int main () { 43 | parent P; 44 | child C; 45 | cout<<"\n\t\t\t GETTING PARENT'S CHARACTERISTICS \n"; 46 | P.getPrivate(); 47 | P.getProp(); 48 | cout<<"\n\t\t\t GETTING CHILD'S CHARACTERISTICS \n"; 49 | C.getPrivate(); 50 | C.getProp(); 51 | C.getNewProp(); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Sort/Insertion_Sort/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | #define pb push_back 6 | #define mp make_pair 7 | #define PI 3.14159265358979323 8 | #define debug(x) cout<<"Case "< vi; 14 | typedef vector vll; 15 | typedef pair pii; 16 | typedef pair pll; 17 | typedef vector < pii > vpii; 18 | typedef vector < pll > vpll; 19 | typedef vector vs; 20 | 21 | //Handle:cyber_rajat 22 | 23 | void insertion_sort(int a[],int n) 24 | { 25 | int j,temp; 26 | for(int i=0;itemp && j>=0;j--) 30 | { 31 | a[j+1]=a[j]; 32 | } 33 | a[j+1]=temp; 34 | } 35 | } 36 | int main() 37 | { 38 | int n; 39 | cout<<"Size of Array::"; 40 | cin>>n; 41 | int a[n]; 42 | cout<<"Enter Sequence::"; 43 | for(int i=0;i>a[i]; 45 | 46 | //insertion short 47 | insertion_sort(a,n); 48 | 49 | cout<<"Sorted Array::"; 50 | for(int i=0;i 6 | using namespace std; 7 | 8 | class A { 9 | public: 10 | int a; 11 | protected: 12 | float x; 13 | }; 14 | 15 | class B: public A { 16 | public: 17 | int b; 18 | }; 19 | 20 | class C: public A { 21 | public: 22 | int c; 23 | }; 24 | 25 | class D: public B, public C { 26 | public: 27 | int d; 28 | }; 29 | 30 | int main () { 31 | // Make instance of class B, C, D 32 | B b; 33 | C c; 34 | D d; 35 | // Read the values of a,b and c 36 | cout<<"Enter the value of B->b: "; cin>>b.b; 37 | cout<<"Enter the value of C->c: "; cin>>c.c; 38 | cout<<"Enter the value of D->d: "; cin>>d.d; 39 | cout<<"Enter the value of B->a: "; cin>>b.a; 40 | cout<<"Enter the value of C->a: "; cin>>c.a; 41 | cout<<"Enter the value of D->b: "; cin>>d.b; 42 | cout<<"Enter the value of D->c: "; cin>>d.c; 43 | // Print the values 44 | cout<<"\nThe value of B->b is: "<c is: "<d is: "<a is: "<a is: "<b is: "<c is: "< 7 | #include 8 | 9 | struct Books { 10 | char title[50]; 11 | char author[50]; 12 | char subject[100]; 13 | int book_id; 14 | }; 15 | 16 | void displayBookDetails(struct Books book, int i) { 17 | printf("\nTitle of book %d: %s",i+1,book.title); 18 | printf("\nAuthor of book %d: %s",i+1,book.author); 19 | printf("\nSubject of book %d: %s",i+1,book.subject); 20 | printf("\nBook ID of book %d: %d",i+1,book.book_id); 21 | } 22 | 23 | int main() { 24 | 25 | // Declare 2 instances of structure books 26 | struct Books book[100]; 27 | int n,i; 28 | printf("Enter the number of books: "); 29 | scanf("%d",&n); 30 | 31 | // Enter the details of all books 32 | for(i=0;i 6 | using namespace std; 7 | 8 | // Make a class for the information of passengers 9 | class Pass { 10 | private: 11 | int x, age; 12 | char boardPass[10], address[40], name[20], dateP[15]; 13 | long int mobile; 14 | float fare, finalFare; 15 | public: 16 | // Declare the functions 17 | void getDetails (); 18 | void discount (); 19 | void generatePass (); 20 | }; 21 | 22 | // Function to get the passenger details 23 | void Pass::getDetails () { 24 | cin>>name; 25 | cin>>x; 26 | cin>>age; 27 | cin>>address; 28 | 29 | cin>>dateP; 30 | cin>>mobile; 31 | cin>>fare; 32 | } 33 | 34 | // Function to calculate the discpunt 35 | void Pass::discount () { 36 | if (age>=12 && age<=58) { 37 | finalFare = 0.8*(fare); 38 | } else if (age > 58) { 39 | finalFare = 0.6 * (fare); 40 | } else if (age < 12) { 41 | finalFare = 0.5 * (fare); 42 | } 43 | } 44 | 45 | // Function to generate boarding pass 46 | void Pass::generatePass () { 47 | cout< 5 | int main() { 6 | int n,arr[100],x,i,j,temp; 7 | printf("Enter the number of elements in the array: "); 8 | scanf("%d",&n); 9 | printf("Enter the Elements: \n"); 10 | for(i=0;iarr[j]) { 20 | temp = arr[i]; 21 | arr[i]=arr[j]; 22 | arr[j]= temp; 23 | } 24 | printf("\nSorted Array Is: "); 25 | for(i=0;i0 && mid arr[mid]) { 36 | start = mid+1; 37 | } else { 38 | end = mid-1; 39 | } 40 | } 41 | if(pos == -1) { 42 | printf("The given element does not exist in the array!"); 43 | } else { 44 | printf("The index of the given element is: %d", pos); 45 | } 46 | } -------------------------------------------------------------------------------- /Structures/structinfun.c: -------------------------------------------------------------------------------- 1 | /* =========================================== */ 2 | /* ===== passing structures in functions ===== */ 3 | /* ========== (Call By Reference) ============ */ 4 | /* =========================================== */ 5 | 6 | #include 7 | #include 8 | 9 | struct Books { 10 | char title[50]; 11 | char author[50]; 12 | char subject[100]; 13 | int book_id; 14 | }; 15 | 16 | void inputBookDetails(struct Books *book, int i) { 17 | printf("Enter the title of book %d: ",i+1); 18 | scanf("%s",book->title); 19 | printf("Enter the author of book %d: ",i+1); 20 | scanf("%s",book->author); 21 | printf("Enter the subject of book %d: ",i+1); 22 | scanf("%s",book->subject); 23 | book->book_id = 10000+8*i; 24 | } 25 | 26 | void displayBookDetails(struct Books *book, int i) { 27 | printf("\nTitle of book %d: %s",i+1,book->title); 28 | printf("\nAuthor of book %d: %s",i+1,book->author); 29 | printf("\nSubject of book %d: %s",i+1,book->subject); 30 | printf("\nBook ID of book %d: %d",i+1,book->book_id); 31 | } 32 | 33 | int main() { 34 | 35 | // Declare 2 instances of structure books 36 | struct Books book[100]; 37 | int n,i; 38 | printf("Enter the number of books: "); 39 | scanf("%d",&n); 40 | 41 | // Enter the details of all books 42 | for(i=0;i 2 | using namespace std; 3 | 4 | class Time { 5 | private: 6 | int hours; 7 | int minutes; 8 | public: 9 | Time () { 10 | hours = 0; 11 | minutes = 0; 12 | } 13 | Time (int h, int m) { 14 | hours =h; 15 | minutes = m; 16 | } 17 | void displayTime () { 18 | cout<<"Hours: "<= 60) { 24 | ++hours; 25 | minutes -= 60; 26 | } 27 | if (hours >= 13) { 28 | hours %= 12; 29 | } 30 | return Time (hours, minutes); 31 | } 32 | // Overloading postfix ++ 33 | Time operator ++ (int ) { 34 | /* Time T(hours, minutes); 35 | ++T.minutes; 36 | if (T.minutes >= 60) { 37 | ++T.hours; 38 | T.minutes -= 60; 39 | } 40 | if (T.hours >= 13) { 41 | T.hours -= 12; 42 | } 43 | return T; */ 44 | 45 | ++minutes; 46 | if (minutes >= 60) { 47 | ++hours; 48 | minutes -= 60; 49 | } 50 | if (hours >= 13) { 51 | hours %= 12; 52 | } 53 | return Time (hours, minutes); 54 | } 55 | }; 56 | 57 | int main () { 58 | Time T1(11, 59), T2(30,40); 59 | ++T1; 60 | T1.displayTime(); 61 | ++T1; 62 | T1.displayTime(); 63 | T2++; 64 | T2.displayTime(); 65 | T2++; 66 | T2.displayTime(); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /reviseC/ReviseLoops/ques6.c: -------------------------------------------------------------------------------- 1 | /* ========================================= */ 2 | /* ===== Solution for Sample Problem 6 ===== */ 3 | /* ========================================= */ 4 | 5 | /* 6 | Algorithm : We divide this questiion into 2 parts, 7 | 1. Upper Triangle (Nested Loop 1) 8 | i goes from 1 to n/2 9 | The inside loop prints spaces and stars separately 10 | Number of outer spaces = (n/2)-i+1 11 | Number of Inner Elements = 2*i-1 , 12 | where, first and last element is a star else spaces 13 | 2. Lower Triangle (Nested Loop 2) 14 | rem = n-n/2 15 | i goes form rem to 1 16 | The inside loop prints spaces and stars separately 17 | Number of outer spaces = rem - i 18 | Number of Inner Elements = 2*i - 1 , 19 | where, first and last element is a star else space 20 | */ 21 | 22 | #include 23 | int main () { 24 | int n,i,j,rem; 25 | scanf("%d", &n); 26 | 27 | // Upper Triangle 28 | for (i=1;i<=n/2;i++) { 29 | for(j=1;j<=(n/2)-i+1;j++) 30 | printf(" "); 31 | for(j=1;j<=2*i-1;j++) 32 | if ( j == 1 || j == 2*i-1 ) printf("*"); 33 | else printf(" "); 34 | printf("\n"); 35 | } 36 | 37 | // Lower Triangle 38 | rem = n - n/2; 39 | for (i=rem;i>=1;i--) { 40 | if ( n%2 == 0 ) printf(" "); 41 | for(j=1;j<=rem-i;j++) 42 | printf(" "); 43 | for(j=1;j<=2*i-1;j++) 44 | if ( j == 1 || j == 2*i-1 ) printf("*"); 45 | else printf(" "); 46 | printf("\n"); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Sort/Heap_Sort/heap-sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | // To heapify a subtree rooted with node i which is 7 | // an index in arr[]. n is size of heap 8 | void heapify(int arr[], int n, int i) 9 | { 10 | int largest = i; // Initialize largest as root 11 | int l = 2*i + 1; // left = 2*i + 1 12 | int r = 2*i + 2; // right = 2*i + 2 13 | 14 | // If left child is larger than root 15 | if (l < n && arr[l] > arr[largest]) 16 | largest = l; 17 | 18 | // If right child is larger than largest so far 19 | if (r < n && arr[r] > arr[largest]) 20 | largest = r; 21 | 22 | // If largest is not root 23 | if (largest != i) 24 | { 25 | swap(arr[i], arr[largest]); 26 | 27 | // Recursively heapify the affected sub-tree 28 | heapify(arr, n, largest); 29 | } 30 | } 31 | 32 | // main function to do heap sort 33 | void heapSort(int arr[], int n) 34 | { 35 | // Build heap (rearrange array) 36 | for (int i = n / 2 - 1; i >= 0; i--) 37 | heapify(arr, n, i); 38 | 39 | // One by one extract an element from heap 40 | for (int i=n-1; i>=0; i--) 41 | { 42 | // Move current root to end 43 | swap(arr[0], arr[i]); 44 | 45 | // call max heapify on the reduced heap 46 | heapify(arr, i, 0); 47 | } 48 | } 49 | 50 | /* A utility function to print array of size n */ 51 | void printArray(int arr[], int n) 52 | { 53 | for (int i=0; i>n; 66 | int arr[n]; 67 | cout<<"Enter Sequence::"; 68 | for(int i=0;i>arr[i]; 70 | 71 | heapSort(arr, n); 72 | 73 | cout << "Sorted array is \n"; 74 | printArray(arr, n); 75 | } 76 | -------------------------------------------------------------------------------- /Sort/Merge_Sort/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | #define pb push_back 6 | #define mp make_pair 7 | #define PI 3.14159265358979323 8 | #define debug(x) cout<<"Case "< vi; 14 | typedef vector vll; 15 | typedef pair pii; 16 | typedef pair pll; 17 | typedef vector < pii > vpii; 18 | typedef vector < pll > vpll; 19 | typedef vector vs; 20 | 21 | //handle:cyber_rajat 22 | 23 | void merge(int *a,int *l,int left,int *r,int right) { 24 | int i=0,j=0,k=0; 25 | 26 | while(i>n; 61 | int a[n]; 62 | cout<<"Enter Sequence::"; 63 | for(int i=0;i>a[i]; 65 | 66 | //merge short 67 | merge_sort(a,n); 68 | cout<<"Sorted Array::"; 69 | for(int i=0;i 6 | using namespace std; 7 | #include 8 | #include 9 | 10 | class triangle 11 | { 12 | int a; 13 | int b; 14 | int c; 15 | double area; 16 | int perimeter; 17 | public: 18 | //function to read data members of class 19 | void read(); 20 | //function to calculate area 21 | void compute_area(); 22 | //function to calculate perimeter 23 | void compute_perimeter(); 24 | //function to check if the triangle is Heronian 25 | bool is_Heronian(); 26 | //function to print perimeter of triangle 27 | void print_perimeter(); 28 | //function to print area of triangle 29 | void print_area(); 30 | 31 | }; 32 | 33 | void triangle::read () { 34 | cin>>a; 35 | cin>>b; 36 | cin>>c; 37 | } 38 | 39 | void triangle::compute_perimeter() { 40 | perimeter = a+b+c; 41 | } 42 | 43 | void triangle::print_perimeter () { 44 | cout<temp && j>=0;j--) 39 | { 40 | a[j+1]=a[j]; 41 | } 42 | a[j+1]=temp; 43 | } 44 | } 45 | int main() 46 | { 47 | int n; 48 | cout<<"Size of Array::"; 49 | cin>>n; 50 | int a[n]; 51 | cout<<"Enter Sequence::"; 52 | for(int i=0;i>a[i]; 54 | 55 | //insertion short 56 | insertion_sort(a,n); 57 | 58 | cout<<"Sorted Array::"; 59 | for(int i=0;i 6 | using namespace std; 7 | 8 | class customer { 9 | protected: 10 | char name[20], address[40], id[10]; 11 | long int mobile; 12 | float cost[100]; 13 | int num; 14 | public: 15 | void get () { 16 | cin>>name; 17 | cin>>mobile; 18 | cin>>address; 19 | cin>>id; 20 | cin>>num; 21 | for (int i=0; i>cost[i]; 23 | } 24 | } 25 | 26 | float calc_Total() { 27 | float tot=0; 28 | for (int i=0;i=20000) { 42 | tot=0.96*tot; 43 | } else if (tot>=15000 && tot<20000) { 44 | tot = 0.97*tot; 45 | } else if (tot>=10000 && tot<15000) { 46 | tot = 0.98*tot; 47 | } else if (tot>=5000 && tot<10000) { 48 | tot = 0.99*tot; 49 | } 50 | finalTot += tot; 51 | } 52 | return finalTot; 53 | } 54 | }; 55 | 56 | 57 | 58 | int main() { 59 | int ch; 60 | //get choice of customer 61 | cin>>ch; 62 | if(ch==0) { 63 | customer c1; 64 | //get the details of customer 65 | c1.get(); 66 | //calculate total amount to be paid 67 | //develop a function in customer class that will calculate 68 | // the total amount and return it 69 | cout< 6 | using namespace std; 7 | //Function to find weekday number 8 | // 0 - Sunday, 1 - Monday and so on 6-Saturday 9 | int find_day(int n); 10 | //Given a character array of size 5 with subject letter print the name of the subject corressponding to position i 11 | void print_first_hour(char* sub, int i); 12 | //Function to check if given Saturday is an even Saturday 13 | bool check_Even_Sat(int d); 14 | // Function to find odd Saturday number, odd Saturday number of day 6 is 1, day 20 is 2 and so on 15 | int find_Odd_Sat_Num(int d); 16 | 17 | int main () { 18 | char subjects[5]; 19 | int n,i,weekday,pos,rem,num; 20 | bool sat; 21 | for(i=0;i<5;i++) { 22 | cin>>subjects[i]; 23 | } 24 | cin>>n; 25 | weekday = find_day(n); 26 | rem = n/7; 27 | if (weekday == 6) { 28 | sat = check_Even_Sat(rem); 29 | if (!sat) { 30 | num = find_Odd_Sat_Num(rem); 31 | num = num%5; 32 | print_first_hour(subjects,num); 33 | 34 | } else { 35 | print_first_hour(subjects,-1); 36 | } 37 | } else { 38 | if(weekday==0) { 39 | print_first_hour(subjects,-1); 40 | } else { 41 | print_first_hour(subjects,weekday-1); 42 | } 43 | } 44 | return 0; 45 | 46 | } 47 | 48 | int find_day (int n) { 49 | return n%7; 50 | } 51 | 52 | void print_first_hour (char* sub, int i) { 53 | if (i==-1) { 54 | cout<<"Holiday"; 55 | } 56 | else { 57 | if (sub[i] == 'E') cout<<"English"; 58 | else if (sub[i] == 'P') cout<<"Physics"; 59 | else if (sub[i] == 'C') cout<<"Chemistry"; 60 | else if (sub[i] == 'M') cout<<"Maths"; 61 | else if (sub[i] == 'R') cout<<"Computer Science"; 62 | } 63 | 64 | } 65 | 66 | bool check_Even_Sat (int d) { 67 | if (d%2 == 0) { 68 | return false; 69 | } else { 70 | return true; 71 | } 72 | } 73 | 74 | int find_Odd_Sat_Num (int d) { 75 | return (d/2)+1; 76 | } 77 | 78 | -------------------------------------------------------------------------------- /reviseC/TAT1/README.md: -------------------------------------------------------------------------------- 1 | # TEST YOUR SKILLS 2 | 3 | ## Take-A-Test 1 4 | 5 | ### Question 1 -- Second Smallest Number 6 | 7 | Given a set of n elements, write a program to find the second smallest number in that set. 8 | [**See Answer**](ques1.cpp) 9 | 10 | ### Question 2 -- Euclids Algorithm 11 | 12 | Find the GCD of two given numbers using euclids algorithm 13 | [**See Answer**](ques2.c) 14 | 15 | ### Question 3 -- Self power or mth power 16 | 17 | Given two number ‘n’ and ‘m’, write a C++ function to find Sum. Where Sum = 1m+2m+3m+...+nm, when m > 0 and Sum = 1^1+2^2+3^3+...+n^n when m = 0. 18 | 19 | For example, when n = 5 and m = 3, Sum = 1^3+2^3+3^3+4^3+5^3 = 225 and when n = 5 and when m = 0, Sum = 1^1+2^2+3^3+4^4+5^5 = 3413. 20 | 21 | **Boundary Conditions** 22 | 23 | 0≤n,m≤10 24 | 25 | **Input Format** 26 | 27 | First line of input contains an integer, n 28 | 29 | Second line of input contains an integer, m 30 | 31 | **Output Format** 32 | 33 | Contains either the value of Sum if the given input satisfies the boundary conditions and ‘Invalid input’ otherwise. 34 | 35 | [**See Answer**](ques3.cpp) 36 | 37 | ### Question 4 -- Subject of the first hour 38 | 39 | Time table of students in a schools has the following subjects and represented by a letter: 40 | 41 | ``` 42 | E - English 43 | 44 | P - Physics 45 | 46 | C - Chemistry 47 | 48 | M - Maths 49 | 50 | R - Computer Science 51 | ``` 52 | 53 | Assume the current day is Sunday. Given first hours of weekdays from Monday to Friday and a number ‘n’, write a C++ function to print the first hour of ‘nth’ day. Odd Saturdays from today are working days and even Saturdays are holidays and Sundays are always holidays. First hour of an mth odd Saturday is first hour of (m%5)th day of week. 54 | 55 | **Example 1** 56 | If first hours of Monday to Friday are given as P, C, M, R, E and the value of n is 15. Weekday for n as 15 is 1 which corresponds to Monday, so print the subject of first hour as Physics. 57 | 58 | **Example 2** 59 | If first hours of Monday to Friday are given as P, C, M, R, E and the value of n is 13. Weekday for n as 13 is 6 which corresponds to Saturday and it is Second Saturday, so print the subject of first hour as Holiday. 60 | 61 | [**See Answer**](ques4.cpp) 62 | 63 | ### Question 5 -- Recursive fibonacci 64 | 65 | Write a recursive function to find and print fibonacci series till the entered number n. 66 | 67 | **Input Format** 68 | 69 | value of n. 70 | 71 | **Output Format** 72 | 73 | fibonacci series till n. -------------------------------------------------------------------------------- /IntroToOOP/tryCatch.cpp: -------------------------------------------------------------------------------- 1 | /* ============================================================ */ 2 | /* ===== Sammple program to illustrate exception handling ===== */ 3 | /* ============================================================ */ 4 | 5 | // Make a calculator that operates only on positive numbers 6 | 7 | #include 8 | using namespace std; 9 | 10 | int add (int x, int y) { 11 | if (x<0 || y<0) { 12 | throw 10; 13 | } 14 | return x+y; 15 | } 16 | 17 | int sub (int x, int y) { 18 | if (x<0 || y<0) { 19 | throw 10; 20 | } else if (x>a; 47 | cout<< "Enter the value of b: "; cin>>b; 48 | cout<<"\na. add\nb. subtract\nc. multiply \nd divide"<>ch; 50 | if (ch == 'a' || ch == 'A') { 51 | try { 52 | int res; 53 | res = add (a,b); 54 | cout< 6 | #include 7 | 8 | struct M1 { 9 | char name[50]; 10 | int numItems; 11 | struct items { 12 | char name[20]; 13 | float cost; 14 | }item[10]; 15 | }; 16 | 17 | struct customers { 18 | char name[50]; 19 | int acno; 20 | float balance; 21 | }; 22 | 23 | float findSpent(struct M1 sh[], int n); 24 | float findRemaining(float spent, struct customers c[], int n); 25 | 26 | int main () { 27 | 28 | // Input all the required data 29 | int nc,i,j,m; 30 | scanf("%d", &nc); 31 | struct customers abc[nc]; 32 | for(i=0;i 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | #define pb push_back 6 | #define mp make_pair 7 | #define PI 3.14159265358979323 8 | #define debug(x) cout<<"Case "< vi; 14 | typedef vector vll; 15 | typedef pair pii; 16 | typedef pair pll; 17 | typedef vector < pii > vpii; 18 | typedef vector < pll > vpll; 19 | typedef vector vs; 20 | 21 | //cyber_rajat 22 | 23 | //to calculate in degree 24 | vector indegree(int n,vector>adj) 25 | { 26 | vectora(n,0); 27 | for(int i=0;i topological_sort(int n,vectorin_degree,vector>adj) 37 | { 38 | vectorsort; 39 | bool visited[n]={false}; 40 | queueq; 41 | for(int i=0;i>n>>m; 69 | 70 | vectortemp; 71 | vector>adj(n,temp); 72 | for(int i=0;i>u>>v; 75 | adj[u].push_back(v); 76 | } 77 | //to find the in degree of each vertex 78 | vectorin_degree(n,0); 79 | in_degree=indegree(n,adj); 80 | vector sort=topological_sort(n,in_degree,adj); 81 | 82 | if(sort.size()!=n) 83 | { 84 | cout<<"Toposort is not possible since there is atleast one cycle"<Input Format
17 | First line contains the value of ‘n’
18 | Output Format
19 | Print the pattern given in the question 20 |

21 | [See The Answer Here](ques1.c) 22 | 23 | ### Question 2 24 | Given the value of ‘n’, develop an algorithm and write a C program to print the following pattern. When the value of ‘n’ is 5, the pattern will look as follows: 25 | ``` 26 | ***** 27 | 28 | **** 29 | 30 | *** 31 | 32 | ** 33 | 34 | * 35 | ``` 36 | 37 | Input Format
38 | First line contains the value of ‘n’ 39 |
40 | Output Format
41 | Print the pattern given in the question 42 |

43 | [See the Answer Here](ques2.c) 44 | 45 | ### Question 3 46 | Given the value of ‘n’, develop an algorithm and write a C program to print the following pattern. When the value of ‘n’ is 5, the pattern will look as follows: 47 | ``` 48 | * 49 | 50 | *** 51 | 52 | ***** 53 | 54 | ******* 55 | 56 | ********* 57 | ``` 58 | 59 | Input Format
60 | First line contains the value of ‘n’ 61 |
62 | Output Format
63 | Print the pattern given in the question 64 |

65 | [See the Answer Here](ques3.c) 66 | 67 | ### Question 4 68 | Given the value of ‘n’, develop an algorithm and write a C program to print the following pattern. When the value of ‘n’ is 5, the pattern will look as follows: 69 | ``` 70 | 0 1 0 1 0 71 | 72 | 0 1 0 1 73 | 74 | 0 1 0 75 | 76 | 0 1 77 | 78 | 0 79 | ``` 80 | 81 | Input Format
82 | First line contains the value of ‘n’ 83 |
84 | Output Format
85 | Print the pattern given in the question 86 |

87 | [See the Answer Here](ques4.c) 88 | 89 | ### Question 5 90 | Given the value of ‘n’, develop an algorithm and write a C program to print the following pattern. When the value of ‘n’ is 5, the pattern will look as follows: 91 | ``` 92 | **$ 93 | 94 | **$**$ 95 | 96 | **$**$**$ 97 | 98 | **$**$**$**$ 99 | 100 | **$**$**$**$**$ 101 | ``` 102 | 103 | Input Format
104 | First line contains the value of ‘n’ 105 |
106 | Input Format
107 | Print the pattern given in the question 108 |

109 | [See the Answer Here](ques5.c) 110 | 111 | ### Question 5 112 | Given the value of ‘n’, develop an algorithm and write a C program to print the following pattern. When the value of ‘n’ is 5, the pattern will look as follows: 113 | ``` 114 | * 115 | 116 | * * 117 | 118 | * * 119 | 120 | * * 121 | 122 | * 123 | ``` 124 | 125 | Input Format
126 | First line contains the value of ‘n’ 127 |
128 | Input Format
129 | Print the pattern given in the question 130 |

131 | [See the Answer Here](ques5.c) 132 | 133 | [Go Back](./..){: .btn} -------------------------------------------------------------------------------- /Structures/README.md: -------------------------------------------------------------------------------- 1 | # Structures 2 | A structure, is basically a collection of elements of ***Same/Different*** data types.
3 | More formally, A struct in the C programming language (and many derivatives) is a composite data type declaration that defines a physically grouped list of variables to be placed under one name in a block of memory, allowing the different variables to be accessed via a single pointer, or the struct declared name which returns the same address. 4 | ## Why structures over array? 5 | An array is a collection of elements of same data type. Using an array to solve real world problems is not logical as the data that the user may want to store can contain elements of many different data types, such as integer, float, character, string.... and the list goes on.
6 | Therefore, using structures over array is a more logical choice as it provides more flexibility to store more diverse data in a single functional unit 7 | ## Declaration 8 | The general syntax for a struct declaration in C is:
9 | ```c 10 | struct tag_name { 11 | type member1; 12 | type member2; 13 | /* declare as many members as desired, but the entire structure size must be known to the compiler. */ 14 | }; 15 | ``` 16 | Using structures is the first step we take to store and solve real world problems using code. 17 | 18 | ## Nested Structures 19 | Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure as we declare structure members inside a structure.
20 | The structure variables can be a normal structure variable or a pointer variable to access the data. You can learn below concepts in this section.
21 | 22 | ### Nested structures declaration 23 | * Way #1 24 | ```c 25 | struct date 26 | { 27 | int date; 28 | int month; 29 | int year; 30 | }; 31 | 32 | struct Employee 33 | { 34 | char ename[20]; 35 | int ssn; 36 | float salary; 37 | struct date doj; 38 | }emp1; 39 | ``` 40 | * Way #2 41 | ```c 42 | struct Employee 43 | { 44 | char ename[20]; 45 | int ssn; 46 | float salary; 47 | struct date 48 | { 49 | int date; 50 | int month; 51 | int year; 52 | }doj; 53 | }emp1; 54 | ``` 55 | 56 | ### Index 57 | 1. [Example of using structure in C language](struct.c) 58 | 2. [Making n instances of structure using arrays](nstruct.c) 59 | 3. [Pass structure as function arguement (call by value)](structinfunVal.c) 60 | 4. [Pass structure as function arguement (call by reference)](structinfun.c) 61 | 5. [Read the data for n students using structures
1. Display number of students along with regno who scored centum in maths
2. Number of students along with regno who failed in all three subjects](practiseStruct.c) 62 | 63 | ### Assignment 64 | WAP A C program to read the employee details and calculate and display the employee details along with his/her gross pay, given that, 65 | ```c 66 | gross = bp + 80%DA - 3%PF - 5%LIC 67 | ``` 68 | Your structure can contain the following elements 69 | * emp_number 70 | * emp_name 71 | * emp_designation 72 | * basic_pay 73 | * pf (provident fund) 74 | * da (dearness allowance) 75 | * gross pay 76 | 77 | [Go Back](./..){: .btn} 78 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at madhavbahl10@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /Structures/practiseStruct.c: -------------------------------------------------------------------------------- 1 | /* ========================================================== */ 2 | /* 3 | Question: Read the data for n students using structures 4 | 1. Display number of students along with regno 5 | who scored centum in maths 6 | 2. Number of students along with regno who failed in 7 | all three subjects 8 | */ 9 | /* ========================================================== */ 10 | 11 | #include 12 | 13 | struct stud { 14 | int regno; 15 | char name[100]; 16 | struct marks { 17 | int mat; 18 | int cse; 19 | int phy; 20 | }score; 21 | }students[20]; 22 | 23 | // Various function definitions 24 | void readVal(struct stud *s,int i) { 25 | printf("\n\t\t\t\t STUDENT NUMBER %d\n",i+1); 26 | printf("\nEnter the register number (integer): "); 27 | scanf("%d",&s->regno); 28 | printf("Enter the name of the student (string): "); 29 | scanf("%s",s->name); 30 | printf("\n READING THE MARKS OF THIS STUDENT\n"); 31 | printf("\nEnter the marks in mathematics (out of 100): "); 32 | scanf("%d",&s->score.mat); 33 | printf("Enter the marks in Computer Science (out of 100): "); 34 | scanf("%d",&s->score.cse); 35 | printf("Enter the marks in Physics (out of 100): "); 36 | scanf("%d",&s->score.phy); 37 | } 38 | 39 | void dispVal(struct stud *s, int i) { 40 | printf("\n\n\t\t\t\t STUDENT NUMBER %d\n",i+1); 41 | printf("\nThe register number of the student is: %d",s->regno); 42 | printf("\nThe name of the student is: %s",s->name); 43 | printf("\n DISPLAYING THE MARKS OF THIS STUDENT\n"); 44 | printf("\nThe marks of the student in maths is: %d",s->score.mat); 45 | printf("\nThe marks of the student in computer science is: %d",s->score.cse); 46 | printf("\nThe marks of the student in physics is: %d",s->score.phy); 47 | } 48 | 49 | int main() { 50 | int n,i,j,regs[20],count; 51 | printf("Enter the number of students in your class: "); 52 | scanf("%d",&n); 53 | printf("\n\t\t\t READING THE INFORMATION OF STUDENTS\n"); 54 | // Code block to read the students data 55 | for(i=0;i 13 | Input Format
14 | First line contains the BillAmount 15 |
16 | Second line contains the BuyingDay 17 |
18 | Third line contains the PayingDay 19 | Output Format
20 | Print the amount to be paid with only two decimal places 21 |

22 | [See The Answer Here](ques1.c) 23 | 24 | ### Question 2 25 | Given a three digit identification number, the identification number 26 | is said to be valid if sum of square of the digits is divisible by 10. 27 | Given an identification number, develop an algorithm and write the C code 28 | to print ‘Valid’ or ‘Invalid’. For example, 505, 608 are valid and number 444 is invalid. 29 |
30 | Input Format
31 | First line contains a three digit identification number
32 | Output format 33 | Print either Valid or Invalid 34 |

35 | [See the Answer Here](ques2.c) 36 | 37 | ### Question 3 38 | Part-time employees are paid ‘x’ amount for each 40-hours they work and for the remaining hours they are paid ‘y’ amount. A part-time employee has worked ‘z’ hours per day for six days. Given the value of ‘x’ and ‘y’ and ‘z’, develop an algorithm and write a C code to find the amount to be paid. For example, if the value of x is 2000, ‘y’ is 100 and ‘z’ is 15 then the amount to be paid is 5000. 39 | 40 | 41 |
42 | Input Format
43 | First line contains amount paid for each 40 hours, x 44 | 45 | Second line contains amount paid for each extra hour, y 46 | 47 | Third line contains number of hours worked per day, z
48 | Output format 49 | Print the amount to be paid 50 |

51 | [See the Answer Here](ques3.c) 52 | 53 | ### Question 4 54 | The following is a hypothetical condition. There are different cadre of employees in railways department. There are four cadres of employees ‘A’, ‘B’, ‘C’ and ‘D’. Each cadre has different rate of discount as follows: 55 | 56 | ‘A’ – 10% 57 | 58 | ‘B’ - 8% 59 | 60 | ‘C’ – 6% 61 | 62 | ‘D’ – 5% 63 | 64 | Given the cadre of employee, develop an algorithm and write the ‘C’ program to print the rate of discount for the employee. The input shall be given in upper or lower case letter. Print ‘Invalid input’ if the input is any other character 65 | 66 | 67 |
68 | Input Format
69 | First line contains the cadre of employee, this input shall be given in upper or lower case
70 | Output format 71 | Print the discount percentage for the employee. Print ‘%’ symbol at the end of the output 72 |

73 | [See the Answer Here](ques4.c) 74 | 75 | ### Question 4 76 | Given a character, depending on the character write an algorithm and C program to print ‘You have entered an alphabet’ if the character entered is a letter or ‘You have entered a digit’ if the character entered is a number and ‘You have entered a special character’ otherwise. 77 | 78 |
79 | Input Format
80 | 81 | First line contains the character entered by the user
82 | Output format 83 | Print either 84 | 85 | You have entered an alphabet or 86 | 87 | You have entered a digit or 88 | 89 | You have entered a special character 90 |

91 | [See the Answer Here](ques4.c) 92 | 93 | [Go Back](./..){: .btn} -------------------------------------------------------------------------------- /reviseC/ReviseArrays/README.md: -------------------------------------------------------------------------------- 1 | ## Practise Expressions and conditional statements 2 | 3 | ### Sample Problem 1 4 | Given a list of ‘n’ numbers, write an algorithm and a C program to print all numbers that have ‘mid property’. A number in the list is said to have mid property if the number to its left is less than itself and the number in the right to itself has value greater than itself. First number in the list is said to have mid property if the number to its right is greater than itself and the last number is said to have mid property if the number to its left is less than itself. For example, if the list of 10 numbers is 15, 12, 13, 45, 23, 56, 65, 11, 9 and 25 then the numbers with mid property are 13, 56 and 25. If none of the numbers in the list has mid property then print ‘No number has mid property’. 5 | 6 | Input Format 7 | First line contains the number of elements in the list, n 8 | 9 | Next ‘n’ lines contains the elements in the list
10 | Output Format 11 | Print numbers with mid property or print ‘No number has mid property’ when there are no elements with the property 12 |

13 | [Click here to see the answer](ques1.c) 14 | 15 | ### Sample Problem 2 16 | Given a String with spaces, write an algorithm and a C program to count the number of words in it and length of the longest word. For example, if the input string is ‘I love programming’ then the number of words is three and length of the longest string is 11. 17 | 18 | Input Format 19 | First line contains the sentence to be analyzed
20 | Output Format 21 | Print the number of words in the first line and length of the longest word in the second line 22 | 23 | 24 |

25 | [Click here to see the answer](ques2.c) 26 | 27 | ### Sample Problem 3 28 | Given a NXN matrix of numbers, write an algorithm and a C code to check if the outer elements are same. For example if the 4X4 matrix as shown below is given then print ‘Same’. 29 | 30 | ![image](https://user-images.githubusercontent.com/26179770/34876698-b8a771ca-f7c8-11e7-8316-ecbded23d310.png) 31 | 32 | If the matrix given is as follows then print ‘Not same’. 33 | ![image](https://user-images.githubusercontent.com/26179770/34876700-bb6ece12-f7c8-11e7-9daa-374c0f40f7aa.png) 34 | 35 | Input Format 36 | First line contains the dimension of the matrix, n 37 | 38 | Next nXn lines, contains elements of the matrix given row-wise
39 | Output Format 40 | Print either Same or Not same 41 |

42 | [Click here to see the answer](ques3.c) 43 | 44 | ### Sample Problem 4 45 | Given a NXN character matrix, write an algorithm and a C program to toggle the case of the characters along the diagonals of the matrix, for example given a 5X 5 matrix as follows: 46 | ![image](https://user-images.githubusercontent.com/26179770/34877046-56b6a90c-f7ca-11e7-97dc-b37c2fa6bf72.png) 47 | 48 | Then the output matrix should be: 49 | ![image](https://user-images.githubusercontent.com/26179770/34877049-596ca2f0-f7ca-11e7-8f87-3d1edccbdb03.png) 50 | 51 | Input Format 52 | First line contains the dimension of the matrix, n 53 | Next nXn lines, contains elements of the matrix given row-wise
54 | 55 | Output Format 56 | Print the output nXn matrix in matrix format 57 |

58 | [Click here to see the answer](ques4.c) 59 | 60 | ### Sample Problem 5 61 | Given ‘n’ words, write an algorithm and the C program to print all the ‘Leader words’. A word is said to be a leader word if it is lexicographically greater than all the words that are right to it. Last word is always a ‘Leader word’. For example, given five strings rat, cat, apple, ball and bag the output should be rat, cat, ball and bag. 62 | 63 | Input Format 64 | First line contains the number of words, n 65 | 66 | Next ‘n’ lines contain the words
67 | 68 | Output Format 69 | Print the leader words one in each line 70 |

71 | [Click here to see the answer](ques5.c) 72 | 73 | [Go Back](./..){: .btn} -------------------------------------------------------------------------------- /Sort/Quick_Sort/quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | #define pb push_back 6 | #define mp make_pair 7 | #define PI 3.14159265358979323 8 | #define debug(x) cout<<"Case "< vi; 14 | typedef vector vll; 15 | typedef pair pii; 16 | typedef pair pll; 17 | typedef vector < pii > vpii; 18 | typedef vector < pll > vpll; 19 | typedef vector vs; 20 | 21 | //Handle:cyber_rajat 22 | 23 | //defintion of structure node 24 | struct node 25 | { 26 | int data; 27 | node *next,*prev; 28 | }; 29 | //decleration of functions 30 | void quicksort(node *head,node *end); 31 | node* partition(node *head,node *end); 32 | void swap(int *p,int* q); 33 | void insertion_at_end(node **head,node **tail,int data); 34 | void display(node *p); 35 | int main() 36 | { 37 | int data,choice,pos; 38 | node *head=NULL,*end=NULL; 39 | while(1) 40 | { 41 | cout<<"\nEnter your choice" 42 | <<"\n1.Insertion at end of list" 43 | <<"\n2.Display list" 44 | <<"\n3.Sort the List using Quick sort technique" 45 | <<"\n4.Exit::::"; 46 | cin>>choice; 47 | switch(choice) 48 | { 49 | case 1:cout<<"\nEnter the data to insert:"; 50 | cin>>data; 51 | insertion_at_end(&head,&end,data); 52 | break; 53 | case 2:display(head); 54 | break; 55 | case 3:quicksort(head,end); 56 | cout<<"\nList After Quick Sort:::"; 57 | display(head); 58 | break; 59 | case 4:exit(0); 60 | default:cout<<"\nInvalid input"; 61 | } 62 | } 63 | return 0; 64 | } 65 | //recursive function for quick sort 66 | void quicksort(node *head,node *end) 67 | { 68 | if(head!=NULL && head!=end && head->next !=end) 69 | { 70 | node* q; 71 | q=partition(head,end); 72 | quicksort(head,q->prev); 73 | quicksort(q->next,end); 74 | } 75 | } 76 | //function for partitioning the list 77 | node* partition(node *head,node *end) 78 | { 79 | int pivot=end->data; 80 | node *q,*temp=NULL; 81 | q=head; 82 | temp=head; 83 | 84 | while(temp!=end) 85 | { 86 | if(head->data<=pivot) 87 | { 88 | q=q->next; 89 | } 90 | else if((temp->data)<=pivot) 91 | { 92 | swap(&(temp->data),&(q->data)); 93 | q=q->next; 94 | } 95 | temp=temp->next; 96 | } 97 | swap(&(q->data),&(end->data)); 98 | return q; 99 | } 100 | //swap the data of two nodes 101 | void swap(int * p,int * q) 102 | { 103 | int temp; 104 | temp=*p; 105 | *p=*q; 106 | *q=temp; 107 | } 108 | //insertion at the end of list 109 | //here head and end are passed by reference 110 | void insertion_at_end(node **head,node **tail,int data) 111 | { 112 | node *ptr=NULL; 113 | ptr=new node; 114 | ptr->data=data; 115 | if(*head==NULL) 116 | { 117 | ptr->prev=ptr->next=NULL; 118 | *head=(*tail)=ptr; 119 | } 120 | else 121 | { 122 | (*tail)->next=ptr; 123 | ptr->prev=*tail; 124 | ptr->next=NULL; 125 | *tail=ptr; 126 | } 127 | } 128 | //Display the list 129 | void display(node *p) 130 | { 131 | cout<<"\nList is::"; 132 | if(p==NULL) 133 | { 134 | cout<<"\nList is Empty"; 135 | return; 136 | } 137 | while(p!=NULL) 138 | { 139 | cout<<" -> "<data; 140 | p=p->next; 141 | } 142 | 143 | -------------------------------------------------------------------------------- /reviseC/ques4.c: -------------------------------------------------------------------------------- 1 | /* ========== 2 | Question: Imagine the case of a darshan queue at a holy temple, where the queue is 3 | divided into three levels: I, II, and III. There are three categories of 4 | darshan: i) Normal, ii) Special Darshan, and iii) Special Darshan with 5 | Puja. A devotee for normal darshan is entered into the queue of level -III. 6 | When it is found that queue level II is not full, then the devotee from 7 | front of the queue level III is removed and inserted to the queue level II. 8 | Similarly, when queue level I is not full, a devotee from the front of level 9 | II is removed and inserted to level I. However, a devotee for Special 10 | Darshan and Special darshan with puja is inserted directly in the end of 11 | queue level II and I respectively. Write a menu driven program in C / 12 | C++ to implement the above data structure and all its operations. 13 | ========== */ 14 | 15 | // Include the required header files 16 | #include 17 | 18 | // Consider that the maximum number of people in each queue ca be 15 19 | const max_size = 10; 20 | 21 | // Functions for queue operations 22 | void addDevotee(int queue[], int *front, int *rear, int *qno) { 23 | if(*rear == max_size-1) { 24 | printf("\nAll The Queues Are Full! \nPlease Try Again After Some Time!"); 25 | } else if(isEmptyQ(queue, &front, &rear) == 1) { 26 | *front=0; 27 | *rear =0; 28 | queue[*rear]=1; 29 | printf("\nCongrats! You found a place in the queue %d",*qno); 30 | } else { 31 | *rear = *rear+1; 32 | queue[*rear]=1; 33 | printf("\nCongrats! You found a place in the queue %d",*qno); 34 | } 35 | } 36 | void removeDevotee(int queue, int *front, int *rear, int *qno) { 37 | if(isEmptyQ(queue, &front, &rear) == 1) { 38 | printf("\nThe queue %d is empty", *qno); 39 | return; 40 | } else if (*front == *rear) { 41 | *front = -1; 42 | *rear = -1; 43 | } else { 44 | *front = *front + 1; 45 | } 46 | } 47 | int isEmptyQ(int queue[], int *front, int *rear) { 48 | if(*front == -1 && *rear == -1) { 49 | return 1; 50 | } else { 51 | return 0; 52 | } 53 | } 54 | int isNotFull(int queue[], int *front, int *rear, int *qno) { 55 | if(*rear == max_size-1) { 56 | return 0; 57 | } else { 58 | *qno = *qno-1; 59 | printf("\nWAIT!!! The Queue level %d is not yet full!",*qno); 60 | return 1; 61 | } 62 | } 63 | 64 | // Main Function 65 | int main() { 66 | // Declare the needed variables to solve this problem 67 | int choice,q1[max_size],q2[max_size],q3[max_size],f1=-1,f2=-1,f3=-1,r1=-1,r2=-1,r3=-1,cq; 68 | 69 | while(1) { 70 | // Menu 71 | printf("\n\n\t\t\t Managing queue at temple\n"); 72 | printf("\nChoose the category: "); 73 | printf("\n 1. Normal Devotee"); 74 | printf("\n 2. Special Devotee"); 75 | printf("\n 3. Special Devotee with puja"); 76 | printf("\nEnter your choice: "); 77 | scanf("%d",&choice); 78 | 79 | // for normal devotee 80 | if(choice == 1) { 81 | // Add the devotee to queue level 3 82 | cq=3; 83 | addDevotee(q3,&f3,&r3,&cq); 84 | // Check for a position in queue 2 85 | if(isNotFull(q2,&f2,&r2,&cq) == 1) { 86 | // Remove the man from queue 3 and put him in queue 2 87 | removeDevotee(q3,&f3,&r3,&cq); 88 | addDevotee(q2,&f2,&r2,&cq); 89 | } else { 90 | printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); 91 | } 92 | // Check for a position in queue 1 93 | if(isNotFull(q1,&f1,&r1,&cq) == 1) { 94 | // Remove the man from queue 3 and put him in queue 2 95 | removeDevotee(q2,&f2,&r2,&cq); 96 | addDevotee(q1,&f1,&r1,&cq); 97 | } else { 98 | printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); 99 | } 100 | 101 | } 102 | // for special darshan devotee 103 | else if(choice == 2) { 104 | // Add the devotee to queue level 2 105 | cq=2; 106 | addDevotee(q2,&f2,&r2,&cq); 107 | // Check for a position in queue 1 108 | if(isNotFull(q1,&f1,&r1,&cq) == 1) { 109 | // Remove the man from queue 3 and put him in queue 2 110 | removeDevotee(q2,&f2,&r2,&cq); 111 | addDevotee(q1,&f1,&r1,&cq); 112 | } else { 113 | printf("\nQueue level 1 is full! the devotee stays in Queue 2 for some time!"); 114 | } 115 | } 116 | // for special darshan with puja devotee 117 | else if(choice == 3) { 118 | // Add the devotee to queue level 1 119 | cq=1; 120 | addDevotee(q1,&f1,&r1,&cq); 121 | } 122 | else { 123 | printf("\nInvalid Input"); 124 | } 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /reviseC/ReviseStruct/README.md: -------------------------------------------------------------------------------- 1 | ## Practise Structures and Functions 2 | 3 | ### Sample Problem 1 -- Find Potential Teammates 4 | A game is conducted with ‘n’ players. Given the name, age and size of tube with each player and a player name ‘p’, write an algorithm and the C program to print name of all the players who can be partner of the player ‘p’. A player ‘q’ can be partner of player ‘p’ if the age of ‘q’ is less than player ‘p’ and tube size of player ‘q’ is greater than tube size of player ‘p’. 5 | ``` 6 | For example, given details of five salespersons as follows: 7 | 8 | Name1, 34, 15 9 | 10 | Name2, 23, 12 11 | 12 | Name3, 45, 9 13 | 14 | Name4, 19, 34 15 | 16 | Name5, 32, 14 17 | 18 | And player ‘p’ name as Name1. Name of players who can be partner of player ‘p’ are Name2, Name5. 19 | ``` 20 | 21 | Input Format 22 | First line contains the number, n 23 | 24 | Next n lines contain details of ‘n’ players such as name, age and size in order and separated by space 25 | 26 | Next line contains the name of the player, p
27 | Output Format 28 | Print all the name of players with age less than age of player p and tube size less than tube size of player p 29 |

30 | [Click here to see the answer](ques1.c) 31 | 32 | ### Sample Problem 2 -- Best sales person 33 | A company stores the name, age and sales made in five cities of their salespersons, given the details of ‘n’ employees, write an algorithm and the C program to find the best sales person. Best sales person is the one who has made maximum sales in the company. For example given the details of six salespersons with the following details: 34 | ``` 35 | SP1, 34, 45, 18, 22, 38, 37 36 | 37 | SP2, 32, 46, 15, 23, 35, 29 38 | 39 | SP3, 29, 47, 16, 30, 35, 35 40 | 41 | SP4, 31, 49, 12, 32, 36, 40 42 | 43 | SP5, 23, 45, 11, 30, 35, 39 44 | 45 | SP6, 29, 41, 15, 31, 33, 37 46 | ``` 47 | Then the best salesperson is SP4. 48 | 49 | Input Format 50 | First line contains the number of salespersons, n 51 | 52 | Next n lines contain the details of ‘n’ salespersons such as name, age and sales made by the salesperson in five cities separated by space
53 | Output Format 54 | Print the name of the best sales person 55 |

56 | [Click here to see the answer](ques2.c) 57 | 58 | ### Sample Problem 3 -- Recursive reverse string 59 | Write a recursive ‘C’ program to print the reverse of the string. 60 | Input Format 61 | First line contains the string, S
62 | Output Format 63 | Print reverse of string, S 64 |

65 | [Click here to see the answer](ques3.c) 66 | 67 | ### Sample Problem 4 -- Convert Base 68 | A Quadadecimal number system is a hypothetical number system with base 14. The digits of the number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D. A decimal number ‘x’ can be converted to quadadecimal number by dividing it repeatedly by 14. The reminders obtained during division put together in reverse order form the quadadecimal equivalen of ‘x’. Decimal number 82 is converted to its quadadecimal equivalent (5C ) as follows: 69 | ![image](https://user-images.githubusercontent.com/26179770/34890904-aeb75460-f7f9-11e7-9ade-02a77544f9e8.png) 70 | 71 | Input Format 72 | First line contains the number n, in decimal number system
73 | Output Format 74 | Print the quadadecimal equivalent of number, n 75 |

76 | [Click here to see the answer](ques4.c) 77 | 78 | ### Sample Problem 5 -- Amount remaining after shopping 79 | Sherley goes for a shopping to a mall ‘M1’ . She uses credit card of bank ‘ABC’ for her purchases. Account details of each customer of ‘ABC’ contain Account holder name, Account number and Balance. Details of customers of mall ‘M1’ includes customer name and list of items purchased and cost of the items. Given the details of ‘n’ customers of bank ‘ABC’ and the purchase details of ‘m’ customers to mall ‘M1’, design an algorithm and write a C program to print the name of items purchased by Sherley and the balance amount in the account of Sherley in the bank ‘ABC’. 80 | 81 | ``` 82 | For example, if details (Name, Account number, Balance) of six customers of bank are given as follows: 83 | 84 | Raju 12356 1000.00 85 | 86 | Sam 12789 980.00 87 | 88 | Ram 13457 975.50 89 | 90 | Sherley 16789 1500.00 91 | 92 | Sheela 17890 1345.50 93 | 94 | Kamala 12378 2567.75 95 | ``` 96 | 97 | Details (Name, number of items purchased, item name1, cost1, item name2, cost2,...) of three customers of mall m1 are given as follows: 98 | 99 | ``` 100 | Ram 2 Bread 50.00 Jam 25.00 101 | 102 | Sherley 3 Milk 20.00 Bread 50.00 Butter 31.50 103 | 104 | Mukesh 4 Chocolate 15.00 Chips 12.50 Rice 29.00 Dall 31.25 105 | ``` 106 | Assume that the customer of mall has purchased only a maximum of ten items 107 | 108 | Input Format 109 | First line contains the number of customers of ABC bane, n
110 | 111 | Next ‘n’ lines contain the details of customers of bank such as Account holder name, Account number and Balance in order and separated by space
112 | 113 | 114 | 115 | Next line contains the number of customers to mall M1, m
116 | 117 | Next ‘m’ lines contains the details of customers to mall such as name, number of items purchased ‘r’, 2*r detail such as item name and cost. Each detail is separated by a sp
118 | Output Format 119 |
Print name of the items purchased by Sherley, one item name in a line and balance amount in account of Sherley in the bank 120 |

121 | [Click here to see the answer](ques4.c) 122 | 123 | 124 | [Go Back](./..){: .btn} -------------------------------------------------------------------------------- /pointersInC/README.md: -------------------------------------------------------------------------------- 1 | # Pointers 2 | * Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. 3 | * Variable that contains address in memory of another variable 4 | * We can have a pointer to any variable type 5 | * Unary or monadic operator & gives the `address of a variable` 6 | * operator * gives the `contents of an object pointed to by a pointer` 7 | * To declare a pointer to a variable : 8 | ```c 9 | datatype * name_Of_Variable;   10 | ``` 11 | EXAMPLE 12 | ```c 13 | int num = 10; 14 | int *nump = # 15 | 16 | float data = 105.8; 17 | float *ptr; 18 | ptr = &data; 19 | ``` 20 | 21 | ### Consider the following example 22 | ```c 23 | #include 24 | int main() { 25 | int a=5; 26 | int *P; 27 | P=&a; 28 | temp=&P; 29 | printf("\naddress of a = value of P: %u",P); 30 | printf("\nValue of a: %d",a); 31 | printf("\nValue of *P: %d",*P); 32 | } 33 | ``` 34 | 35 | Here, 36 | * P stores the memory address of a. 37 | * *P stores the value of a 38 | 39 | ### Dereferencing a pointer variable 40 | ```c 41 | #include 42 | int main() { 43 | float data = 100; 44 | float *ptr = &data; 45 | printf("%x %f\n",ptr, *ptr); 46 | *ptr = 200; 47 | printf("%x %f\n",ptr, *ptr); 48 | } 49 | ``` 50 | NOTE**
51 | * Never try to assign a specific integer value to a pointer variable, it can be disastrous.
52 | * If a pointer is not initialized during declaration, it is wise to give it a `NULL` value.
53 | ``float *ptr = NULL``
54 | * The NULL pointer is a valid address for any data type, but NULL is not memory address 0. 55 | * It is an error to dereference a pointer whose value is NULL, such an error may cause your program to crash, or behave erratically. 56 | 57 | ## Operations on pointer variables 58 | * Assignment
59 | the value of one pointer variable can be assigned to another pointer variable of the same type 60 | * Relational Operations
61 | two pointer variables of the same type can be compared for equality, and so on 62 | * Arithmetic Operations
63 | integer values can be added to and subtracted from a pointer variable, value of one pointer variable can be subtracted from another pointer variable
64 | Four arithmetic operators can be used on pointers: ++, --, +, and –
65 | Consider that ptr is an integer pointer which points to the address 1000 66 | Assume 4 bytes are allocated for integers. After the following operation `ptr++` ptr will point to location 1004, On integer pointers -- will decrement by 4. 67 | 68 | ### Pointing to Array Elements 69 | ```c 70 | #include 71 | int main() { 72 | int gradeList[8] = {92,85,75,88,79,54,34,96}; 73 | int *myGrades = gradeList; 74 | printf("1st element of gradelist using array index: %d\n",gradeList[0]); 75 | printf("1st element of gradelist using pointer: %d\n",*myGrades); 76 | printf("2nd element of gradelist using array index: %d\n", *(myGrades + 1)); 77 | printf("2nd element of gradelist using pointer: %d\n", myGrades[1]); 78 | printf("3rd element of gradelist using array index: %d\n", *(myGrades + 2)); 79 | printf("3rd element of gradelist using pointer: %d\n", myGrades[2]); 80 | printf("4th element of gradelist using array index: %d\n", *(myGrades + 3)); 81 | printf("4th element of gradelist using pointer %d\n", myGrades[3]); 82 | printf("5th element of gradelist using array index: %d\n", *(myGrades + 4)); 83 | printf("5th element of gradelist using pointer: %d\n", myGrades[4]); 84 | return 0; 85 | } 86 | ``` 87 | 88 | ### Pointer to an Array and Array of Pointers 89 | * int (*a)[35]; - declares a pointer to an array of 35 ints.  90 | * int *a[35]; - declares an array of 35 pointers to ints.  91 | 92 | ## Memory Allocation Techniques 93 | There are two techniques of allocating memory to a variable,
94 | 1. Static Memory Allocation 95 | 2. Dynamic Memory Allocation 96 | 97 | ### Static Allocation 98 | Allocation of memory space when execution begins. 99 | 100 | ### Dynamic Allocation 101 | Allocation of memory space at run time. 102 | 103 | ## Dynamic Memory Allocation 104 | 105 | ### malloc() 106 | * Dynamically allocates memory when required 107 | * This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error 108 | * Syntax: `void * malloc (size_t size);` 109 | ### calloc() 110 | * Used to allocate storage to a variable while the program is running 111 | * Syntax: `void * calloc (size_t n, size_t size);` 112 | * For example, an int array of 10 elements can be allocated as: `int * array = (int *) calloc (10, sizeof (int));` 113 | 114 | #### Difference between malloc() and calloc() 115 | * Calloc allocates multiple blocks of data whereas malloc allocates as a single block  116 | * Calloc initializes all bytes in the allocation block to zero 117 | 118 | ### realloc() 119 | * Modifies the allocated memory size by malloc () and calloc () functions to new size 120 | * If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees old block 121 | * Syntax: `void * realloc (void * ptr, size_t size);` 122 | ### free() 123 | * frees the allocated memory by malloc (), calloc (), realloc () functions and returns the memory to the system 124 | 125 | 126 | ## Index 127 | 128 | 1. [Pointers](pointer.c) 129 | 2. [Poiners on array](PointToArray.c) 130 | 3. [Call by reference](swapUsingPointer.c) 131 | 4. [Dynamic memory alllocation](malloc.c) 132 | 133 | [Go Back](./..){: .btn} 134 | -------------------------------------------------------------------------------- /reviseC/README.md: -------------------------------------------------------------------------------- 1 | # C Programming 2 | C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, and therefore it has found lasting use in applications that had formerly been coded in assembly language, including operating systems, as well as various application software for computers ranging from supercomputers to embedded systems.
3 | C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs, and used to re-implement the Unix operating system. It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems. C has been standardized by the American National Standards Institute (ANSI) since 1989 (see ANSI C) and subsequently by the International Organization for Standardization (ISO). 4 | 5 | ## Getting started with C 6 | There are many books you can refer to get started with C Programming: 7 | * [Let Us C](https://www.amazon.in/Let-Us-C-Yashavant-Kanetkar/dp/8183331637/ref=as_li_ss_tl?s=books&ie=UTF8&qid=1482474153&sr=1-1&keywords=let+us+c&linkCode=sl1&tag=thecrazprog-21&linkId=0eee92bcac00b24033e591f1ba74faaf) 8 | * [The C Programming language](https://www.amazon.in/Programming-Language-Kernighan-Dennis-Ritchie/dp/9332549443/ref=as_li_ss_tl?s=books&ie=UTF8&qid=1482474311&sr=1-1&keywords=the+c+programming+language&linkCode=sl1&tag=thecrazprog-21&linkId=d802d14bd1b47f83f949746ea2f05b94) 9 | * [C: The Complete Reference](https://www.amazon.in/C-Complete-Reference-Herbert-Schildt/dp/0070411832/ref=as_sl_pc_tf_til?tag=thecrazprog-21&linkCode=w00&linkId=TUAPDSTEEGNKVVWF&creativeASIN=0070411832) 10 | * [Programming in ANSI C](https://www.amazon.in/Programming-ANSI-C-Balagurusamy/dp/933921966X/ref=as_li_ss_tl?s=books&ie=UTF8&qid=1482474187&sr=1-1&keywords=ansi+c&linkCode=sl1&tag=thecrazprog-21&linkId=30fc46dc98b370dd22cfda8bb2cd856b) 11 | * [Head First C](https://www.amazon.in/Head-First-C-David-Griffiths/dp/9350236923/ref=as_sl_pc_tf_til?tag=thecrazprog-21&linkCode=w00&linkId=RUUWS5S4GYEUTYL5&creativeASIN=9350236923) 12 | 13 | ## NOTE* 14 | Even though all answers are given, try slving the problems by yourself, even before looking at the answer. 15 | 16 | ## Confident On Your Skiils? Test Them 17 | Try out some good problems. Do them yourself, if you get stuck somewhere, the answers are always there. 18 | 19 | 1. [Assignment on conditional statements in C](./ReviseConditional) 20 | 2. [Assignment on Looping statements in C](./ReviseLoops) 21 | 3. [Assignment on Arrays and strings in C](./ReviseArrays) 22 | 4. [Assignment on Structures and functions in C](./ReviseStruct) 23 | 5. [Take A Test 1](./TAT1) 24 | 25 | ## Begginer? Try out some basic programs in C 26 | 27 | 1. [Factorial of a given number](factorial.c)
28 | LOGIC: use recursive functions
29 | ```c 30 | int factorial(int n) { 31 | if(n>1) return n*factorial(n-1); 32 | else return 1; 33 | } 34 | ``` 35 | 2. [Prime Number](prime.c)
36 | LOGIC: Use for loop till n/2 elements
37 | ```c 38 | for(i=2;i<=n/2;i++) { 39 | if(n%i == 0){ 40 | flag = 1; 41 | break; 42 | } 43 | } 44 | ``` 45 | 3. [Fibonacci Series](fibonacci.c)
46 | LOGIC: Use for loop
47 | ```c 48 | for(i=1;i<=n;i++) { 49 | if(i<3) a3=1; 50 | else { 51 | a3=a2+a1; 52 | a1=a2; 53 | a2=a3; 54 | } 55 | } 56 | ``` 57 | 4. [Sum of elements in array](sumOfElements.c)
58 | LOGIC: Use for loop
59 | ```c 60 | for(i=0;i 65 | LOGIC: Use for loop
66 | ```c 67 | for(i=0;i 72 | LOGIC:Use temp variable
73 | ```c 74 | for(i=0,j=n-1;i 81 | LOGIC: Use nested loops
82 | ```c 83 | for(i=0;i 89 | LOGIC: Add individual element
90 | ```c 91 | for(i=0;i 99 | ```c 100 | strlen(); 101 | strrev(); 102 | strcpy(); 103 | strcat(); 104 | strcmp(); 105 | ``` 106 | 10. [WAP which reads a single letter of alphabet. If it is a lowercase between 107 | ’a’ and ’g’, the program prints out the alphabet in uppercase form. If it is anything 108 | else, the program should print out uppercase ’X’.](ans1.c) 109 | 110 | 11. [WAP that accepts 4 real numbers from the keyboard and prints out the 111 | difference of the maximum and minimum values of these numbers using 4-decimal 112 | places.](ans2.c) 113 | 114 | 12. [Find sin(1/x) where x != 0 upto 4 digits of precision](sin.c) 115 | 13. [Check for palindrom number](palindrom.c) 116 | 14. [Number of vowels in a given line](vowels.c)
117 | LOGIC: Use if condition
118 | ```c 119 | for(i=0;i 50, raise a character exception and print ‘Age cannot be greater than 50’ 61 | 62 | #### Example 1 63 | 64 | If the details entered are Ramu, E123 and 25 then print the details ramu, 123 and 25, one in each line. 65 | 66 | #### Example 2 67 | 68 | If the details entered are Ramu, E123 and 15 then raise an exception and print ‘Age cannot be less than 18’. 69 | 70 | #### Example 3 71 | 72 | If the details entered are Ramu, E123 and 55 then raise an exception and print ‘Age cannot be greater than 50’. 73 | 74 | **Input Format** 75 | 76 | First line contains name of the employee 77 | 78 | Second line contains employee ID of the employee 79 | 80 | Third line contains age of the employee 81 | 82 | **Input Format** 83 | 84 | Print either the details of the employee entered. One detail in each line or print ‘Age cannot be less than 18’ or ‘Age cannot be greater than 50’ when invalid age is entered 85 | 86 | [**See Answer**](sample2.cpp) 87 | 88 | ## Problem 3: Heronian triangle 89 | 90 | In geometry, a Heronian triangle is a triangle that has side lengths and area that are all integers. Heronian triangles are named after Hero of Alexandria. Design a class to represent a triangle and provide functions to calculate perimeter of triangle, area of triangle and a function to check if the given triangle is Heronian triangle. 91 | 92 | #### Boundary conditions 93 | 94 | Sides a,b,c are integers and the values are given such that they can be sides of a triangle 95 | 96 | Note: 97 | 98 | Given sides of the triangle a,b and c, area of the triangle, S is calculated as: 99 | 100 | ![image](https://user-images.githubusercontent.com/26179770/36069840-91c6a5ac-0f16-11e8-9100-d5d03cfcc6e6.png) 101 | 102 | Print only two decimal places when the area is not an integer and print only integral part when decimal part of area is zero. 103 | 104 | If you have a float variable, f and you want to print only two decimal places then write cout with manipulators as shown below: 105 | 106 | 107 | 108 | Include iomanip namespace in the top of the file: 109 | 110 | #include 111 | 112 | And include the line below 113 | 114 | cout<OOP is an approach to program organizational and development that attempts to eliminate some of the pitfalls of proceedural programming.
2 | 3 | # Proceedure oriented programming 4 | 5 | * Conventional programming using high level languages COBOL, FORTRAN, C etc. 6 | * The problem is viewed as a sequence of things to be done 7 | * The primary focus is on functions 8 | * It consists of writing a list of instructions for the computer to follow and organizing these instructions into groups known as functions 9 | * To revise a data structure, we also need to revise all functions that access the data 10 | * This approach does not model real world problems 11 | 12 | ## Characteristics of Proceedural Programming 13 | 14 | * Large problems divided into smaller sub problems called functions 15 | 16 | ## Drawbacks of proceedural programming 17 | 18 | There are some issues in Proceedural programming paradigm 19 | * This approach does not model real world problems 20 | * Data can not be classified into private and public 21 | * Most of the functions share global data 22 | * 23 | 24 | 25 | # Object Oriented Programming 26 | 27 | ## Why OOP 28 | 29 | Object Oriented Programming has a capability of programming/coding (more precisely, MODELLING) any(most of) real world scenarios. 30 | Note* C++ is not purely object oriented, JAVA is a purely object oriented programming language 31 | 32 | ## Major advantages of OOP 33 | 34 | * OOP treat data as a critical element in the program development and does not allow it to flow freely around the system 35 | * Emphasis is on data rather than proceedure 36 | * Data is hidden and can not be accessed by unauthorized external functions 37 | * Programs are divided into objects 38 | * It is based on grouping data (called data members) and related functions (called member functions) into a bigger model called a ***class*** 39 | * Class is a blueprint of object. It is designed in such a way that it characterizes the objects 40 | * It ties data more closely to the functions that operates on it, protects it from accidental modifications fro outside functions 41 | * OOP allows decomposition of a problem into a number of entities called objects and then build data freely around these objects 42 | * Data of an object can be accessed only by the functions associated with that object 43 | * Functions of one object can access the functions of another objects 44 | 45 | ### Classes 46 | 47 | ### Objects 48 | 49 | ### Class Diagrams 50 | 51 | ### Syntax 52 | 53 | ```cpp 54 | #include 55 | using namespace std; 56 | 57 | class abc 58 | { 59 | int a,b; 60 | public: 61 | void add(int a, int b) // Inline Function -- Member function defined inside the class 62 | { 63 | cout< 99 | C++ implements static polymorphism through 100 | overloaded functions 101 | overloaded operators 102 |

103 | Three ways of achieving overloading in C++ 104 | * Function Overloading 105 | * Operator Overloading 106 | * Dynamic Binding 107 | 108 | ## Overloading 109 | 110 | A name having two or more distinct meanings
111 | **Function Overloading** -- A function having two or more distinct meaning 112 | **Operator Overloading** -- When two or more distinct meanings are defined for a single operator 113 |
For example -- '-' can be unary as well as binary, '*' is used for multiplication as well as pointers 114 | 115 | [See Example](funOver.cpp) 116 | 117 | #### Signature 118 | 119 | Combination of function's name and its parameter types (in order). 120 | Or, a function's arguement list is known as the function's signature. Overloaded functions are distinguished by their signatures 121 | 122 | Signature is only on the parameter's, **NOT** on the return type 123 | 124 | ## Function Overloading -- Finding the best match 125 | 126 | A call to an overloaded function is resolved to a particular instance of the function, there are three possible cases, a function call may result in:
127 | * **One Match** - A match is found for the function call 128 | * **No Match** - No match is found for the function call 129 | * **Ambiguous Match** - More than one defined instance for the function call. 130 | 131 | ## Match Techniques 132 | 133 | ### Exact Match 134 | 135 | For example, there are two functions with same name afunc: 136 |
void afunc(int); 137 |
void afunc(double); 138 | The function call afunc(0); 139 | is matched to void afunc(int); and compiler invokes corresponding function definition 140 | as 0 (zero) is of type int 141 | 142 | ### Match through promotion 143 | 144 | If no exact match is found, an attempt is made to achieve a match through promotion of the actual argument. 145 | Recall that the conversion of integer types (char, short, enumerator, int) into int - integral promotion 146 |
147 | For example, consider the following code fragment:
148 | void afunc (int);
149 | void afunc (float);
150 | afunc (‘c’); 151 | Will invoke afunc(int) 152 | 153 | ## Constructors and Destructors 154 | 155 | ## Constructors 156 | 157 | A constructor is a special member function whose task is to initialize the objects of its class. It's name is same as the name of the class. 158 | The constructor is invoked whenever an object of it's associated class is created.
159 | It is called constructor because it constructs the values of data members of the class. 160 | 161 |
**Example** 162 | ```cpp 163 | class add { 164 | int m,n; 165 | public: 166 | add (void); 167 | }; 168 | 169 | add::add(void) { 170 | m=0; 171 | n=0; 172 | } 173 | ``` 174 | 175 | ### Parameterized Constructors 176 | 177 | When a constructor is parametrized, we must pass the initial values as arguements to the constructor function. 178 | 179 | ### Copy Constructor 180 | 181 | A copy constructor is used 182 | ```cpp 183 | sample::sample (sample &i) { 184 | a=i.a; 185 | b=i.b; 186 | } 187 | ``` 188 | 189 | #### Multiple constructors in a class 190 | 191 | * constructor overtloading is possible in c++. 192 | * Default arguement constructors are allowed `A::A(int x=0)` 193 | 194 | [See an example here](copy.cpp) 195 | 196 | ## Destructor 197 | 198 | A destructor is used to destroy the objects that have been created by a constructor 199 | Destructor never takes any arguements nor returns any value 200 | It will be invoked implicitly by the compiler upon exit from the program (or any block/function). 201 | 202 | ## Function calling methods 203 | 204 | 1. Call by Value 205 | 2. Call by Address 206 | 3. Call ny Reerance 207 | 208 | ## Dynamic memory Allocation in C++ 209 | 210 | C++ has two new operators apart form malloc() and calloc(), called `new` and `delete` 211 | 212 | ### New and delete in C++ 213 | 214 | Similar to malloc and free in C 215 | But there is an option to initialize memory 216 | Can be used allocate memory for single or array of elements 217 | If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. 218 | If sufficient memory is not available, the new operator returns NULL. 219 | Dynamically allocated object/array exists until the delete operator destroys it 220 | 221 | [1. Dynamic Memory Allocation](dynAlloc.cpp) 222 | [2. Dynamic Memory Allocation for Arrays](dynamicArray.cpp) 223 | [3. Dynamic Memory Allocation for Objects](dynamicObject.cpp) 224 | 225 | ## Exception handling 226 | 227 | Preventing program/Software to crash in case of wrong inputs by throwing appropriate error messages/. 228 | 229 | **try, catch and throw** 230 | 231 | ### TRY 232 | 233 | ```cpp 234 | try { 235 | . 236 | . 237 | // Possibly an unexpected situation 238 | throw(val1); 239 | . 240 | . 241 | . 242 | // Possibly an unexpected situation 243 | throw(val2); 244 | . 245 | . 246 | . 247 | } 248 | 249 | catch (val1) { 250 | .. .. 251 | .. .. 252 | .. .. 253 | } 254 | catch (val2) { 255 | .. .. 256 | .. .. 257 | .. .. 258 | } 259 | 260 | 261 | catch (...) { // catch(...) catches any throw 262 | 263 | } 264 | ``` 265 | 266 | ## Friend Function 267 | 268 | A friend function is a function that can access the non-public members of a class, even though the function itself is not a member of the class. 269 | 270 | ### Doesn't it violate the concept of data hiding 271 | 272 | The concepts of encapsulation and data hiding dictate that non-member functions should not be able to access an object’s private or protected data. 273 | However, there are situations where such rigid discrimination leads to considerable inconvenience. 274 | A friend function is a normal function with special access privileges. 275 | 276 | ### More about friend function 277 | 278 | A friend function of a class is a non-member function of a class that has the right to access all private and protected (non-public) members of the class. 279 | Friend function prototype should be placed inside the class definition (can be any where inside the class definition). 280 | Friend function definition should be outside the class scope. 281 | Even though the prototypes of friend functions appear in the class definition, friends are not member functions. 282 | 283 | A friend function of a class can be a 284 | 285 | * function (non-member of a class) 286 | * member function of another class 287 | * function template 288 | 289 | To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend. 290 | Friend functions are used in Operator overloading to increase the versatility of operators. 291 | 292 | ### Syntax 293 | 294 | ```cpp 295 | class ClassName { 296 | // Some statements 297 | friend returnType functionName( arguments ); // friend function declaration 298 | // Some Statements 299 | }; 300 | // friend function definition does not start with friend keyword 301 | returnType functionName( arguments ) { 302 | ... ... ... 303 | // private and protected data of the above class can be accessed from this function 304 | ... ... ... 305 | } 306 | int main( ) { 307 | functionName( arguments ); // Call to the friend function 308 | } 309 | ``` 310 | 311 | [**See a sample program**](friend.cpp) 312 | 313 | ### Difference between Friend function and Member function 314 | 315 | |Member Function|Friend Functoon| 316 | |--|---| 317 | |It is invoked through an object|Not invoked through an object since it is a non-member of a class
If the friend function of class X is a member function of class Y, then it must be invoked through an object of class Y | 318 | |Can access the non-public members of the class directly|Can access the non-public members of the class only through an object (since this pointer is not visible)| 319 | 320 | ## Friend Class 321 | 322 | Member functions of a class X operate on the data members of Class X. 323 | At times, we need a helper class to operate on non-public data members of the class X. In such circumstances, the helper class has to be treated as a friend of class X to access the non-public data members of class X. 324 | So, a class can be a friend of another class 325 | 326 | For example:
327 | If class Y is a friend of class X then
328 | All the member functions of class Y can access the non-public members of class X 329 | 330 | ### Friendship is not symmetric 331 | 332 | If class Y is a friend of class X then 333 | class X is not a friend of class Y 334 | 335 | ### Friendship is not transitive 336 | 337 | If class X is a friend of class Y and If class Y is a friend of class Z then 338 | class X is not a friend of class Z 339 | 340 | ### Syntax 341 | 342 | ```cpp 343 | 344 | class employer;// forward declaration of class Y 345 | class employee { 346 | ... ... 347 | friend class employer;// friend class declaration 348 | ... ... 349 | }; 350 | class employer { 351 | // All the member functions of class employer can access non-public members of class employee using an object 352 | }; 353 | 354 | 355 | ``` 356 | 357 | ## Operator overloading 358 | 359 | C++ allows most of the operators within the language to be overloaded so that they work with classes. This 360 | - allows the language to be extended to cover new situations 361 | - enhances program readability 362 | - enhances program functionality 363 | - is an essential components of C++ templates and the standard templates library 364 | 365 | ### Restrictions 366 | 367 | The operators . :: ?: sizeof **may not** be overloaded. 368 | 369 | All other operators can be overloaded 370 | 371 | An operator is overloaded by writing a non-static member function definition or non-member 372 | function definition as you normally would, except that the function name 373 | starts with the keyword operator followed by the symbol for the operator being overloaded. 374 | 375 | **For example**, the function name operator+ would be used to overload the addition operator (+) 376 | for use with objects of a particular class. 377 | 378 | [**Overloading binary addition operator**](opOver.cpp)
379 | [**Overloading unary subtraction operator**](opOverUnary.cpp)
380 | [**Overloading unary increment operator**](incrementOver.cpp)
381 | [**Overloading subscript operator**](incrementOver.cpp)
382 | 383 | ## Inheritance 384 | 385 | Inheritance means deriving qualities and characteristics from parents or ancestors. 386 | 387 | Inheritance in Object Oriented Programming can be described as a process of creating new classes from existing classes which will have the properties similar to that of parent classes. 388 | Or simply, Inheritance is the process by which objects of one class acquire the properties of objects of another class in the hierarchy. 389 | 390 | Subclasses provide specialized behavior from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times. 391 | 392 | Reusing existing code saves time and money and increases a program’s reliability. 393 | 394 | ![image](https://user-images.githubusercontent.com/26179770/36838639-b9c269e4-1d65-11e8-9c98-506477719a4d.png) 395 | 396 | New classes can be built from the existing classes. It means that we can add additional features to an existing class without modifying it. The new class is referred as derived class or subclass and the original class is known as base classes or super class. 397 | 398 | ### Syntax 399 | 400 | ```cpp 401 | class derivedClasas: accessSpecifier baseClass 402 | ``` 403 | 404 | ## Access Specifiers 405 | 406 | Access specifiers are (as the name suggests) specifiers which tell what should be the privacy of the content, and how much content wee can access. 407 | 408 | Access specifier can be public, protected and private. The default access specifier for data members is private. Access specifiers affect accessibility of data members of base class from the derived class. In addition, it determines the accessibility of data members of base class outside the derived class. 409 | 410 | ## Inheritance Access Specifiers 411 | 412 | ### Public 413 | 414 | This inheritance mode is used mostly. In this the protected member of Base class becomes protected members of Derived class and public becomes public. 415 | 416 | ### Protected 417 | 418 | In protected mode, the public and protected members of Base class becomes protected members of Derived class. 419 | 420 | ### Private 421 | 422 | In private mode the public and protected members of Base class become private members of Derived class. 423 | 424 | ## Types Of Inheritance 425 | 426 | - [Single Inheritance](#single-inheritance) 427 | - [Multiple Inheritance](#single-inheritance) 428 | - [Multi Level Inheritance](#single-inheritance) 429 | - [Hierarchical Inheritance](#single-inheritance) 430 | - [Hybrid Inheritance](#single-inheritance) 431 | 432 | ### Single inheritance 433 | 434 | One child class inherits one parent class 435 | 436 | ![image](https://user-images.githubusercontent.com/26179770/36835325-d9d905d0-1d5b-11e8-99f6-f53e93ed5a38.png) 437 | 438 | 439 | [**See a sample program here**](./inheriance/single.cpp) 440 | 441 | ### Multiple Inheritance 442 | 443 | When one child cass inherits properties of more than one parent classes. 444 | Simply, one subclass and many super classes form a multiple inheritance. 445 | 446 | ![image](https://user-images.githubusercontent.com/26179770/36891750-9fad27ec-1e28-11e8-9dd5-87b935688bd7.png) 447 | 448 | [**See a sample program here**](./inheritance/multiple.cpp) 449 | 450 | ### Multilevel Inheritance 451 | 452 | As the name suggests, in this type of inheritance, there are multiple levels of inheritance. This is analogous to grand parents, then parents then children. 453 | 454 | ![image](https://user-images.githubusercontent.com/26179770/37459322-b018b41c-286d-11e8-9382-dc31f5690ccd.png) 455 | 456 | Example: 457 | ![image](https://user-images.githubusercontent.com/26179770/37459129-2b6145f4-286d-11e8-83ee-bfcafe56f689.png) 458 | 459 | [**See a sample program here**](./inheritance/multilevel.cpp) 460 | 461 | ### Hierarchical Inheritance 462 | 463 | In this case the inheritance pattern forms a hierarchy, i.e., there are multiple derived classes of same base class. 464 | 465 | ![image](https://user-images.githubusercontent.com/26179770/37459413-f5d3db94-286d-11e8-9e82-c2675b36c8ac.png) 466 | 467 | [**See a sample program here**](./inheritance/hierarchical.cpp) 468 | 469 | ### Hybrid Inheritance 470 | 471 | Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. 472 | 473 | ![image](https://user-images.githubusercontent.com/26179770/37460441-3e203598-2871-11e8-9b7b-e3f1150aaf07.png) 474 | 475 | [**See a sample program here**](./inheritance/hybrid.cpp) 476 | 477 | ## Templates 478 | 479 | Template is a kind of macro that supports the generic programming which allows to develop the reusable components. 480 | It is one of the main features of object oriented language such as C++. 481 | Actually, it allows the declaration of data items without specifying their exact data type. 482 | 483 | ## 2 Types pf templates 484 | 485 | 1. Function Templates 486 | 2. Class Templates 487 | 488 | ### Function Templates 489 | 490 | Function templates are generic functions, which are operating on different data items.
491 | They describe a function format that when instantiated with particulars generates a function definition, basically it acts like a template schema which can be used 492 | for parameters with any datatype, instead of some fixed data type 493 | 494 | * Avoids redifinition of function 495 | 496 | * Makes code more reusable (write once, use multiple times) 497 | 498 | The C++ language allows the compiler to generate multiple versions of a function by allowing parameterized data types and hence it supports the parameterized polymorphism. 499 | 500 | The data items (types) are not declared while defining the function. 501 | 502 | Once when the function call is made using appropriate data type, then the template function is transformed to operate on that specific data types. 503 | 504 | #### Syntax 505 | 506 | ```cpp 507 | template 508 | returntype functionname(arguments) 509 | { 510 | ....... 511 | statements; 512 | ....... 513 | } 514 | ``` 515 | 516 | [See a sample program here](./template.cpp) 517 | 518 | ### Class Template 519 | 520 | Generic classes with template data variables and template member functions 521 | 522 | [See a sample program here](./classTemplate.cpp) 523 | 524 | 525 | ### Sample Programs 526 | 1. [Sample Program for Classes and Object 1](./IntroToOOPS.cpp) 527 | 2. [Sample Program for Classes and Object 2](./class1.cpp) 528 | -------------------------------------------------------------------------------- /IntroToOOP/README.md: -------------------------------------------------------------------------------- 1 | OOP is an approach to program organizational and development that attempts to eliminate some of the pitfalls of proceedural programming.
2 | 3 | # Proceedure oriented programming 4 | 5 | * Conventional programming using high level languages COBOL, FORTRAN, C etc. 6 | * The problem is viewed as a sequence of things to be done 7 | * The primary focus is on functions 8 | * It consists of writing a list of instructions for the computer to follow and organizing these instructions into groups known as functions 9 | * To revise a data structure, we also need to revise all functions that access the data 10 | * This approach does not model real world problems 11 | 12 | ## Characteristics of Proceedural Programming 13 | 14 | * Large problems divided into smaller sub problems called functions 15 | 16 | ## Drawbacks of proceedural programming 17 | 18 | There are some issues in Proceedural programming paradigm 19 | * This approach does not model real world problems 20 | * Data can not be classified into private and public 21 | * Most of the functions share global data 22 | * 23 | 24 | 25 | # Object Oriented Programming 26 | 27 | ## Why OOP 28 | 29 | Object Oriented Programming has a capability of programming/coding (more precisely, MODELLING) any(most of) real world scenarios. 30 | Note* C++ is not purely object oriented, JAVA is a purely object oriented programming language 31 | 32 | ## Major advantages of OOP 33 | 34 | * OOP treat data as a critical element in the program development and does not allow it to flow freely around the system 35 | * Emphasis is on data rather than proceedure 36 | * Data is hidden and can not be accessed by unauthorized external functions 37 | * Programs are divided into objects 38 | * It is based on grouping data (called data members) and related functions (called member functions) into a bigger model called a ***class*** 39 | * Class is a blueprint of object. It is designed in such a way that it characterizes the objects 40 | * It ties data more closely to the functions that operates on it, protects it from accidental modifications fro outside functions 41 | * OOP allows decomposition of a problem into a number of entities called objects and then build data freely around these objects 42 | * Data of an object can be accessed only by the functions associated with that object 43 | * Functions of one object can access the functions of another objects 44 | 45 | ### Classes 46 | 47 | ### Objects 48 | 49 | ### Class Diagrams 50 | 51 | ### Syntax 52 | 53 | ```cpp 54 | #include 55 | using namespace std; 56 | 57 | class abc 58 | { 59 | int a,b; 60 | public: 61 | void add(int a, int b) // Inline Function -- Member function defined inside the class 62 | { 63 | cout< 99 | C++ implements static polymorphism through 100 | overloaded functions 101 | overloaded operators 102 |

103 | Three ways of achieving overloading in C++ 104 | * Function Overloading 105 | * Operator Overloading 106 | * Dynamic Binding 107 | 108 | ## Overloading 109 | 110 | A name having two or more distinct meanings
111 | **Function Overloading** -- A function having two or more distinct meaning 112 | **Operator Overloading** -- When two or more distinct meanings are defined for a single operator 113 |
For example -- '-' can be unary as well as binary, '*' is used for multiplication as well as pointers 114 | 115 | [See Example](funOver.cpp) 116 | 117 | #### Signature 118 | 119 | Combination of function's name and its parameter types (in order). 120 | Or, a function's arguement list is known as the function's signature. Overloaded functions are distinguished by their signatures 121 | 122 | Signature is only on the parameter's, **NOT** on the return type 123 | 124 | ## Function Overloading -- Finding the best match 125 | 126 | A call to an overloaded function is resolved to a particular instance of the function, there are three possible cases, a function call may result in:
127 | * **One Match** - A match is found for the function call 128 | * **No Match** - No match is found for the function call 129 | * **Ambiguous Match** - More than one defined instance for the function call. 130 | 131 | ## Match Techniques 132 | 133 | ### Exact Match 134 | 135 | For example, there are two functions with same name afunc: 136 |
void afunc(int); 137 |
void afunc(double); 138 | The function call afunc(0); 139 | is matched to void afunc(int); and compiler invokes corresponding function definition 140 | as 0 (zero) is of type int 141 | 142 | ### Match through promotion 143 | 144 | If no exact match is found, an attempt is made to achieve a match through promotion of the actual argument. 145 | Recall that the conversion of integer types (char, short, enumerator, int) into int - integral promotion 146 |
147 | For example, consider the following code fragment:
148 | void afunc (int);
149 | void afunc (float);
150 | afunc (‘c’); 151 | Will invoke afunc(int) 152 | 153 | ## Constructors and Destructors 154 | 155 | ## Constructors 156 | 157 | A constructor is a special member function whose task is to initialize the objects of its class. It's name is same as the name of the class. 158 | The constructor is invoked whenever an object of it's associated class is created.
159 | It is called constructor because it constructs the values of data members of the class. 160 | 161 |
**Example** 162 | ```cpp 163 | class add { 164 | int m,n; 165 | public: 166 | add (void); 167 | }; 168 | 169 | add::add(void) { 170 | m=0; 171 | n=0; 172 | } 173 | ``` 174 | 175 | ### Parameterized Constructors 176 | 177 | When a constructor is parametrized, we must pass the initial values as arguements to the constructor function. 178 | 179 | ### Copy Constructor 180 | 181 | A copy constructor is used 182 | ```cpp 183 | sample::sample (sample &i) { 184 | a=i.a; 185 | b=i.b; 186 | } 187 | ``` 188 | 189 | #### Multiple constructors in a class 190 | 191 | * constructor overtloading is possible in c++. 192 | * Default arguement constructors are allowed `A::A(int x=0)` 193 | 194 | [See an example here](copy.cpp) 195 | 196 | ## Destructor 197 | 198 | A destructor is used to destroy the objects that have been created by a constructor 199 | Destructor never takes any arguements nor returns any value 200 | It will be invoked implicitly by the compiler upon exit from the program (or any block/function). 201 | 202 | ## Function calling methods 203 | 204 | 1. Call by Value 205 | 2. Call by Address 206 | 3. Call ny Reerance 207 | 208 | ## Dynamic memory Allocation in C++ 209 | 210 | C++ has two new operators apart form malloc() and calloc(), called `new` and `delete` 211 | 212 | ### New and delete in C++ 213 | 214 | Similar to malloc and free in C 215 | But there is an option to initialize memory 216 | Can be used allocate memory for single or array of elements 217 | If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. 218 | If sufficient memory is not available, the new operator returns NULL. 219 | Dynamically allocated object/array exists until the delete operator destroys it 220 | 221 | [1. Dynamic Memory Allocation](dynAlloc.cpp) 222 | [2. Dynamic Memory Allocation for Arrays](dynamicArray.cpp) 223 | [3. Dynamic Memory Allocation for Objects](dynamicObject.cpp) 224 | 225 | ## Exception handling 226 | 227 | Preventing program/Software to crash in case of wrong inputs by throwing appropriate error messages/. 228 | 229 | **try, catch and throw** 230 | 231 | ### TRY 232 | 233 | ```cpp 234 | try { 235 | . 236 | . 237 | // Possibly an unexpected situation 238 | throw(val1); 239 | . 240 | . 241 | . 242 | // Possibly an unexpected situation 243 | throw(val2); 244 | . 245 | . 246 | . 247 | } 248 | 249 | catch (val1) { 250 | .. .. 251 | .. .. 252 | .. .. 253 | } 254 | catch (val2) { 255 | .. .. 256 | .. .. 257 | .. .. 258 | } 259 | 260 | 261 | catch (...) { // catch(...) catches any throw 262 | 263 | } 264 | ``` 265 | 266 | ## Friend Function 267 | 268 | A friend function is a function that can access the non-public members of a class, even though the function itself is not a member of the class. 269 | 270 | ### Doesn't it violate the concept of data hiding 271 | 272 | The concepts of encapsulation and data hiding dictate that non-member functions should not be able to access an object’s private or protected data. 273 | However, there are situations where such rigid discrimination leads to considerable inconvenience. 274 | A friend function is a normal function with special access privileges. 275 | 276 | ### More about friend function 277 | 278 | A friend function of a class is a non-member function of a class that has the right to access all private and protected (non-public) members of the class. 279 | Friend function prototype should be placed inside the class definition (can be any where inside the class definition). 280 | Friend function definition should be outside the class scope. 281 | Even though the prototypes of friend functions appear in the class definition, friends are not member functions. 282 | 283 | A friend function of a class can be a 284 | 285 | * function (non-member of a class) 286 | * member function of another class 287 | * function template 288 | 289 | To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend. 290 | Friend functions are used in Operator overloading to increase the versatility of operators. 291 | 292 | ### Syntax 293 | 294 | ```cpp 295 | class ClassName { 296 | // Some statements 297 | friend returnType functionName( arguments ); // friend function declaration 298 | // Some Statements 299 | }; 300 | // friend function definition does not start with friend keyword 301 | returnType functionName( arguments ) { 302 | ... ... ... 303 | // private and protected data of the above class can be accessed from this function 304 | ... ... ... 305 | } 306 | int main( ) { 307 | functionName( arguments ); // Call to the friend function 308 | } 309 | ``` 310 | 311 | [**See a sample program**](friend.cpp) 312 | 313 | ### Difference between Friend function and Member function 314 | 315 | |Member Function|Friend Functoon| 316 | |--|---| 317 | |It is invoked through an object|Not invoked through an object since it is a non-member of a class
If the friend function of class X is a member function of class Y, then it must be invoked through an object of class Y | 318 | |Can access the non-public members of the class directly|Can access the non-public members of the class only through an object (since this pointer is not visible)| 319 | 320 | ## Friend Class 321 | 322 | Member functions of a class X operate on the data members of Class X. 323 | At times, we need a helper class to operate on non-public data members of the class X. In such circumstances, the helper class has to be treated as a friend of class X to access the non-public data members of class X. 324 | So, a class can be a friend of another class 325 | 326 | For example:
327 | If class Y is a friend of class X then
328 | All the member functions of class Y can access the non-public members of class X 329 | 330 | ### Friendship is not symmetric 331 | 332 | If class Y is a friend of class X then 333 | class X is not a friend of class Y 334 | 335 | ### Friendship is not transitive 336 | 337 | If class X is a friend of class Y and If class Y is a friend of class Z then 338 | class X is not a friend of class Z 339 | 340 | ### Syntax 341 | 342 | ```cpp 343 | 344 | class employer;// forward declaration of class Y 345 | class employee { 346 | ... ... 347 | friend class employer;// friend class declaration 348 | ... ... 349 | }; 350 | class employer { 351 | // All the member functions of class employer can access non-public members of class employee using an object 352 | }; 353 | 354 | 355 | ``` 356 | 357 | ## Operator overloading 358 | 359 | C++ allows most of the operators within the language to be overloaded so that they work with classes. This 360 | - allows the language to be extended to cover new situations 361 | - enhances program readability 362 | - enhances program functionality 363 | - is an essential components of C++ templates and the standard templates library 364 | 365 | ### Restrictions 366 | 367 | The operators . :: ?: sizeof **may not** be overloaded. 368 | 369 | All other operators can be overloaded 370 | 371 | An operator is overloaded by writing a non-static member function definition or non-member 372 | function definition as you normally would, except that the function name 373 | starts with the keyword operator followed by the symbol for the operator being overloaded. 374 | 375 | **For example**, the function name operator+ would be used to overload the addition operator (+) 376 | for use with objects of a particular class. 377 | 378 | [**Overloading binary addition operator**](opOver.cpp)
379 | [**Overloading unary subtraction operator**](opOverUnary.cpp)
380 | [**Overloading unary increment operator**](incrementOver.cpp)
381 | [**Overloading subscript operator**](incrementOver.cpp)
382 | 383 | ## Inheritance 384 | 385 | Inheritance means deriving qualities and characteristics from parents or ancestors. 386 | 387 | Inheritance in Object Oriented Programming can be described as a process of creating new classes from existing classes which will have the properties similar to that of parent classes. 388 | Or simply, Inheritance is the process by which objects of one class acquire the properties of objects of another class in the hierarchy. 389 | 390 | Subclasses provide specialized behavior from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times. 391 | 392 | Reusing existing code saves time and money and increases a program’s reliability. 393 | 394 | ![image](https://user-images.githubusercontent.com/26179770/36838639-b9c269e4-1d65-11e8-9c98-506477719a4d.png) 395 | 396 | New classes can be built from the existing classes. It means that we can add additional features to an existing class without modifying it. The new class is referred as derived class or subclass and the original class is known as base classes or super class. 397 | 398 | ### Syntax 399 | 400 | ```cpp 401 | class derivedClasas: accessSpecifier baseClass 402 | ``` 403 | 404 | ## Access Specifiers 405 | 406 | Access specifiers are (as the name suggests) specifiers which tell what should be the privacy of the content, and how much content wee can access. 407 | 408 | Access specifier can be public, protected and private. The default access specifier for data members is private. Access specifiers affect accessibility of data members of base class from the derived class. In addition, it determines the accessibility of data members of base class outside the derived class. 409 | 410 | ## Inheritance Access Specifiers 411 | 412 | ### Public 413 | 414 | This inheritance mode is used mostly. In this the protected member of Base class becomes protected members of Derived class and public becomes public. 415 | 416 | ### Protected 417 | 418 | In protected mode, the public and protected members of Base class becomes protected members of Derived class. 419 | 420 | ### Private 421 | 422 | In private mode the public and protected members of Base class become private members of Derived class. 423 | 424 | ## Types Of Inheritance 425 | 426 | - [Single Inheritance](#single-inheritance) 427 | - [Multiple Inheritance](#single-inheritance) 428 | - [Multi Level Inheritance](#single-inheritance) 429 | - [Hierarchical Inheritance](#single-inheritance) 430 | - [Hybrid Inheritance](#single-inheritance) 431 | 432 | ### Single inheritance 433 | 434 | One child class inherits one parent class 435 | 436 | ![image](https://user-images.githubusercontent.com/26179770/36835325-d9d905d0-1d5b-11e8-99f6-f53e93ed5a38.png) 437 | 438 | 439 | [**See a sample program here**](./inheriance/single.cpp) 440 | 441 | ### Multiple Inheritance 442 | 443 | When one child cass inherits properties of more than one parent classes. 444 | Simply, one subclass and many super classes form a multiple inheritance. 445 | 446 | ![image](https://user-images.githubusercontent.com/26179770/36891750-9fad27ec-1e28-11e8-9dd5-87b935688bd7.png) 447 | 448 | [**See a sample program here**](./inheritance/multiple.cpp) 449 | 450 | ### Multilevel Inheritance 451 | 452 | As the name suggests, in this type of inheritance, there are multiple levels of inheritance. This is analogous to grand parents, then parents then children. 453 | 454 | ![image](https://user-images.githubusercontent.com/26179770/37459322-b018b41c-286d-11e8-9382-dc31f5690ccd.png) 455 | 456 | Example: 457 | ![image](https://user-images.githubusercontent.com/26179770/37459129-2b6145f4-286d-11e8-83ee-bfcafe56f689.png) 458 | 459 | [**See a sample program here**](./inheritance/multilevel.cpp) 460 | 461 | ### Hierarchical Inheritance 462 | 463 | In this case the inheritance pattern forms a hierarchy, i.e., there are multiple derived classes of same base class. 464 | 465 | ![image](https://user-images.githubusercontent.com/26179770/37459413-f5d3db94-286d-11e8-9e82-c2675b36c8ac.png) 466 | 467 | [**See a sample program here**](./inheritance/hierarchical.cpp) 468 | 469 | ### Hybrid Inheritance 470 | 471 | Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance. 472 | 473 | ![image](https://user-images.githubusercontent.com/26179770/37460441-3e203598-2871-11e8-9b7b-e3f1150aaf07.png) 474 | 475 | [**See a sample program here**](./inheritance/hybrid.cpp) 476 | 477 | ## Diamond Problem 478 | 479 | This is the problem arised in some cases of hybrid inheritance. In this problem a Derived class will have multiple paths to a Base class. This will result in duplicate inherited members of the Base class. 480 | 481 | ![image](https://user-images.githubusercontent.com/26179770/37461230-a6283a62-2873-11e8-8194-c30136e21f1d.png) 482 | 483 | ## Virtual Base Class 484 | 485 | Virtual base class is used in situation where a derived have multiple copies of base class to avoid dreaded diamonds problem.
486 | reference: http://www.tutorialdost.com/Cpp-Programming-Tutorial/51-Cpp-Virtual-Base-Class.aspx 487 | 488 | ![image](https://user-images.githubusercontent.com/26179770/37461316-f3efedb2-2873-11e8-8a33-576936ccc2d2.png) 489 | 490 | 491 | ### Example without using virtual class 492 | 493 | ```cpp 494 | #include 495 | #include 496 | 497 | class ClassA 498 | { 499 | public: 500 | int a; 501 | }; 502 | 503 | class ClassB : public ClassA 504 | { 505 | public: 506 | int b; 507 | }; 508 | class ClassC : public ClassA 509 | { 510 | public: 511 | int c; 512 | }; 513 | 514 | class ClassD : public ClassB, public ClassC 515 | { 516 | public: 517 | int d; 518 | }; 519 | 520 | void main() 521 | { 522 | 523 | ClassD obj; 524 | 525 | obj.a = 10; //Statement 1, Error occur 526 | obj.a = 100; //Statement 2, Error occur 527 | 528 | obj.b = 20; 529 | obj.c = 30; 530 | obj.d = 40; 531 | 532 | cout<< "\n A : "<< obj.a; 533 | cout<< "\n B : "<< obj.b; 534 | cout<< "\n C : "<< obj.c; 535 | cout<< "\n D : "<< obj.d; 536 | 537 | } 538 | ``` 539 | 540 | **This will result in error** 541 | Therefore, to avoid such situations, we use virtual class 542 | 543 | ### Example with virtual base class 544 | 545 | ```cpp 546 | #include 547 | #include 548 | 549 | class ClassA 550 | { 551 | public: 552 | int a; 553 | }; 554 | 555 | class ClassB : virtual public ClassA 556 | { 557 | public: 558 | int b; 559 | }; 560 | class ClassC : virtual public ClassA 561 | { 562 | public: 563 | int c; 564 | }; 565 | 566 | class ClassD : public ClassB, public ClassC 567 | { 568 | public: 569 | int d; 570 | }; 571 | 572 | void main() 573 | { 574 | 575 | ClassD obj; 576 | 577 | obj.a = 10; //Statement 1 578 | obj.a = 100; //Statement 2 579 | 580 | obj.b = 20; 581 | obj.c = 30; 582 | obj.d = 40; 583 | 584 | cout<< "\n A : "<< obj.a; 585 | cout<< "\n B : "<< obj.b; 586 | cout<< "\n C : "<< obj.c; 587 | cout<< "\n D : "<< obj.d; 588 | 589 | } 590 | 591 | Output : 592 | 593 | A : 100 594 | B : 20 595 | C : 30 596 | D : 40 597 | 598 | ``` 599 | 600 | Here, ClassD have only one copy of ClassA and statement 4 will overwrite the value of a, given in statement 3. 601 | 602 | ## Virtual Functions 603 | 604 | There are many cases where there is a function declared in base class and then again declared in the child class, i.e., that function is overridden. 605 | So basically, a virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class. 606 | 607 | Characteristics of virtual functions: 608 | 609 | * Ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. 610 | 611 | * Used to achieve dynamic/runtime polymorphism 612 | 613 | * Functions are declared with a virtual keyword in base class. 614 | 615 | * The resolving of function call is done at Run-time. 616 | 617 | ### Rules for virtual functions 618 | 619 | * They Must be declared in public section of class. 620 | 621 | * Virtual functions cannot be static and also cannot be a friend function of another class. 622 | 623 | * Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism. 624 | 625 | * The prototype of virtual functions should be same in base as well as derived class. 626 | 627 | * They are always defined in base class and overridden in derived class. 628 | 629 | * It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used. 630 | 631 | * A class may have virtual destructor but it cannot have a virtual constructor. 632 | 633 | [See a sample program here](./virtual.cpp) 634 | 635 | ## Pure Virtual Functions (Abstract Classes) 636 | 637 | Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class. 638 | 639 | [See a sample program here](./absract.cpp) 640 | 641 | ## Templates 642 | 643 | Template is a kind of macro that supports the generic programming which allows to develop the reusable components. 644 | It is one of the main features of object oriented language such as C++. 645 | Actually, it allows the declaration of data items without specifying their exact data type. 646 | 647 | ## 2 Types pf templates 648 | 649 | 1. Function Templates 650 | 2. Class Templates 651 | 652 | ### Function Templates 653 | 654 | Function templates are generic functions, which are operating on different data items.
655 | They describe a function format that when instantiated with particulars generates a function definition, basically it acts like a template schema which can be used 656 | for parameters with any datatype, instead of some fixed data type 657 | 658 | * Avoids redifinition of function 659 | 660 | * Makes code more reusable (write once, use multiple times) 661 | 662 | The C++ language allows the compiler to generate multiple versions of a function by allowing parameterized data types and hence it supports the parameterized polymorphism. 663 | 664 | The data items (types) are not declared while defining the function. 665 | 666 | Once when the function call is made using appropriate data type, then the template function is transformed to operate on that specific data types. 667 | 668 | #### Syntax 669 | 670 | ```cpp 671 | template 672 | returntype functionname(arguments) 673 | { 674 | ....... 675 | statements; 676 | ....... 677 | } 678 | ``` 679 | 680 | [See sample program 1 here](./template.cpp) 681 | [See sample program 2 here](./tempAdd.cpp) 682 | 683 | ### Class Template 684 | 685 | Generic classes with template data variables and template member functions 686 | 687 | [See a sample program here](./classTemplate.cpp) 688 | 689 | ## Standard Template Libraries 690 | 691 | The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL. 692 | 693 | ## 4 components of STL 694 | 695 | * Algorithms 696 | 697 | * Containers 698 | 699 | * Functions 700 | 701 | * Iterators 702 | 703 | ### 704 | 705 | ### Sample Programs 706 | 1. [Sample Program for Classes and Object 1](./IntroToOOPS.cpp) 707 | 2. [Sample Program for Classes and Object 2](./class1.cpp) 708 | --------------------------------------------------------------------------------