Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

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

๐ŸŒ™