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

C Program: Union and Nibble Sum of a Hexadecimal Number

C Program: Union and Nibble Sum

๐Ÿ”ท C Program: Union and Nibble Sum of a Hexadecimal Number

#include <stdio.h>

union byteunion
{
    unsigned int full_word;
    unsigned char bytes[4];
};

int main( )
{
    union byteunion data;
    scanf("%x", &data.full_word);

    int upper_sum = 0, lower_sum = 0;

    printf("\nBytes: ");
    for (int i = 3; i >= 0; i--)
    {
        printf("0x%02X", data.bytes[i]);
        if (i != 0)
            printf(", ");
    }

    for (int i = 0; i < 4; i++)
    {
        int byte = data.bytes[i];
        int upper = byte / 16;
        int lower = byte % 16;
        upper_sum += upper;
        lower_sum += lower;
    }

    printf("\nUpper nibble addition: 0x%02x", upper_sum);
    printf("\nLower nibble addition: 0x%02X\n", lower_sum);
}
  

๐Ÿ“˜ Explanation:

This program demonstrates how to use a union in C to access individual bytes of a 32-bit hexadecimal input.

๐Ÿ”น A union is used to share memory between an unsigned int and an array of 4 bytes.
๐Ÿ”น The user inputs a 32-bit hexadecimal number.
๐Ÿ”น The program prints all 4 bytes from most significant to least significant.
๐Ÿ”น Each byte is split into upper and lower 4-bit nibbles.
๐Ÿ”น It then calculates and displays the sum of upper and lower nibbles separately in hexadecimal format.

๐Ÿ” Sample Output:

Input:
12345678

Output:
Bytes: 0x12, 0x34, 0x56, 0x78
Upper nibble addition: 0x15
Lower nibble addition: 0x14
    

๐Ÿท️ Keywords:

C union example, hexadecimal byte access, nibble sum, bitwise manipulation, memory sharing in C, byte array, 32-bit hex analysis

Comments

Popular Posts

๐ŸŒ™