Skip to main content

Featured

C Pattern Programs: Square Number and Alphabet Patterns Explained

πŸ”· Square Star Pattern πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("* ");//keep"* " } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Column-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = num; i >= 1; i--) { for(int j = num; j >= 1; j--) { printf("%c ", j + 64);//%c for Character and 64 will be ASIIC VALUE } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Row-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; ...

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

πŸŒ™