Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

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

๐ŸŒ™