pascal's Triangle implementation - c++

I am trying to make a program for pascal's triangle,the formaula to calculate the rth value in nth row is n!/r!(n-r)!
I've been tring to implement it like this:
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setw
int Pascal(int ,int );
int Factorial( int);
int main ()
{
int n=0;//Number of rows in the triangle
for(int i=12;i>0;i--)
{
std::cout << std::setw(i)<<std::endl;
for (int j=1;j<12-i;j++)
{
int r=0; //rth element initialized for each row
int P= Pascal(r,n);
std::cout << P ;
std::cout <<std::setw(2);
r=r+1;
}
n=n+1;
}
std::cout<<std::endl;
return 0;
}
int Pascal(int r,int n)
{
int d = n-r; ///Difference of n with r
int f1; ///factorial of n
int f2; ///factorial of r
int f3; ///factorial of (n-r)
f1=Factorial(n);
f2=Factorial(r);
f3=Factorial(d);
return f1/(f2*f3);
}
int Factorial( int begin )
{
int F;
if ( begin == 0 )
{
return 1;
}
else
{
F= begin*Factorial(begin-1);
}
return F;
}
but somehow I am getting this output:
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 112
Could someone guide me where am I going wrong?

Your first, obvious problem is of course that you should be printing Pascal(i,j). Your second is more subtle:
Recursion
The whole point of Pascal's Triangle is that it gives a way of computing binomial coefficients without needing to compute the factorials.
The problem is factorials grow really quickly and a coefficient such as Pascal(1,120) = 120!/(1!*119!}, is equal only to 120, but its nominator and denominator are on the order of 10^198 which could not be stored in any machine integer type.
Check out Pascal's Triangle on Wikipedia. The whole point is the recursive relation:
Pascal( r, n ) = Pascal( r-1, n-1 ) + Pascal( r, n-1 )
Here's a simple solution making use of that (this only prints the r,n pascal number):
#include <iostream>
#include <sstream>
int pascal( int r, int n ) {
if( n == 0 )
return 1;
if( r == 0 || r == n )
return 1;
return pascal( r - 1, n - 1 ) + pascal( r, n - 1 );
}
int main( int argc, char *argv[] ) {
if( argc != 3 ) {
std::cout << "Expected exactly 3 arguments." << std::endl;
return -1;
}
int r, n;
std::stringstream ss;
ss << argv[1] << ' ' << argv[2];
ss >> r >> n;
if( ss.bad() || r < 0 || n < 0 || r > n ) {
std::cout << "Invalid argument values." << std::endl;
return -2;
}
std::cout << pascal( r, n ) << std::endl;
return 0;
}
Memoization
There is a third and even more subtle problem with this method, its complexity is much worse than it needs to be. Think about computing Pascal(3,6):
Pascal(3,6) =
= Pascal(2,5) + Pascal(3,5) =
= (Pascal(1,4)+Pascal(2,4)) + (Pascal(2,4)+Pascal(3,4)) = ...
In that last line you'll notice Pascal(2,4) appears twice which means your code will compute it twice. Futhermore Pascal( 3, 5 ) is actually equal to Pascal(2,5). So your could is computing Pascal(2,5) twice, which means computing Pascal(2,4) four times. This means as r and n grow large the program will be very slow. We would like to compute each Pascal(i,j) a single time and then save its value to be used by other calls. To do this, a simple way is to use a map which maps (r,n) pairs to Pascal(r,n) values: std::map< std::pair, int >. This method is called memoization. Also, changing ints to long long for big numbers, you get the following algorithm:
#include <iostream>
#include <sstream>
#include <map>
typedef long long Integer;
typedef std::map< std::pair< Integer, Integer >, Integer > MemoMap;
typedef MemoMap::iterator MemoIter;
MemoMap memo;
Integer pascal( Integer r, Integer n ) {
// make sure r <= n/2 using the fact that pascal(r,n)==pascal(n-r,n)
if( r > n / 2LL )
r = n - r;
// base cases
if( n == 0LL || r == 0LL )
return 1LL;
// search our map for a precalculated value of pascal(r,n)
MemoIter miter = memo.find( std::make_pair( r, n ) );
// if it exists return the precalculated value
if( miter != memo.end() )
return miter->second;
// otherwise run our function as before
Integer result = pascal( r - 1LL, n - 1LL ) + pascal( r, n - 1LL );
// save the value and return it
memo.insert( std::make_pair( std::make_pair( r, n ), result ) );
return result;
}
int main( int argc, char *argv[] ) {
if( argc != 3 ) {
std::cout << "Expected exactly 3 arguments." << std::endl;
return -1;
}
Integer r, n;
std::stringstream ss;
ss << argv[ 1 ] << ' ' << argv[ 2 ];
ss >> r >> n;
if( ss.bad() || r < 0LL || n < 0LL || r > n ) {
std::cout << "Invalid argument values." << std::endl;
return -2;
}
std::cout << pascal( r, n ) << std::endl;
return 0;
}
Before, Pascal(5,100) would never terminate. Now it finishes instantly on my computer. Integrate this code into yours and you'll be a happy panda.
Bottom-up
Memoization is top-down dynamic programming i.e. you first think of the hardest problem and then divide it into simpler, overlapping problems while saving the results along the way. A bottom up solution would start with the first row of the Pascal Triangle and keep computing following rows - this is more efficient, both in speed and memory (storing only two arrays).
The top-down method however is easier to implement (you don't have to think about what values you're going to need you just save everything) and it allows you to save intermediate results between independent pascal() calls. In your case, since you're trying to print Pascal's Triangle by calling pascal independently many times, this is the appropriate method. If you print and compute at the same time, bottom up is by far the most efficient way of doing it:
#include <iostream>
#include <sstream>
#include <vector>
typedef long long Integer;
void print_pascal( Integer maxn ) {
std::vector< Integer > prevRow, currentRow;
prevRow.resize( maxn + 1 );
currentRow.resize( maxn + 1);
prevRow[ 0 ] = 1;
// print first row.
std::cout << 1 << std::endl;
for( Integer currentN = 1 ; currentN <= maxn ; ++ currentN ) {
// compute & print current row
currentRow[ 0 ] = currentRow[ currentN ] = 1;
std::cout << 1;
for( Integer r = 1 ; r < currentN ; ++ r ) {
currentRow[ r ] = prevRow[ r - 1 ] + prevRow[ r ];
std::cout << ' ' << currentRow[ r ];
}
std::cout << ' ' << 1 << std::endl;
// constant time because swap() only swaps internal ptrs.
currentRow.swap( prevRow );
}
}
int main( int argc, char *argv[] ) {
if( argc != 2 ) {
std::cout << "Expected exactly 1 argument." << std::endl;
return -1;
}
Integer maxn;
std::stringstream ss;
ss << argv[ 1 ]; ss >> maxn;
if( ss.bad() || maxn < 0LL ) {
std::cout << "Invalid argument values." << std::endl;
return -2;
}
print_pascal( maxn );
return 0;
}

The very first thing you've gone wrong at is the formatting of your code. It's horrible. (Sorry, it really is.)
The second thing is that you are always printing Pascal(r, n) whereas they are constant 0, 0 - you should print Pascal(i, j) instead, since i and j are the loop counters.
By the way, you'd be better off calculating the factorials iteratively and using long enough integers, your code threw SIGXCPU on IDEOne and segfaulted on my computer.

Related

For loop crashes program while trying to read array c++

Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.
Lets say s = 4 and A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)
My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?
#include <iomanip>
using namespace std;
int ordering(int s, int n, int A[]);
int main()
{
int n, A[n];
int s;
cout << "Vlera e s: ";
cin >> s;
if (s <= 0)
{
return 1;
}
cout << "\nN: ";
cin >> n;
if (n <= 0)
{
return 1;
}
cout << "\nVector:";
for (int i = 0; i < n; i++)
{
A[i] = i + 1;
cout << " " << A[i] << " ";
}
if (s > n)
{
cout << "\nNo change\n";
return 0;
}
else
{
ordering(s, n, A);
}
cout << "\nNew vector:";
for (int i = 0; i < n; i++)
{
cout << " " << A[i] << " ";
}
return 0;
}
int ordering(int s, int n, int A[])
{
int counter = 0;
for (int i = 0, divider = n / s; i < divider; i++)
{
int decrease = 0;
for (int j = counter, a = counter + s; j < a; j++)
{
A[j] = a - decrease;
decrease++;
}
counter += s;
}
return 0;
}
This program using a compiler extension to allow variable sized arrays in the form myArray[variableSize]. Whilst not standard, it does work on some compilers.
You are using this feature here:
int n, A[n];
However, n is uninitialised at this point. This is undefined behaviour even on the compilers that support such variable sized arrays. One possible (but not the only) outcome of undefined behaviour is your program crashing.
Undefined behaviour can do anything in theory, but the realistic set of things in can do in reality is smaller. Some of the likely implications of the undefined behaviour here:
n has some huge number in it, from whatever last used that bit of memory. As a result, A is huge.
n is 0. You can't have a 0 sized array. If the compiler doesn't notice this, you could end up trashing memory.
Since n is uninitialised, the optimiser for the compiler (they usually do very some optimisations, even when on -O0) assumes that undefined behaviour cannot occur, which is violated here, leading to strange behaviour.
n is a reasonable value, just by luck, but because it is later updated it no longer matches the size of the array and you end up reading / writing memory off the end of the array, trashing memory.
There are other possibilities, but this gives an idea of the kind of things that can happen as a result of this specific instance of undefined behaviour. If you're interested to know more, using a debugger to step through the code in assembly (you only need learn a little to understand the output, it looks more scary than it need be) will show you what's actually happening.
Variable length arrays is not a standard C++ feature.
int n, A[n];
Moreover in the above declaration the variable n was not initialized. So in any case the program has undefined behavior.
Instead of an array you could use the standard class template std::vector.
The program can look simpler and more safer is to use standard algorithms such as, for example, std::reverse.
Here is a demonstrative program.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
void reorder( std::vector<int> &v, size_t s )
{
if ( not ( s < 2 ) )
{
for ( auto last = std::end( v );
not (std::distance( std::begin( v ), last ) < s ); )
{
auto first = std::prev( last, s );
std::reverse( first, last );
last = first;
}
}
}
int main()
{
std::cout << "Vlera e s: ";
size_t s = 0;
std::cin >> s;
std::cout << "N: ";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
std::iota( std::begin( v ), std::end( v ), 1 );
putchar( '\n' );
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
reorder( v, s );
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look like
Vlera e s: 4
N: 10
1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7
But it seems you need write the corresponding code yourself using loops. In this case the program can look like
#include <iostream>
#include <vector>
void reorder( std::vector<int> &v, size_t s )
{
if ( not ( s < 2 ) )
{
for ( auto n = v.size(); !( n < s ); n -= s )
{
for ( size_t i = 0; i < s / 2; i++ )
{
int value = v[n - s + i];
v[n - s + i] = v[n - i - 1];
v[n - i - 1] = value;
}
}
}
}
int main()
{
std::cout << "Vlera e s: ";
size_t s = 0;
std::cin >> s;
std::cout << "N: ";
size_t n = 0;
std::cin >> n;
std::vector<int> v( n );
int value = 1;
for ( auto &item : v ) item = value++;
putchar( '\n' );
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
reorder( v, s );
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look as already shown above
Vlera e s: 4
N: 10
1 2 3 4 5 6 7 8 9 10
1 2 6 5 4 3 10 9 8 7
Passing variable as array size is not valid you need to use constant const int n or create dinamic array int* arr = new int[n];, that array will be created in runtime, and you can pass variable as it size. Dont forget to delete that array whet it goes out of scope delete[] arr;

Combination of unique elements without repetition

Elements : a b c
all combinations in such a way:abcabacbcabc
Formula to get total number of combinations of unique elements without repetition = 2^n - 1 (where n is the number of unique elements)
In our case top: 2^3 - 1 = 7
Another formula to get the combinations with specific length = n!/(r! * (n - r)!) (where n= nb of unique items and r=length)
Example for our the above case with r=2 : 3!/(2! * 1!) = 3 which is ab ac bc
Is there any algorithm or function that gets all of the 7 combinations?
I searched a lot but all i can find is one that gets the combinations with specific length only.
UPDATE:
This is what I have so far but it only gets combination with specific length:
void recur(string arr[], string out, int i, int n, int k, bool &flag)
{
flag = 1;
// invalid input
if (k > n)
return;
// base case: combination size is k
if (k == 0) {
flag = 0;
cout << out << endl;
return;
}
// start from next index till last index
for (int j = i; j < n; j++)
{
recur(arr, out + " " + arr[j], j + 1, n, k - 1,flag);
}
}
The best algorithm I've ever find to resolve this problem is to use bitwise operator. You simply need to start counting in binary. 1's in binary number means that you have to show number.
e.g.
in case of string "abc"
number , binary , string
1 , 001 , c
2 , 010 , b
3 , 011 , bc
4 , 100 , a
5 , 101 , ac
6 , 110 , ab
7 , 111 , abc
This is the best solution I've ever find. you can do it simply with loop. there will not be any memory issue.
here is the code
#include <iostream>
#include <string>
#include <math.h>
#include<stdio.h>
#include <cmath>
using namespace std;
int main()
{
string s("abcd");
int condition = pow(2, s.size());
for( int i = 1 ; i < condition ; i++){
int temp = i;
for(int j = 0 ; j < s.size() ; j++){
if (temp & 1){ // this condition will always give you the most right bit of temp.
cout << s[j];
}
temp = temp >> 1; //this statement shifts temp to the right by 1 bit.
}
cout<<endl;
}
return 0;
}
Do a simple exhaustive search.
#include <iostream>
#include <string>
using namespace std;
void exhaustiveSearch(const string& s, int i, string t = "")
{
if (i == s.size())
cout << t << endl;
else
{
exhaustiveSearch(s, i + 1, t);
exhaustiveSearch(s, i + 1, t + s[i]);
}
}
int main()
{
string s("abc");
exhaustiveSearch(s, 0);
}
Complexity: O(2^n)
Here's an answer using recursion, which will take any number of elements as strings:
#include <vector>
#include <string>
#include <iostream>
void make_combos(const std::string& start,
const std::vector<std::string>& input,
std::vector<std::string>& output)
{
for(size_t i = 0; i < input.size(); ++i)
{
auto new_string = start + input[i];
output.push_back(new_string);
if (i + 1 == input.size()) break;
std::vector<std::string> new_input(input.begin() + 1 + i, input.end());
make_combos(new_string, new_input, output);
}
}
Now you can do:
int main()
{
std::string s {};
std::vector<std::string> output {};
std::vector<std::string> input {"a", "b", "c"};
make_combos(s, input, output);
for(auto i : output) std::cout << i << std::endl;
std::cout << "There are " << output.size()
<< " unique combinations for this input." << std::endl;
return 0;
}
This outputs:
a
ab
abc
ac
b
bc
c
There are 7 unique combinations for this input.

Inconsistent Quick Sort Function

So I have written this quick sort function, and it works for SOME input.
For example it works for the following inputs : "5 4 3 2 1", "3 4 5 6 7", etc.
However when I input something like : "0 3 5 4 -5 100 7777 2014" it will always mix up the multi digit numbers.
I was hoping someone could help point me to where my code is failing at this test case.
Sort.cpp
std::vector<int> QuickSort::sortFunc(std::vector<int> vec, int left, int right) {
int i = left, j = right;
int tmp;
int pivot = vec.at( (left + right) / 2 );
/* partition */
while (i <= j) {
while (vec.at(i) < pivot)
i++;
while (vec.at(j) > pivot)
j--;
if (i <= j) {
tmp = vec.at(i);
vec.at(i) = vec.at(j);
vec.at(j) = tmp;
i++;
j--;
}
}
/* recursion */
if (left < j)
return sortFunc( vec, left, j );
if (i < right)
return sortFunc( vec, i, right );
else
{
return vec;
}
}
main.cpp
int main()
{
// The user inputs a string of numbers (e.g. "6 4 -2 88 ..etc") and those integers are then put into a vector named 'vec'.
std::vector<int> vec;
// Converts string from input into integer values, and then pushes said values into vector.
std::string line;
if ( getline(std::cin, line) )
{
std::istringstream str(line);
int value;
str >> value;
vec.push_back( value );
while ( str >> value )
{
vec.push_back( value );
}
}
// Creating QuickSort object.
QuickSort qSort;
QuickSort *ptrQSort = &qSort;
// Creating new vector that has been 'Quick Sorted'.
int vecSize = vec.size();
std::vector<int> qSortedVec;
qSortedVec = ptrQSort->sortFunc( vec, 0, vecSize-1 );
// Middle, start, and end positions on the vector.
int mid = ( 0 + (vec.size()-1) ) / 2;
int start = 0, end = vec.size() - 1;
// Creating RecursiveBinarySearch object.
RecursiveBinarySearch bSearch;
RecursiveBinarySearch *ptrBSearch = &bSearch;
//bool bS = ptrBSearch->binarySearch( qSortedVec, mid, start, end );
bool bS = ptrBSearch->binarySearch( bSortedVec, mid, start, end );
/*--------------------------------------OUTPUT-----------------------------------------------------------------------*/
// Print out inputted integers and the binary search result.
// Depending on the binary search, print either 'true' or 'false'.
if ( bS == 1 )
{
std::cout << "true ";
}
if ( bS == 0 )
{
std::cout << "false ";
}
// Prints the result of the 'quick sorted' array.
int sortedSize = qSortedVec.size();
for ( int i = 0; i < sortedSize; i++ )
{
std::cout << qSortedVec[i] << " ";
}
std::cout << "\n";
return 0;
}
Thanks for any and all help you can give me guys.
I'm not sure if this solves it completely, but after sorting the left part, you still need to sort the right part, but you already return instead.
Also, passing the vector by value and returning it is overhead and not needed, because in the end there should only be one version of the vector, so passing by reference is preferred. Passing by value and returning is sometimes needed when doing recursion, especially when backtracking (looking for different paths), but not in this case where left and right provide the needed state.

Program about Fibonacci numbers

I am obliged to write program that will show minimal quantity of Fibonacci numbers which sum is equal to k number which user write into program.
So for example user writes 1070
And the program will show 987 89 -5 -1 (because all of these numbers are Fibonacci numbers (you can add or substract to get desired sum).
I have problem to think about solution to this problem.
I wrote code to get all Fibonacci numbers from 0 to 46.
#include <iostream>
unsigned long long Fibbo[47];
void preapare()
{
Fibbo[0] = 0;
Fibbo[1] = 1;
i = 2;
while (i<47)
{
Fibbo[i] = Fibbo[i - 1] + Fibbo[i - 2];
i++;
}
}
int main()
{
preapare();
int k=0;
std::cin >> k;
}
I will be glad for any help. You can use Fibonacci Number as many times as you will. For example you can do 1+1+1+1+1
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
void prepare( vector<int> & fibos ) { ... } // along the lines we see in OPs code
int findClosest( int n, vector<int> & fibos ){ // return Fibonacci number closest to n
int fi = 0;
for( std::vector<int>::iterator it = fibos.begin() ; it != fibos.end(); ++it){
if( abs(*it - n) < abs(fi - n) ){
fi = *it;
}
}
return fi;
}
// The algorithm:
// lookup closest Fi, add "signed" to terms
// reduce n, adjust sign and call recursively
void sum( int n, vector<int> & fibos, vector<int> & terms, int sign = 1 ){
if( n == 0 ) return;
int fi = findClosest( n, fibos );
terms.push_back( sign*fi );
sum( abs(n - fi), fibos, terms, n - fi > 0 ? sign : -sign );
}
int main() {
vector<int> fibos;
prepare( fibos );
vector<int> terms;
int n = 1070;
sum( n, fibos, terms );
cout << n << " =";
for( std::vector<int>::iterator it = terms.begin() ; it != terms.end(); ++it){
cout << " " << *it;
}
cout << endl;
return 0;
}
For user input:
Before the while loop, you need to get the input, save it to a variable, and use that in your while condition. Something like this:
#include <iostream>
...
int k_val = 0;
std::cout << "Enter the value for k: ";
std::cin >> k_val;
...
Your prepare() fixed:
unsigned long long* preapare(const size_t n) {
unsigned long long* Fibbo = new unsigned long long[n];
Fibbo[0] = 0;
Fibbo[1] = 1;
for(size_t i = 2; i < n; ++i) {
Fibbo[i] = Fibbo[i - 1] + Fibbo[i - 2];
}
return Fibbo;
}
then you'll have to memory manage the returned array;
I've done this, the code will solve the grater fibonacci numbers to be add so the result will be the specified number:
fiboMax return a sequence with the fibonacci number less to the input number.
getiboSec return a sequence with the bigger fibonacci numbers that sum the input number.
'''
Created on 15/01/2014
'''
def fiboMax(num):
ret = [0,1]
a = 1
b = 2
while b < num:
ret.append(b)
tmp = a + b
a = b
b = tmp
return ret
def getFiboSec(num):
fiboSec = []
fiboNumbers = fiboMax(num)
i = len(fiboNumbers) - 1
while num > 0 and i > 0:
fiboNum = fiboNumbers[i]
while(fiboNum <= num):
fiboSec.append(fiboNum)
num -= fiboNum
i -= 1
return fiboSec
if __name__ == '__main__':
num = 20
print(fiboMax(num))
print(getFiboSec(num))
output:
figonnaci number to 20 = [0, 1, 2, 3, 5, 8, 13]
fibonacci number that sum 20 = [13, 5, 2]
It doesnt work with negative numbers, anyway its solving the problem but not the efficient way.
You are accessing the indexes -2 and -1 in your loop. Your variable i should start at 2. You also try to add values to pointers. None of your values in Fibbo[] are set.

c++ Algorithm to convert an integer into an array of bool

I'm trying to code an algorithm that will save to file as binary strings every integer in a range. Eg, for the range 0 to 7:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Note that the leading zeros and spaces between digits are essential.
What I cant figure out how to do in a simple way is to convert the integers to binary numbers represented by bool []s (or some alternate approach).
EDIT
As requested, my solution so far is:
const int NUM_INPUTS = 6;
bool digits[NUM_INPUTS] = {0};
int NUM_PATTERNS = pow(2, NUM_INPUTS);
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1 ; w--)
{
if( ! ((q+1) % ( (int) pow(2, w))) )
digits[w] = !digits[w];
outf << digits[w] << " ";
}
outf << "\n";
}
Unfortunately, this is a bit screwy as the first pattern it gives me is 000001 instead of 000000.
This is not homework. I'm just coding a simple algorithm to give me an input file for training a neural network.
Don't use pow. Just use binary math:
const int NUM_INPUTS = 6;
int NUM_PATTERNS = 1 << NUM_INPUTS;
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1; w--)
{
outf << ((q>>w) & 1) << " ";
}
outf << "\n";
}
Note: I'm not providing code, but merely a hint because the question sounds like homework
This is quite easy. See this example:
number = 23
binary representation = 10111
first digit = (number )&1 = 1
second digit = (number>>1)&1 = 1
third digit = (number>>2)&1 = 1
fourth digit = (number>>3)&1 = 1
fifth digit = (number>>4)&1 = 1
Alternatively written:
temp = number
for i from 0 to digits_count
digit i = temp&1
temp >>= 1
Note that the order of digits taken by this algorithm is the reverse of what you want to print.
The lazy way would be to use std::bitset.
Example:
#include <bitset>
#include <iostream>
int main()
{
for (unsigned int i = 0; i != 8; ++i){
std::bitset<3> b(i);
std::cout << b << std::endl;
}
}
If you want to output the bits individually, space-separated, replace std::cout << b << std::endl; with a call to something like Write(b), with Write defined as:
template<std::size_t S>
void Write(const std::bitset<S>& B)
{
for (int i = S - 1; i >= 0; --i){
std::cout << std::noboolalpha << B[i] << " ";
}
std::cout << std::endl;
}