Fibonacci series in C++ can't get more than 47 numbers - c++

I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}

When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.

You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>

This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}

Related

What is wrong in this code? (Largest and Smallest element in array)

This is my code in C++. When I am taking input {11 10 5 6 7} in the array, Every time it's giving output smallest as 0. But giving correct output to the other inputs.
#include<bits/stdc++.h>
using namespace std;
int main() {
int a[100000];
int large, small;
int n;
cin >> n;
for (int j = 0; j < n; j++) {
cin >> a[j];
}
for (int j = 0; j < n; j++) {
cout << a[j] << " ";
}
large = small = a[0];
for (int i = 1; i <= n; i++) {
if (a[i] < small) {
small = a[i];
}
if (a[i] > large) {
large = a[i];
}
}
cout << "Smallest is " << small << endl;
cout << "Largest is " << large << endl;
}
You have three loops, two of them run while i<n and the third one while i<=n. And then it uses a[n] item. How do you think what the value of a[n] is?
You were asking:
What is wrong in my code
Let me first answer this question and then we will refactor and optimize it.
So, let's list up the findings
#include<bits/stdc++.h> is non-compliant C++ code. It should never be used. It will run only on selected compilers
using namespace std; should not be used. Always use fully qualified names
C-Style arrays, like a[100000] should not be used in C++. Always use dedicated C++ containers like std::array or std::vector or others. In your case, the size of the array is determined at runtime. So, std::vector must be used
the “100000” is a magic number. Why 100000? Why not 500?. And what happens if the user enters 200000 as array size. Then the program will most likely crash
Use always meaningful variable names. Something like “n” will not be understood. The variable “arraySize” would be understood.
Variables shall always be initialized. And only defined, where they are used and not in the beginning of the program
Input should be verified (cin >> n). What will happen, if the user enters ‘x’ and not ‘5’. Remember, you do not initialize variable n.
large and small must be initialized with the smallest / largest value that the relevant data type can hold. Otherwise the result will always be wrong
array indices start with 0 and not with 1. So, your for loop will fail. The result will be wrong. And you used <=n. So, you will access an out of bounds value.
No need to use endl with cout. ‘\n’ will be sufficient
Then, from the design point of view. You do not need an array at all. You can make all checks immediately, directly after reading the next value.
Anyway, let us make the first step of refactoring. And ths adopted to your programming style. We will
still use C-Style arrays and dynamically allocate the memory
even use raw pointers for owned memory and new. Please note. This should not be done!
correct the bugs
use INT_MIN and INT_MAX
use meaningful variable names and comments
Please see the first refactoring step:
#include <iostream>
#include <climits>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
int* const array = new int[arraySize]();
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = INT_MIN;
int minValueInArray = INT_MAX;
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Free the allocated memory. We do not need it any longer
delete [] array;
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
So, next, let’s go a little bit more into the direction C++.
We will get rid of raw pointers, new and will use the correct limit values.
#include <iostream>
#include <limits>
#include <memory>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::unique_ptr<int[]> array = std::make_unique<int[]>(arraySize);
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
A little bit better. Now we get rid of the whole manual memory allocation and use a std::vector, which is by far better. And we will use range based for loops, which will make our life simpler:
#include <iostream>
#include <limits>
#include <vector>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::vector<int> data(arraySize, 0);
// Read all values from user into the just allocated array
for (int& value : data) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (const int& value : data) {
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
And last but not least, we will get of the whole array/vector stuff. It is not needed.
#include <iostream>
#include <limits>
int main() {
// Get the number of values to check from the user and validate the input
unsigned int numberOfValues{};
if ((std::cin >> numberOfValues) and (numberOfValues > 0u)) {
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Read all values from user and check them immediately
for (unsigned int i{}; i<numberOfValues; ++i) {
// Read value and check, if OK. If not, value will be 0
int value{};
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading number of values\n\n";
}
On the third loop it will be
for(int i=0;i<n;i++)

How to use pow() function for calculating powers more than 2^32 in C++?

I wrote a simple program which is:
#include<iostream>
#include<cmath>
int main()
{
int t, n;
int count = 0;
std::cin>>t;
for(int i = 0; i < t; i++)
{
std::cin>>n;
int num = n;
while(num > 0)
{
num = num/2;
count++;
}
}
std::cout<<"\n count "<<count<<std::endl;
std::cout<<pow(2, count-1)<<std::endl;
return 0;
}
Here I want my program to work for input like
t = 1
n = 1000000000000000 (10^15)
Now when I use this input then the input buffer of program never ends(i.e to close the program we have to press ctrl + c). I guess that there is problem in the power function. So I want to know how to avoid such condition in c++.
I want to know if it is possible to calculate values of 2^32 in C++ ? either by pow() or through any other manual method.
Problem
You are using data types that do not have sufficient space to store a value that is greater than 2^32.
Solution
Use a data type that can store values that are larger than 2^32. Try using long long instead of int. How large these data types are will depend on your compiler.
#include<iostream>
#include<cmath>
int main()
{
long long t, n;
long long count = 0;
std::cin>>t;
for(long long i = 0; i < t; i++)
{
std::cin>>n;
long long num = n;
while(num > 0)
{
num = num/2;
count++;
}
}
std::cout<<"\n count "<<count<<std::endl;
std::cout<<pow(2, count-1)<<std::endl;
return 0;
}
If you do not require negative values then you can increase the maximum value a long long or int can hold by declaring them unsigned.
It works with pow and powl. There are values greater than 2^32, but you need to know that here we use mantissa:
#include <iostream>
#include <iomanip>
#include <cmath>
int main() {
using namespace std;
cout << sizeof(int) << endl;
int n = 1024 - 1;
cout << fixed << setprecision(0) << pow(2,n) << endl;
cout << sizeof(pow(2,n)) << endl;
n = 1024 * 16 - 1;
cout << fixed << setprecision(0) << powl(2,n) << endl;
cout << sizeof(powl(2,n)) << endl;
return 0;
}
Output:
4
89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112068608
8
594865747678615882542879663314003565381722343548255118736337410616630679090241843452244297736306019957557718742419654629448833690654343713137262349170782503040435817183002448761071625809765723422976172854741067923518323732415492392357140483922807069238022169202443061452643427656618079347999942895053178509060407681660390482161856378582145306703437601208682661975133940044533758686135305417823772877890396715811106725951908929815345155671925328769680324822596641589145883829482702642556778067184896640862944007954207337644916269031709617444299949490311557012560837236025936219660661599201471352670683475637369507296908449144497222586700182308964188569037205672895924286797538585218822095871944822442688842369161120304119539530699737837667369892008245871310742614507423836167988948579198667113174867405720826538879125494463015447394802338076552128630070903411513794001720975727663850799035640794798584706982804219752491585627531141013313100024021074904100001030496716840618811928940313739863536438741419219352524017082316668506692702999020350954331193650802509094131286861883139620399465858854403950870132703965488209824438934802008758845969343994044004472125629413484844182097066972890078922182473026356827727453163593714265947550139347559661748404351815218096963796346172410406417148682239343431032084521229277568266027525254094945933423431899958823773645685786750350507598779548726520016515760341759108247097818348038874055299142450671805734607137060905247538989637778322582491925031025533258542323684732018320284669732418586091676478436956021320001805809394639097855026047281380653351775920165055322550997717583813344334813881910302171240178953207677106366473378036503453544435248062525034078329626380648832032749173746330899412031156105204637292282793632423208825080061587937017363130978644540733098825776915372212354849317376813885178113563072526274562614724020074557397840679937984256404287622135935727727042447493077510397403490469607829027659582820840552983227079975738454291564860751649408292571036530740444010884909169208564698439185729787923026291571464223624851849274062647887960468225011325713624974790354101983041423775460945576066660524005986941818288912766662994426078162719667510657656067040695225510627681853951747958481562962100583938595054467627957269744108448558971634686804319537236396375558357563553198212540676776568606776445269901301489322659897550488216469545962330114439456450327105059143649149353691079858592284770257701514586653646227195894784337109820380725586800308876093495956683418516943600791035812934123566552256657548637356721364170303321445203248318052221608876405613735014581429046863850524823249770110491990966393306602127113232121844805053714961598819340772918780886767784492268026813617212138552880462432011890814832763157455453480244036737608502560568155935219962881254333016283106875208347859959837111605303362360686735617010806770356094119954850985971972173740157108951943158883889960769946088667172184453775159400416773426172185163544642073750820294724241000627118693340037228670955466887445979840508258034553074952786212905447793469416533745102450184312083150984276502843520142547725242420036764321913285201883578643256190127554977259428506738294094650002069424857941569933035773787408238363817558217731402200556355696264590285397096711343409176606399534486123848595737134078956097986897096403649443476180550440132129400660464020005964076985400565370669775001649507962489129968487179363143071990260056227184635557041873959503901703298160676708502034434721702736070337981820498702504612901752836363232547753133669634446212182280948830953449212093385245517672040199624163548955856440570085192091029300807379142100375091750164679249845932033295269830354534768690800943839523328879827294000968558885672349163214396311447169008056222766769723543731024881704573771049624407760697964694003855586008947448896853302136740492580514407729393955580489556711216778774585452721013198637847641603652665922709995374673905262003097098600295826073933596848127168932490801916573177100850314408973588759057608837176008255586173863863537610028088874109464298579173372270668553679213878959830281291941911631089480845893613059432816382467144386202929877438879934617765326964968950596805834503736177373180382300936221015689972069912183414349395106461498087096364312945860028806254674550241272982076023238962557223250366082054549672629899727845047788394343198743530974427374512431803960928917102896898594417389828136739556194292853212418189536177705143393509263700826967109944180530974835980527534343480734009517814874712043293597520502202457633238136380535255784193531700632068258618605704958229398173812474607952266968605468760232899150087704008769431156359521180518564669448293014075023298039436222182782240272844516787977851494198359872264106492071289241977002542132163865420492710010704534742706160402634260047073399438055207291585195236991244449614045909106967144147839858684971576230223513645334982033408
16
If you need accuracy for big numbers when the better way is to use BigInteger from non-standard libraries because C++ Standard Library doesn't support it.

Creating an array

write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

how to store an input into an array? C++

int b;
int array[12];
cout << "Enter binary number: ";
cin >> b;
(for example: b will be 10100)
** How to store b(10100) into an array so that it'll be [1][0][1][0][0] **
cout << array[0] << endl;
** output should be 1 **
cout << array[1] << endl;
** output should be 0 **
Please help thank you.
A string can also be treated as an array of chars. So you can get input into a string, instead, and the cout statements you wrote, should work. However, they will be chars and not ints, so you would be storing '1' and '0' instead of 1 and 0. Converting between them is easy, just use array[0]-'0'
#include <string>
#include <iostream>
using namespace std;
int main()
{
string array;
cout << "Enter binary number: "; cin >> array;
// Suppose the user inputs 10100
cout << array[0] << endl; // outputs '1'
cout << array[1] << endl; // outputs '0'
cout << array[2] << endl; // outputs '1'
return 0;
}
Update: Added compilable code. Note that this is pretty much the original code posted with the question, except for inputting a string.
I had originally wrote up an answer similar to Pablo, but seeing as he already posted it, here is one more consistent with the information given.
It takes an int input and places it into an int array.
#include <iostream>
#include <cmath>
int main( )
{
int b;
int numDigits;
// Get bit string int
std::cin >> b;
// Get the number of digits
numDigits = std::floor( std::log10( ( float )std::abs( b != 0 ? b : 1 ) ) ) + 1;
// Dynamically create a new array of the appropriate size
int* arr = new int[ numDigits ];
// Initialize all the blocks of memory
std::memset( arr, 0, numDigits );
// Fill the array
for( int i = 0; i < numDigits; i++ )
{
arr[ numDigits - i - 1 ] = b % 10;
b /= 10;
}
system( "PAUSE" );
// Delete the array
delete [] arr;
return 0;
}
This one dynamically sets the size of the array so it fits correctly.
The following example stores bits to a raw C-style array as you require. But you can replace it with a std::vector if you want.
int main()
{
// assume sizeof(int) is 32, or you can use heap-allocated array or std::vector
int array[32];
unsigned int mask = 1;
// mask is initially 0x80000000
mask = mask << (sizeof(int)*8 - 1);
int i = 0;
// we start counting from the first "1",
// preceding "0"s are ignored to display
bool started = false;
int b;
cin >> b;
while (mask != 0)
{
// if current bit is "1" or "0"
if (mask & b)
{
started = true;
array[i++] = 1;
}
// if current bit is "0" and counting started
else if (started)
{
array[i++] = 0;
}
// ready to test next bit
mask = mask >> 1;
}
// test result
for (int j = 0; j < i; ++j) cout << array[j];
cout << endl;
return 0;
}
Test cases:
1. b = 8 => array: 1000
2. b = -8 => array: 11111111111111111111111111111000
3. ..
You can use boots dynamic bitset
#include "boost/dynamic_bitset.hpp"
#include <sstream>
#include <iostream>
int main()
{
boost::dynamic_bitset<> val;
std::stringstream input("1010101010");
input >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}
If you don't have boost use the std::bitset.
The only problem with std::bitset it has a fixed size
#include <bitset>
#include <sstream>
#include <iostream>
int main()
{
std::bitset<16> val; // fixed 16 bit size
std::cout << "Enter binary number:\n";
std::cin >> val; // Input a binary number
// Can use std::cin or another stream
std::cout << val.to_ulong() << "\n";
std::cout << val[5] << "\n";
}
STORING A BINARY NUMBER INTO AN ARRAY
char binaryArray [5]; // The array looks like this: [][][][][]
cout << "Enter binary number: ";
cin >> binaryArray; // Stores the binary number into the array: [1][0][1][0][0]
cout << binaryArray[0] << endl; // The first element is sent to standard output.
cout << binaryArray[1] << endl; // The second element is sent to standard output.
For your input the output will be:
1
0
Here we have an array of characters. We input the binary number into the array and then we print each element of the array to display each bit. The first print line accesses the first element [1] [0] [1] [0] [0]. The second print line accesses the second element [1] [0] [1] [0] [0].
Let's say we had a binary number with 100 characters. The way that we output each element of the array would take a long time.
1.) Can you think of a more efficient way of printing out the contents of our array?
2.) How can we ensure that the user is inputting only ones and/or zeroes?