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...

Nibble Swapping in C (Hexadecimal Input) in C

Nibble Swapping in C

๐Ÿ”ถ Nibble Swapping in C (Hexadecimal Input)

#include<stdio.h>
int main( )
{
    unsigned int num;
    printf("Enter the number(in hex):");
    scanf("%x",&num);
    num = num & 0xFF;
    unsigned int swapped = ((num & 0x0F) << 4) | ((num & 0xF0) >> 4);
    printf("After swapping number is: %02X\\n", swapped);
    return 0;
}
  

๐Ÿ“˜ Explanation:

This C program swaps the upper and lower 4-bit nibbles of an 8-bit hexadecimal number.

๐Ÿ”น `scanf("%x", &num);` reads a hexadecimal value.
๐Ÿ”น `num & 0xFF` ensures the value is within 8 bits.
๐Ÿ”น `(num & 0x0F) << 4` moves the lower nibble to the upper nibble position.
๐Ÿ”น `(num & 0xF0) >> 4` moves the upper nibble to the lower nibble position.
๐Ÿ”น The final result is obtained by combining both using bitwise OR (`|`).
๐Ÿ”น `%02X` prints the swapped result in uppercase hexadecimal format with leading zero if needed.

๐Ÿ” Sample Output:

Enter the number(in hex):3C
After swapping number is: C3

Enter the number(in hex):F0
After swapping number is: 0F
    

๐Ÿท️ Keywords:

bitwise operations in C, swap nibbles C, C program hex input, 8-bit nibble swap, binary logic in C, nibble masking, hex manipulation

Comments

Popular Posts

๐ŸŒ™