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

Count Set Bits in an Integer (C Program)

Count Set Bits in C

๐Ÿ”ข Count Set Bits in an Integer (C Program)

#include<stdio.h>
int count_set_bits(int num)
{
    unsigned int mask = (unsigned int)num;
    int count = 0;
    while(mask)
    {
        count += mask & 1;
        mask >>= 1;
    }
    return count; 
}
int main( )
{
    int number;
  //  printf("Enter the number: ");
    scanf("%d", &number);
    int result = count_set_bits(number);
    printf("The count of set bits is %d\\n", result);
}
  

๐Ÿ“˜ Explanation:

This program counts the number of set bits (1s) in the binary representation of an integer using bitwise operations.

๐Ÿ”น `mask & 1` checks the least significant bit (LSB) of the number.
๐Ÿ”น If it's 1, `count` is incremented.
๐Ÿ”น The mask is then right-shifted using `mask >>= 1` to check the next bit.
๐Ÿ”น The loop continues until the entire binary number is processed.

๐Ÿ”ธ Note: Casting `num` to `unsigned int` ensures correct behavior for negative numbers (avoiding sign extension).

๐Ÿ” Sample Output:

Input:
13

Output:
The count of set bits is 3
    

๐Ÿท️ Keywords:

count set bits C, number of 1s in binary, bitwise AND, C bit manipulation, right shift, count bits using loop

Comments

Popular Posts

๐ŸŒ™