Recursion

Recursion

 Recursion is a programming technique where a function calls itself in order to solve a problem. The function typically works by breaking down a large problem into smaller, more manageable subproblems, which it solves by calling itself. This continues until a base case is met, which stops the recursion.

A recursive function generally has two main parts:

  1. Base Case: This is the condition that stops the recursion and prevents the function from calling itself indefinitely. Without a base case, the recursion would continue forever.

  2. Recursive Case: This is where the function calls itself with modified arguments to work towards the base case.

1. Factorial Calculation

A function that calculates the factorial of a number.

#include <stdio.h>

int factorial(int n) {

    if (n == 0)

        return 1;

    return n * factorial(n - 1);

}

int main() {

    int num = 5;

    printf("Factorial of %d is %d\n", num, factorial(num));

    return 0;

}

2. Fibonacci Sequence

A function that returns the nth Fibonacci number.

#include <stdio.h>

int fibonacci(int n) {

    if (n <= 1)

        return n;

    return fibonacci(n - 1) + fibonacci(n - 2);

}

int main() {

    int num = 6;

    printf("Fibonacci number at position %d is %d\n", num, fibonacci(num));

    return 0;

}

3. Sum of Natural Numbers

A function to calculate the sum of natural numbers up to a given number.

#include <stdio.h>

int sumNaturalNumbers(int n) {

    if (n == 0)

        return 0;

    return n + sumNaturalNumbers(n - 1);

}

int main() {

    int num = 5;

    printf("Sum of natural numbers up to %d is %d\n", num, sumNaturalNumbers(num));

    return 0;

}

4. Power of a Number

A function to compute the power of a number.

#include <stdio.h>

 

int power(int base, int exp) {

    if (exp == 0)

        return 1;

    return base * power(base, exp - 1);

}

int main() {

    int base = 2, exp = 3;

    printf("%d raised to the power of %d is %d\n", base, exp, power(base, exp));

    return 0;

}

5. Binary Search (Recursive)

A function that searches for an element in a sorted array using recursion.

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int target) {

    if (low > high)

        return -1;

    int mid = (low + high) / 2;

    if (arr[mid] == target)

        return mid;

    if (arr[mid] > target)

        return binarySearch(arr, low, mid - 1, target);

    return binarySearch(arr, mid + 1, high, target);

}

int main() {

    int arr[] = {1, 3, 5, 7, 9, 11};

    int target = 7;

    int result = binarySearch(arr, 0, 5, target);

    if (result != -1)

        printf("Element found at index %d\n", result);

    else

        printf("Element not found\n");

    return 0;

}

6. Reverse a String

A function to reverse a string using recursion.

#include <stdio.h>

#include <string.h>

void reverseString(char str[], int start, int end) {

    if (start >= end)

        return;

    char temp = str[start];

    str[start] = str[end];

    str[end] = temp;

    reverseString(str, start + 1, end - 1);

}

int main() {

    char str[] = "Hello";

    reverseString(str, 0, strlen(str) - 1);

    printf("Reversed string: %s\n", str);

    return 0;

}

7. Finding GCD (Greatest Common Divisor)

A function to compute the greatest common divisor of two numbers using recursion.

#include <stdio.h>

int gcd(int a, int b) {

    if (b == 0)

        return a;

    return gcd(b, a % b);

}

int main() {

    int a = 56, b = 98;

    printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));

    return 0;

}

8. Tower of Hanoi

A function to solve the Tower of Hanoi problem.

#include <stdio.h>

void towerOfHanoi(int n, char source, char target, char auxiliary) {

    if (n == 1) {

        printf("Move disk 1 from %c to %c\n", source, target);

        return;

    }

    towerOfHanoi(n - 1, source, auxiliary, target);

    printf("Move disk %d from %c to %c\n", n, source, target);

    towerOfHanoi(n - 1, auxiliary, target, source);

}

int main() {

    int n = 3;

    towerOfHanoi(n, 'A', 'C', 'B');

    return 0;

}

9. Count Digits of a Number

A function that counts the number of digits in a number.

#include <stdio.h>

int countDigits(int n) {

    if (n == 0)

        return 0;

    return 1 + countDigits(n / 10);

}

int main() {

    int num = 12345;

    printf("Number of digits in %d is %d\n", num, countDigits(num));

    return 0;

}

10. Print All Natural Numbers Up to n

A function that prints all natural numbers from 1 to a given number.

#include <stdio.h>

void printNumbers(int n) {

    if (n == 0)

        return;

    printNumbers(n - 1);

    printf("%d ", n);

} 

int main() {

    int num = 5;

    printf("Natural numbers from 1 to %d: ", num);

    printNumbers(num);

    printf("\n");

    return 0;

}

Nested Loop Comparision

Nested Loop Comparision

Right Triangle and Its Mirror 

#include<stdio.h>

// Left-aligned triangle
void tr(int r){
    int i, j;
    for(i = 0; i <= r; i++, printf("\n"))
        for(j = 0; j <= i; j++)
            printf("*");
}

// Right-aligned triangle
void rtr(int r){
    int i, j;
    for(i = 0; i <= r; i++, printf("\n"))
        for(j = 0; j <= r; j++)
            printf(j < r - i ? " " : "*");
}

// Inverted left-aligned triangle
void itr(int r){
    int i, j;
    for(i = r; i >= 0; i--, printf("\n")) // Corrected the loop condition
        for(j = 0; j <= i; j++)
            printf("*");
}

// Full pyramid
void pr(int r){
    int i, j;
    for(i = 0; i <= r; i++, printf("\n")) {
        for(j = 0; j <= r - i; j++)  // spaces
            printf(" ");
        for(j = 0; j < 2*i - 1; j++) // stars
            printf("*");
    }
}

// Inverted Pyramid
void ipr(int r){
    int i, j;
    for(i = r; i >= 0; i--, printf("\n")) {
        for(j = 0; j <= r - i; j++)  // spaces
            printf(" ");
        for(j = 0; j < 2*i - 1; j++) // stars
            printf("*");
    }
}

// Inverted Mirrored Right Triangle
void ritr(int r){
    int i, j;
    for(i = r; i >= 0; i--, printf("\n"))
        for(j = 0; j <= r; j++)
            printf(j < r - i ? " " : "*");
}

int main(){
    tr(5);   // Left-aligned triangle
    printf("\n");  // Separator
    rtr(5);  // Right-aligned triangle
    printf("\n");  // Separator
    itr(5);  // Inverted left-aligned triangle
    printf("\n");  // Separator
    pr(5);   // Full pyramid
    printf("\n");  // Separator
    ipr(5);  // Inverted pyramid
    printf("\n");  // Separator
    ritr(5); // Inverted mirrored right triangle

    return 0;
}


output:
*
**
***
****
*****
******

     *
    **
   ***
  ****
 *****
******

******
*****
****
***
**
*

      
     *
    ***
   *****
  *******
 *********

 *********
  *******
   *****
    ***
     *
      

******
 *****
  ****
   ***
    **
     *

Number Triangle

#include<stdio.h>

// Left-aligned triangle with repeated numbers
void tr1(int r){
    int i, j;
    for(i = 1; i <= r; i++, printf("\n"))
        for(j = 1; j <= i; j++)
            printf("%d",i); // Print the row number i
}

// Left-aligned triangle with increasing numbers
void tr2(int r){
    int i, j;
    for(i = 1; i <= r; i++, printf("\n"))
        for(j = 1; j <= i; j++)
            printf("%d",j); // Print numbers from 1 to i
}

// Palindromic number triangle
void palin(int r){
    int i, j;
    for(i = 1; i <= r; i++, printf("\n")) {
        // Print leading spaces for centering
        for(j = 1; j <= r - i; j++) 
            printf(" ");
        
        // Print ascending part of the palindrome
        for(j = 1; j <= i; j++) 
            printf("%d",j);
        
        // Print descending part of the palindrome
        for(j = i - 1; j >= 1; j--)
            printf("%d",j);
    }
}

// Centered triangle with increasing numbers
void center(int r){
    int i, j;
    for(i = 1; i <= r; i++, printf("\n")) {
        // Print leading spaces for centering
        for(j = 1; j <= r - i; j++)
            printf(" ");
        
        // Print numbers increasing from 1 to i
        for(j = 1; j <= i; j++) 
            printf("%d", j);
        
        // Print numbers decreasing from i-1 to 1
        for(j = i - 1; j >= 1; j--) 
            printf("%d", j);
    }
}

// Inverted Palindromic number triangle
void ipalin(int r){
    int i, j;
    for(i = r; i >= 1; i--, printf("\n")) {
        // Print leading spaces for centering
        for(j = 1; j <= r - i; j++) 
            printf(" ");
        
        // Print ascending part of the palindrome
        for(j = 1; j <= i; j++) 
            printf("%d",j);
        
        // Print descending part of the palindrome
        for(j = i - 1; j >= 1; j--)
            printf("%d",j);
    }
}

// Inverted Centered triangle with decreasing numbers
void icenter(int r){
    int i, j;
    for(i = r; i >= 1; i--, printf("\n")) {
        // Print leading spaces for centering
        for(j = 1; j <= r - i; j++)
            printf(" ");
        
        // Print numbers increasing from 1 to i
        for(j = 1; j <= i; j++) 
            printf("%d", j);
        
        // Print numbers decreasing from i-1 to 1
        for(j = i - 1; j >= 1; j--) 
            printf("%d", j);
    }
}

int main(){
    tr1(5);    // Left-aligned triangle with repeated numbers
    printf("\n");  // Separator
    tr2(5);    // Left-aligned triangle with increasing numbers
    printf("\n");  // Separator
    palin(5);  // Palindromic number triangle
    printf("\n");  // Separator
    center(5); // Centered triangle with increasing numbers
    printf("\n");  // Separator
    ipalin(5); // Inverted Palindromic number triangle
    printf("\n");  // Separator
    icenter(5); // Inverted Centered triangle with decreasing numbers
    return 0;
}

Output:

1
22
333
4444
55555

1
12
123
1234
12345

    1
   121
  12321
 1234321
123454321

    1
   121
  12321
 1234321
123454321

123454321
 1234321
  12321
   121
    1

123454321
 1234321
  12321
   121
    1


File Handling

File Handling

Basic Syntax

FILE *file=fopen("xyx.txt","r/w/r+/w+/a");
if(!file)return printf("Error Msg"), 1;
.
.
.<<CODE>>>
.
.
fclose(file);


Red Color Highlight Meaning :
You Can Write As you Wish. Instead of file you can write suman,sabin, sunam etc, xyz.txt you can write abc.txt, xyz.doc etc.

File Creation

#include<stdio.h>
int main(){
    FILE *file=fopen("xyz.txt","w"); //here we are creating file                                             xyz.txt 
        if(!file) return printf("Tero File Sile Vetiyana, Ramro Sanga         Bana!");
        fprintf(file,"Hello Dasari!");//Content Here
        fprintf(file, "K cha tero Khabar?");
    fclose("file");
return 0;}


File Reading

Basic Syntax:

FILE *file=fopen("xyx.txt","r/w/r+/w+/a");
if(!file)return printf("Error Msg"), 1;
.
.

char line[];
fgets(line, sizeof(line),file);
printf("%s",line)
.
.
fclose(file);



Now Lets Demostrate

#include<stdio.h>
int main() {
    FILE *file = fopen("xyz.txt", "r");
        if(!file) return printf("error!"), 1;

        char line[100];
        fgets(line, sizeof(line), file);  // Read the first line
        printf("%s", line);               // Print it

    fclose(file);
return 0;
}


Write a program to allocate memory dynamically for a sentence to enter by user, ask user to know the no of character in his/her sentence



Here we will discuss how we can allocate memory and for that we will be using here <
iomanip> and here we will allocate it using cp pointer. Once we done we will clear the memory for that we will use delete function.

 /*Write a program to allocate memory dynamically for a sentence to enter by user, ask user to know the no of character in his/her sentence*/

#include<iostream>

#include<iomanip>

using namespace std;

int main(){

int n;

cout<<"How many character there are in your sentence?";

cin>>n;

char *cp= new char[n]; //dynamically memory allocation

cout<<"Enter your Sentence:";

cin.get(cp,n,'.');

cout<<"Entered sentence is"<<cp;

delete cp;// Memory Freeup

cout<<endl<<"after deallocating memory:"<<cp;

return 0;

}



Write a program to allocate memory dynamically for a sentence to enter by user, ask user to know the no of character in his/her sentence

 /*Write a program to allocate memory dynamically for a sentence to enter by user, ask user to know the no of character in his/her sentence*/

#include<iostream>

#include<iomanip>

using namespace std;

int main(){

int n;

cout<<"How many character there are in your sentence?";

cin>>n;

char *cp= new char[n]; //dynamically memory allocation

cout<<"Enter your Sentence:";

cin.get(cp,n,'.');

cout<<"Enter
ed sentence is"<<cp;

return 0;

}


Dynamic Memory Allocation

Now we will learn how to use the memory allocation. Here we will include<iomanip> .

 /*Dynamic Memory Allocation*/

#include<iostream>

#include<iomanip> 

using namespace std;

int main(){

int n;

cout<<"How many integers you have?";

cin>>n;

int *p=new int[n];

cout<<"Enter "<<n<<"Integers:";

for(int i=0;i<n;i++)

cin>>p[i];


for(int i=0;i<n;i++)

cout<<p[i]<<setw(5);//setw for space input

return 0;}

setw is used to give space for 5 decimal.



Write program to take your full name, email id, contact address in a single variable with new line character embedded in text and display it

Here We will Discuss how we will take multiline input. Previously we had performed it using cin and cout function but while using it will give us the output which is before the space so we will use get() fuction, It is an overloaded function which is used as get(char), get(char,count),get(char,count,deliminator)

/*How to take sentence from user*/

#include<iostream>

using namespace std;

int main(){

char name[20];

cout<< "Enter Your Full Name:";

cin.get(name,20); //get(char),get(char*,Count),get(char*,count,delim)

cout<<"Welcome"<<name;

return 0;}


If we wish to take full paragraph then we have to do it as follows:
/*How to take sentence from user*/
#include<iostream>
using namespace std;

int main(){
char name[200];
cout<< "Enter any paragraph(enter $ for the finish): ";
cin.get(name,200,'$');
cout<<"You had written"<<endl<<name;
return 0;}


now Lets proceed to our final Task.

/*Write program to take your fullname, email id, contact address in a single variable with new line character embedded in text and display it*/
#include<iostream>
using namespace std;

int main(){
char info[100];
cout<<"Enter your Detail";
cin.get(info,100,'$');

cout<<"Your Detail is"<<endl;
cout<<info;

return 0;}