Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

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

๐ŸŒ™