
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Print numbers having first and last bits as the only set bits
The task is to print the given n number which have exactly two set bits that neither less than 2 nor more than 2.
Set bits in computer language are the one that have value 1 and unset bits have value as 0
Input: value of num=5 Output: 1 3 5 As 1 is equivalent to 1 in binary 3 is equivalent to 11 in binary 5 is equivalent to 101 in binary
Algorithm
START Step 1 -> declare variable as unsigned int num=5 and int i=1 Step 2 -> print i Step 3 -> Loop For i=3 and i<=num and ++i IF (!(i-1 & i-2)) Print i End End STOP
Example
#include <stdio.h> int main(int argc, char const *argv[]) { unsigned int num = 5; int i = 1; printf("%d ", i); //printing first number 1 for (i = 3; i <= num; ++i) { if(!(i-1 & i-2)) //performing and operation on i-1 and i-2 printf("%d ", i); } return 0; }
Output
if we run the above program then it will generate the following output
1 3 5
- Related Articles
- Check whether the number has only first and last bits set in Python
- First and Last Three Bits in C++
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++
- Largest number less than X having at most K set bits in C++
- Find the number with set bits only between L-th and R-th index using C++
- Count of divisors having more set bits than quotient on dividing N in C++
- Count set bits using Python List comprehension
- Python Count set bits in a range?
- Maximum sum by adding numbers with same number of set bits in C++
- Find all combinations of k-bit numbers with n bits set where 1
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
- Copy set bits in a range in C++
- Count set bits in an integer in C++
- Count set bits in a range in C++

Advertisements