Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

Reverse Number Using Recursion in C

C Program: Reverse Number Using Recursion

๐Ÿ”ท C Program: Reverse Number Using Recursion

#include<stdio.h>

int reverse(int num, int rev)
{
    if(num == 0)
    {
        return rev;
    }
    else
    {
        return reverse(num / 10, rev * 10 + num % 10);
    }
}

int main()
{
    int num, result;
    printf("Enter the number:\n");
    scanf("%d", &num);

    printf("Before Reversing: %d\n", num);

    if(num <= 0)
    {
        result = reverse(-num, 0);
        printf("After Reversing: -%d\n", result);
    }
    else
    {
        result = reverse(num, 0);
        printf("After Reversing: %d\n", result);
    }
}
  

๐Ÿ“˜ Explanation:

This C program uses a **recursive function** to reverse a given number.

๐Ÿ”ธ The `reverse()` function takes two arguments: - `num`: the original number (or part of it as recursion progresses)
- `rev`: the reversed number being constructed

๐Ÿ”ธ The base condition is when `num` becomes 0. At that point, the accumulated `rev` is returned.

๐Ÿ”ธ During each recursive call: - The last digit of `num` (`num % 10`) is added to `rev` after multiplying `rev` by 10 to shift its digits left.
- Then `num` is reduced by removing the last digit using integer division (`num / 10`).

๐Ÿ”ธ Special handling is added to work with **negative numbers** by reversing the absolute value and printing a minus sign manually.

๐Ÿ” Sample Output:

Enter the number:
1234
Before Reversing: 1234
After Reversing: 4321

Enter the number:
-786
Before Reversing: -786
After Reversing: -687

Enter the number:
0
Before Reversing: 0
After Reversing: 0
    

๐Ÿท️ Keywords:

C reverse number program, recursion in C, reverse using recursion, reverse number logic, C number manipulation, beginner recursion program

Comments

Popular Posts

๐ŸŒ™