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 to Count Total Set Bits in an Array

C Program to Count Total Set Bits in an Array

✅ C Program to Count Total Set Bits in an Array

#include <stdio.h>

int countSetBits(int num) {
    int count = 0;
    while (num > 0) {
        count += (num & 1);  // check last bit
        num >>= 1;           // right shift
    }
    return count;
}

int main() {
    int n;
    printf("Enter size of array: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int totalBits = 0;
    for (int i = 0; i < n; i++) {
        totalBits += countSetBits(arr[i]);
    }

    printf("Total number of set bits in the array = %d\n", totalBits);
    return 0;
}
  

๐Ÿ“˜ Explanation:

This C program counts how many set bits (1s) appear in the binary representation of all elements in an array.

  • countSetBits() checks each bit using num & 1 and shifts right until the number becomes 0.
  • The array elements are input by the user.
  • Each element’s set bits are added to totalBits.
  • The final result is displayed.

๐Ÿงพ Sample Output:

Enter size of array: 4
Enter 4 elements:
5 7 8 3
Total number of set bits in the array = 8
  

๐Ÿ”‘ Keywords:

C program set bits, bitwise AND, right shift operator, count 1s in array, binary representation in C, coding interview C

๐Ÿ“Œ Hashtags:

#CProgramming #BitManipulation #SetBits #InterviewQuestion #LearnC #CodingForBeginners

๐Ÿ” Search Description:

This C program counts the total number of set bits in an array using bitwise operations. Efficient approach with clear explanation and sample output.

Comments

Popular Posts

๐ŸŒ™