C++ Nested for loop for exponents with set base/exponent - c++

So I need some help with this. I want to print out all integers between 2 and 2^20 that are integer powers of 2. I figured out that I need to increase the power by 1 each time but I can't seem to figure out what goes inside the inner for loop. I cannot use the pow() function
c = 2;
cout << "\nPROBLEM C" << endl;
for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent
{
cout << setw(5) << powerC << " ";
counterC++;
for (int x = 1; x <= 20; x++) // where I am having trouble with
{
c = (c*powerC);
cout << setw(5) << c;
} // end inner for loop
if (counterC % 8 == 0)
{
cout << endl;
}
}
cout << "\nNumber of numbers = " << counterC;

This is much simpler by using the << operator.
Since 2 is 2^1, you want to print all integers from 2^1 to 2^20 inclusively, or 20 numbers:
int c = 2;
for (int i=0; i<20; i++)
{
std::cout << c << std::endl;
c <<= 1;
}

Related

How to call a function to search an element an a 2D array?

I'm trying to get my homework done, but there is something is going wrong.
If a 2D array was in the main function, and I want to call a function, which its task is searching for an element in the 2D array, which the user enters the wanted element in the main function. If the wanted element was found, call a function to find its factorial then print the result in the main function, otherwise, call another function to show that the wanted element was not found.
I've tried the lines of code using Visual Studio 2019 as well as Dev C++.
My program does about 13 tasks which I organized them in a Switch Statement,
and the case of doing that task is Case number 9.
But once I enter the element I want to search in the console.
if the element existed in the array, the output always shows up like this:
"
Number 3 Found at position: 4
Factorial of 3 is: 6
3
"
whether the user entered 3 or else number.
Even if it was not found, the output is the same.
#include <iostream>
using namespace std;
// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);
// declaring a function to find the fatorial of the found element.
int fact_num(int);
// declaring a function to print out a searching error.
void search_error();
// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;
cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}
/**********************************************************************/
// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}
if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/
I expected the output of searching will be like this:
Example:
If the user entered the elements of the array as '1 2 3 4 5 6 7 8 9' and searched about the element '9'
IF THE WANTED ELEMENTS WAS FOUND:
the output will be :
"Number 9 Found at position: 4
Factorial of 9 is: 362880"
IF THE WANTED ELEMENTS WAS NOT FOUND:
the output will be :
"The wanted number was not Found in the array!"
You have undefined behaviour filling and searching the array
for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element
Array indices start from 0. If you want to display indices from 1, do arithmetic in the output
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

cout cutting off beginning of string in for loop

I have a double for loop going through a two-dimensional array of object classes, and there is supposed to be a repeated message every time it loops to give specific information, but the strings that are the same every time keep getting cut off at the front more each time it loops. What is the reason why it keeps doing this? I have never had this problem before while using C++.
System systems[29][119];
string ds[29][119];
int sx = 0;
int sy = 0;
for (int i = 0; i < 29; i++) {
for (int o = 0; o < 119; o++) {
int which = rand() % 4 + 1;
system("cls");
cout << "X: " + o << endl << "Y: " + i << endl << endl;
if (which == 1) {
systems[i][o] = genSystem(o, i);
cout << "ID: " + systems[i][o].id << endl
<< "Num Planets: " + systems[i][o].numPlanets << endl;
system("pause >nul");
}
else {
systems[i][o] = genSystem(o, i, false);
cout << "NO SYSTEM" << endl;
system("pause >nul");
}
}
}
You’re adding numbers to string literals (which represent arrrays), which ultimately boils down to pointer arithmetic.
It does not "stringify" the numbers and concatenate them as it would in some other languages.
"Hello" + 1 —> "ello"
"Hello" + 2 —> "llo"
And so on.
Use << instead of +.
You can separate your numbers in cout by << instead of using the arithmetic operator + to add an offset.

How can I get the array to show the previous list of array content before the next input?

I need the user input to be saved into my array and then output the array before the user inputs the next time. I have been moving things around different ways but cannot seem to get them to perform properly. I tried to cut down the code to the two functions I am having issues with.
void PlayGame()
{
const int HighestNum = 50;
const int LowestNum = 1;
int RandomNumber = LowestNum + rand() % HighestNum; //set for better random results
cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n";
const int attempts = 15;// limits the attempts to guess the random number to 15
int Guess [attempts] = {};
cout << "Enter your guess " << endl;
for (int count = 0; count < attempts; count++)
{
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the results
switch (r)//switch statement for function results, letting the user know if they matched the number, if the number is higher, or lower
{
case 0:
cout << "You Win!!" << endl;
cout << "\n";
cin.get();
return;
case 1:
cout << "The number is higher than your guess" << endl;
break;
case -1:
cout << "The number is lower than your guess" <<endl;
break;
}
if (count == 15)
{
cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts
cout << "\n";
cin.get();
Again();
}
}
return;
}
int DisplayGuess(int member[])
{
for(int i = 0; i < 15; ++i)
cout << "\nGuess " << i + 1 << ": " << member[i];
cout << endl;
return;
}
Try this inside your loop
if(count > 0)
{
for (int j= 0; j < count; j++)
{
cout<<Guess[j];
}
}
Call DisplayGuess() in the first line of the for loop. Since the first you time you call it your array is empty, it shouldn't output anything.
So,
for (int count = 0; count < attempts; count++)
{
DisplayGuess(Guess[count]);
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the
results
. . . . . .

Converting the bits of a vector to a decimal integer

I am trying to convert the bits of a vector into a decimal integer. My program is a variable linear feedback shift register. At first it asks the user for the length of the initial sequence of the LFSR, then it asks for the sequence itself and the position of the bits to be xored. So if I entered 4 for the length of the sequence, 1110 for the bit sequence and 20 for polynomial, the key is 0111100, it is stored in a vector keyReg, I tried converting it into a decimal number by using a for condition:
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
But that is not producing the correct decimal equivalent to 0111100. What to do?
Here is the full program:
#include <iostream> //Standard library.
#include <boost/dynamic_bitset.hpp> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
int polyLoc;
int key = 0;
boost::dynamic_bitset<> inpSeq(5);
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
cout << "What is the legnth of the sequence?";
cin >> xx;
inpSeq.resize(xx);
operSeq.resize(xx);
bit.resize(xx);
cout << "Enter a bit sequence: \n";
cin >> inpSeq;
int seq_end = inpSeq.size() - 1;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end] ^ operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << operSeq << "\n";
}
while ((operSeq != inpSeq) && (turnCount < 1024));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for ( unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if ( keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
cout << "Key is " << key << "\n";
cin.get();
}
I think you meant:
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(1 << i); // this is 2^i
cout << key << "\n";
}
}
^ is a bitwise operator for XOR so the code was "valid" from the compiler's point of view.
Why it works:
I cannot find a relevant question but "(1 << i)" was explained somewhere else. 1 is treated as an integer. Then operator<< on integer is a bitwise left shift (by i places).
So it makes 000001 and shifts it left, e.g. when i is 3 it produces 001000. Effectively producing 2^i integer.
Of course one could use something more explicit, however std::pow is defined only for floating point types, so one would need to use some conversions.
(1 << i) also poses some safety concerns. You need to take care of the type of the values you use for shifting (their size), and value you use for shifting, writing (1<<128) might give some unexpected results. Anyway it is the best way to get 2^i for most cases IMO.

add results of a for loop after each iteration

I‘m having trouble with my for loop. I have a basic 2 times table that goes up from 1 to 10. (see below). I'm trying to add the result so that after every loop, allResult displays the values of all results added. it needs to show all results added after every loop. and I don't know how to go about it. A better description is the desired outcome commented in the code.
my Code...
int main(){
int allResult;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << 2 << " times " << i << " = " << result << endl;
// I want allResult to store results added. so after first loop, result = 2 so allResult = 2
// after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added)
// after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added)
// I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2.
}
system("pause");
}
int allResult = 0;
for( int i = 1; i < 11; i++)
{
allResult += 2*i;
cout << 2 << " times " << i << " = " << 2*i << endl;
}
int allResult = 0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
cout << "2 times " << i << " = " << result << endl;
allResult += result;
cout << "allResult: " << allResult << endl;
}
int main()
{
int allResult=0;
for( int i = 1; i < 11; i++)
{
int result = 2*i;
allResult=allResult+result;
/*Initially allResult is 0. After each loop iteration it adds to its previous
value. For instance in the first loop it was allResult=0+2,
which made allResult equal to 2. In the next loop allResult=2+4=6.
Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/
cout << 2 << " times " << i << " = " << result << endl;
}
system("pause");
}