display numbers in following order using "For Loop" - c++

a program that display the following output using "For Loop":
2 4 8 16 32 64 128 256 512 1024
#include <iostream>
using namespace std;
int main()
{
int n ;
for(n=1;n<=2048;n++){
n=n*2;
cout<<"\t"<<n<<endl;
}
return 0;
]

Due to the n++ in the for loop, n is incremented each iteration. Additionally, it is multiplied by 2 at the beginning of each iteration. What you need to do is either change the increment statement in the for loop to transform n how you want:
for (n = 2; n <= 1024; n *= 2) {
cout << "\t" << n << endl;
}
or use a separate loop variable to perform a set number of iterations:
int n = 1;
for (int i = 0; i < 10; i++) {
n *= 2;
cout << "\t" << n << endl;
}

use pow function of c++
#include <math.h>
int s=1;
for(i=1;i<=5;i++)
{
s=Math.pow(2, i);
cout<<s<<"\n";
}
also include math header library

As jcarpenter pointed out, your mistake is incrementing n in your for-loop in addition to n=n*2 (which can be written as n *= 2 BTW). So I've cutted the increment and moved the double operation to the loops head. Fortunatly, multiplying a number with 2 can be implemented very effiecently with a shift operation. So that's the code I would suggest:
#include <iostream>
int main(void)
{
for(int n = 2; n <= 1024; n <<= 1)
{
std::cout << n << std::endl;
}
}

Related

How do I convert a number into an 8-bit binary rather than 4-bit

void decimaltobin()
{
binaryNum = 0;
m = 1;
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * m;
m *= 10;
}
}
Just wondering if there was an easy fix to get this function to print an 8-bit binary number instead of a 4-bit number, e.g. 0000 0101 instead of 0101.
As mentioned in the comments, your code does not print anything yet and the data type of binaryNum is not clear. Here is a working solution.
#include <iostream>
using namespace std;
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing the required number of zeros
int zeros = 8 - i;
for(int m = 0; m < zeros; m++){
cout<<0;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
The code implements the following:
Store the remainder when the number is divided by 2 in an array.
Divide the number by 2
Repeat the above two steps until the number is greater than zero.
Print the required number of zeros. That is 8 - length of the binary number. Note that this code will work for numbers that can be expressed in 8 bits only.
Print the array in reverse order now
Ref
Maybe I am missing your reason but why do you want to code from scratch instead of using a standard library?
You may use standard c++ without having to code a conversion from scratch using for instance std::bitset<NB_OF_BITS>.
Here is a simple example:
#include <iostream>
#include <bitset>
std::bitset<8> decimalToBin(int numberToConvert)
{
return std::bitset<8>(numberToConvert);
}
int main() {
int a = 4, b=8, c=12;
std::cout << decimalToBin(a)<< std::endl;
std::cout << decimalToBin(b)<< std::endl;
std::cout << decimalToBin(c)<< std::endl;
}
It outputs:
00000100
00001000
00001100

Pascal's Triangle fails past row 14

I have to write a program that outputs Pascal's triangle for a computer science class, and everything is correct on the output until it gets past row 14, wherein it starts outputting odd irrational numbers. Here's my code
#include <iostream>
#include "myFunctions.h"
using namespace std;
int main() {
int rows;
cout << "Please Enter The Number of Rows: ";
cin >> rows;
cout << rows << endl;
for (int i = 0; i < rows; i++) {
for (int j = 1; j < (rows - i + 1); j++) {
cout << " ";
}
for (int k = 0; k <= i; k++) {
if (k == 0) {
cout << "1" << " ";
} else {
cout << combination(i, k) << " ";
}
}
cout << "\n";
}
return 0;
}
And here's my functions file:
#ifndef MYFUNCTIONS_CPP_INCLUDED
#define MYFUNCTIONS_CPP_INCLUDED
#include "myFunctions.h"
double factorial (int n) {
assert(n >= 0);
int v = 1;
while (n > 0) {
v *= n;
n--;
}
return v;
}
double combination (int a, int b) {
return (factorial(a) / (factorial(a - b) * factorial(b)));
}
#endif // MYFUNCTIONS_CPP_INCLUDED
And, finally, here's my header file.
#ifndef MYFUNCTIONS_H_INCLUDED
#define MYFUNCTIONS_H_INCLUDED
#include <iostream>
#include <cassert>
//*******************************************************
// description: finds factorial of value *
// return: double *
// precondition: that the value is valid and an integer *
// postcondition: returns the factorial of value *
//*******************************************************
double factorial( int n );
//********************************************************
// description: finds combination of value *
// return: double *
// precondition: both values are integers and valid *
// postcondition: returns the combination of two values *
//********************************************************
double combination( int a, int b );
#endif // MYFUNCTIONS_H_INCLUDED
I'm assuming that I did the equations within functions incorrect, or something specific is happening in main once it hits 14. Any help is appreciated.
What's going on
ints in C++ have a maximum size. As mentioned in comments, depends on your platform but for the sake of this question, I'll assume it's 2^31-1 which corresponds to a 32-bit signed integer and is what I most commonly see.
The issue comes in when you get to factorials. They grow very quickly. 14!=87178291200 which is a whole lot bigger than the maximum size of a 32 bit int. There's no feasible way to keep the whole factorial in memory for an arbitrary n! because of how large they can get.
It's not that your code is broken, it's simply running up against the physical bounds of computing.
How can we fix it?
First off, you could cancel out factorials. Basically, since we can guarantee that a>=b, we know that a!/b! is just multiplying the numbers between a and b. We can do that with a loop. Then it's just a matter of dividing by (a-b)!, which we already know how to do. This would look like
int combination(int a, int b)
{
int tmp = 1;
for(int ii = b;ii<=a;ii++)
tmp*=ii;
tmp /= factorial(b);
return tmp;
}
More efficiently, we can switch to a different algorithm. Wikipedia recommends using an iterative method for pascal's triangle. That is, each element can be calculated from two elements in the row above it. As #Damien mentions in comments, if you're looking for the kth element in row n, then you can calculate that by
int Combination(int n,int k)
{
if (k == 0 or k>n or n <= 1)
return 1;
return Combination(n-1,k) + Combination(n-1,k-1);
}

Program not loading array correctly

Question at hand: Write a function primeTableInRange to generate a table to show whether each number in the range from startNum up to endNum is a prime number. When the number is not a prime number, we will only show a ‘*’. When the number is a prime number, we will show the number.
My code:
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum;
int userarray[arraysize];
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<arraysize;i++)
{
bool prime=true;
for (int r=2;r*r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
Issue is it doesn't start at "startNum" and doesn't end at "endNum". It actually goes from 0 to arraysize. Also it calculates 4 as a prime number. What am I missing here?
Be careful! Arrays always start at 0 and end at arraysize in your case. You cannot have arbitrary indexing. You could do the following:
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=0;i<arraysize;i++)
userarray[i]= startNum+i;
Also, since we start at 0 you need to add +1 in ´arraysize´ to include ´endNum´ in your ´userarray´
try to change this
from:
for (int r=2;r*r<i;r++)
to
for (int r=2;r<i;r++)
At nowhere in your printing function do you even recognize your array. You simply begin looping numbers up to your array size. If you took the array out of your function arguments it would still work, so why are you including it? Your for loops just disregard any values in your array and begin looping from 2 arbitrarily.
As for why 4 is calculated as a prime number, it is because when your second loop starts it sees that 2*2=4 and therefore not less than 4, which is the number you are testing. This results in it skipping over the loop and never setting prime to false. Make the condition in the second for loop to <= or else any perfect square with no other factors will be labelled as prime, such as 25.
Also on a side note, how did this ever compile? You use a dynaimc variable to initiate an array size. That doesn't work and when I tried to run your code to see the output I got errors. Try using std::vector<int>. When you use the for loop to fill the vector you use the values as indexes which is completely and utterly wrong. This is when you should loop from zero to your arraysize because that it the address within the array. You also include unecessary headers like ctime and cmath, and have if(true) in your code for no reason.
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=startNum;i<endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<=arraysize;i++)
{
bool prime=true;
for (int r=2;r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
The declaration for the array (int userarray[arraysize];) is illegal, the array bounds need to be known at compile time. This should not even compile, or it produces a zero-size array.
Afterwards, you randomly access unallocated memory, whcih is UB
Change
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
To
int userarray[1];
int arraysize = endNum - startNum;
userarray[arraysize];
Also, add a return value to the primetableinarray function.
Here is the correct program .
#include <iostream>
using namespace std;
void primetableinarray(int low, int high) ;
int main()
{
int low, high, i, flag;
cout<< "Enter low numbers ";
cin>> low;
cout<< "Enter high numbers ";
cin>>high;
cout<< "Prime numbers between " << low << "and are: " << high <<endl;;
primetableinarray(low, high);
return 0;
}
void primetableinarray(int low, int high) {
int i, flag;
while (low <= high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout<< low <<endl;
else
cout<< "*" <<endl;
++low;
}
}
Output :
Enter low numbers 1
Enter high numbers 10
Prime numbers between 1and are: 10
1
2
3
*
5
*
7
*
*
*
There are copule of problem in your code :
int arraysize = endNum - startNum;
int userarray[arraysize];
How does it compile , it will be compilation error. you can allocate memory dynamically and use it .
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
this is wrong i = startNum and arraysize = arraysize +1 if you are comparing " i<=endNum " .
Correct way is :
for (int i=0;i<=endNum;i++)
userarray[i]= startNum++;

C++ Random Number Generator in Array

I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:
Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568
I couldn't figure out why the last number ignores my rule.
Any help would be appreciated.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 6; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
I couldn't figure out why the last number ignores my rule.
Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be
for (int i = 0; i < 5; i++)
~
Then i will be 0 ~ 4, loop 5 times, not 6 times as your code shown.
You might use range-based for loop (since C++11) to avoid such kind of mistake:
for (auto& i : myArray) {
i = (rand() % 55) + 1;
cout << i << '\t';
}
random numbers from 1 to 54
So this is incorrect as well: (rand() % 55) + 1;
You'll need (rand() % 54) + 1;
Because you went to myArray[5] at the last time and your array don't have this place so you got it
you need to write like that:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 5; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
If you want 6 items you need to make a array for six items
int myArray[5];
this will provide 5 items where as
int myArray[6];
this will provide you 6 items
This will fix your problem

Computing Combinations on basis of number of bits set

I need to compute all possible combinations of n things selected r at a time where 0<=r<=n, One method to do so is generating the numbers up to 0 to 2^n-1. But I need to generate these numbers such that the numbers should be sorted on the basis of the number of bits set in that number. for n=3:
0 // numbers with 0 bits set
1 2 4 // numbers with 1 bits set
3 5 6 // numbers with 2 bits set
7 // numbers with 3 bits set
I need to know how to generate the numbers such that they are sorted in increasing/decreasing order of bits set?
Implement regular algorithm to generate the combinations, but also hold an additional array where you store the numbers sorted accoding to the 1-bits set. Then for each combination generated replace the numbers with the numbers sitting in the corresponding position minus one in the array sorted as I described.
Iterating over all combinations of some some number of items is covered nicely by quant_dev here.
Here is a simple way function that counts the number of bits set in a number's representation:
// Counts how many bits are set in the representation of the input number n
int numOfBitsSet(int n)
{
int cnt = 0;
while (n != 0)
{
cnt += (n & 1);
n = n >> 1;
}
return cnt;
}
And here is how you could use it in a (C++11) program that does what you want:
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
// For instance...
int n = 3;
// Fill up a vector of 2^n entries (0 .. 2^(n - 1))
vector<int> v(1 << n);
iota(begin(v), end(v), 0);
// For each number of bits...
for (size_t i = 0; i <= n; i++)
{
cout << "Numbers with " << i << " bits set: ";
// Find the first number with i bits set...
auto it = find_if(begin(v), end(v), [i] (int x) {
return (numOfBitsSet(x) == i);
});
while (it != end(v))
{
cout << *it << " ";
// Find the next number with i bits set...
it = find_if(next(it), end(v), [i] (int x) {
return (numOfBitsSet(x) == i);
});
}
cout << endl;
}
}
If C++11 is not an option for you, you will have to use functors instead of lambdas, and replace std::iota with a manual loop:
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
struct bit_count_filter
{
bit_count_filter(int i) : _i(i) { }
bool operator () (int x) const { return numOfBitsSet(x) == _i; }
int _i;
};
int main()
{
// For instance...
int n = 3;
// Fill up a vector of 2^n entries (0 .. 2^(n - 1))
vector<int> v(1 << n);
for (size_t i = 0; i < v.size(); i++)
{
v[i] = i;
}
// For each number of bits...
for (size_t i = 0; i <= n; i++)
{
cout << "Numbers with " << i << " bits set: ";
// Find the first number with i bits set...
auto it = find_if(begin(v), end(v), bit_count_filter(i));
while (it != end(v))
{
cout << *it << " ";
// Find the next number with i bits set...
it = find_if(next(it), end(v), bit_count_filter(i));
}
cout << endl;
}
}
You could do it recursively:
void setnbits(unsigned int cur, int n, int toset, int max)
{
if(toset == 0)
{
printf("%d ", cur >> (n + 32 - max) , n);
return;
}
toset--;
for(int i = 1 ; i <= n-toset ; i++)
{
setnbits((cur >> i) | 0x80000000, n-i, toset , max);
}
}
Could be called like:
for(int z = 0 ; z < 4 ; z++)
{
printf("%d bits: ", z);
setnbits(0, 3, z, 3);
printf("\n");
}
prints:
0 bits: 0
1 bits: 1 2 4
2 bits: 3 5 6
3 bits: 7
The numbers are not guaranteed to be in numerical order.
That's pretty easy.
There are two cases:
1) Last 1-bit has 0-bit before:
000111001001 -> 000111001010.
You should just move it to the left
2) There is a chain of 1-bits:
000110111100 -> 000111000111
Then you should move last 1-bit to the nearest 0-bit on the left(before the chain), and move all another bits of that chain to the right.
You'll get this way all needed numbers in increasing order.