#include <iostream>
#include <cmath>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
int arr[5];
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = (value % (exponential *10)) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
In this code here;
I had to write:
int arr[5];
But I wanted the size of this array to be a variable so that its size could be defined and its values could be put by for loop so its size could be equal to the amount of loop.
I wanted to write like this:
for (int i = 0; i <= digitNumber - 1; i++)
{
int arr[i];
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = (value % (exponential *10)) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
Visual Studio says that the value that the array takes as length must be constant that's why you can't determine it by loops etc.
Is there a way to put a variable as size in an array and assign an array's size by a loop in C++?
You probably want something like this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
std::vector<int> arr(digitNumber); // initialize a vector containing
// digitNumber elements
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = value % (exponential * 10) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
// printf values in arr
cout << "arr: ";
for (auto& value : arr)
cout << value << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
But this is a rather convoluted way to decompose a number into it's digits. You don't need floating point arithmetic at all to do this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
std::vector<int> arr; // start off with an empty vector
for (int i = 0; value != 0; i++)
{
arr.push_back(value % 10); // add to the vector
value /= 10;
}
// printf values in arr
cout << "arr: ";
for (auto& value : arr)
cout << value << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
If you want to avoid using vector, you can use this:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool narcissistic(int value)
{
cout << "value is:" << value << endl;
int digitNumber = (log10(value) + 1);
cout << "Digit Number:" << digitNumber << endl;
int sum = 0;
vector<int> v(digitNumber);
int *arr = &v[0];
for (int i = 0; i <= digitNumber - 1; i++)
{
cout << "i digit:" << i << endl;
int exponential = pow(10, i);
arr[i] = value % (exponential * 10) / pow(10, i);
cout << arr[i] << endl;
sum += pow(arr[i], digitNumber);
cout << pow(arr[i], digitNumber) << endl;
cout << i << "'th sum value:" << sum << endl;
}
// print values in arr
cout << "arr: ";
for (int i = 0; i <= digitNumber - 1; i++)
cout << arr[i] << ", ";
return true;
}
int main() {
int value = 153;
narcissistic(value);
return 0;
}
Related
I am trying to subtract the initial value that I gave my code from the sum and then have that sum be subtracted by the initial value - 1. For example, my number is 4 so 0+1+2+3+4= 10 and then have 4 subtract from 10 to get 6, then 6 subtracted by 3 to get 3, and so on. I'm extremely new to c++ and I just need a nudge in the right direction.
#include <iostream>
using namespace std;
int a;
int b = 0;
int c = 0;
int sum = 0;
void main() {
cout << "Please give me a number" << endl;
cin >> a;
do {
if (a <= 0) {
cout << "Incorrect number. The input must be positive" << endl;
cin >> a;
}
} while (a <= b);
for (int i = 0; i <= a; i++) {
cout << i;
cout << "+";
sum += i;
}
cout << endl;
cout << "All numbers from 0 to " << a << " is " << sum << endl;
cout << "Starting with the sum of " << sum << endl;
while (a > 0) {
c = sum - a;
cout << "After subtracting " << a << ", I got the number " << c << endl;
a--;
}
#include <iostream>
using namespace std;
int a;
int b = 0;
int c = 0;
int sum = 0;
int main() {
cout << "Please give me a number" << endl;
cin >> a;
do {
if (a <= 0) {
cout << "Incorrect number. The input must be positive" << endl;
cin >> a;
}
} while (a <= b);
for (int i = 0; i <= a; i++) {
cout << i;
cout << "+";
sum += i;
}
cout << endl;
cout << "All numbers from 0 to " << a << " is " << sum << endl;
cout << "Starting with the sum of " << sum << endl;
c = sum; /*Initialize c */
while (a > 0) {
c = c - a;
cout << "After subtracting " << a << ", I got the number " << c << endl;
a--;
}
return 0;
}
#include <iostream>
using namespace std;
int a;
int sum = 0;
int main() {
cin>>a;
while(a<=0){
cin>>a;
}
for(int i = 0; i <= a; i++){ cout<<i; cout<<"+"; sum+=i;}
while(a > 0){
sum-=(a--);
}
}
I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.
I'm working on an assignment for school. The code is supposed to read form a file and create an array, then sort the values of the array to output certain info. It works just fine as long as I have 3+ lines of info in the file. If not, I get the following error:
First-chance exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
Unhandled exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
I can't figure out why, any help would be appreciated. Here's the code:
#include <iostream> //calls the information needed
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std; //sets all unmarked commands to std::
const int ARRSIZE = 1000;
struct Student
{
string firstName;
string lastName;
string id, temp;
double gpa;
};
int readArray(ifstream& ifile, Student arr[]);
void swapElements(Student arr[], int i, int j);
void sortArray(Student arr[], int numberInTheArray);
int main()
{ // Declares the needed variables
double sought, min, max;
int i, ival, returnvar, count = 0, mincount, maxcount;
string filename;
ifstream ifile;
Student arr[ARRSIZE];
cout << "Input File Name: ";//requesting the file name
cin >> filename;
ifile.open(filename.c_str());//opening the file
if (!ifile)//checking if it opened or not
{
cout << endl << "That file does not exist!" << endl;//informing the user it did
return 1;//not open and returning 1
}
cout << "Which number do you want to return? ";//requesting the desired number
cin >> ival;
i = ival - 1;
cout << endl;
returnvar = readArray(ifile, arr);
min = arr[0].gpa;
max = arr[0].gpa;
sought = arr[0].gpa;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
if (count == 0)
{
cout << "The file is empty!" << endl;
return 1;
}
cout << "Before Sort:" << endl;
cout << " Min GPA is " << min << " for " << arr[mincount].lastName << "." << endl;
cout << " Max GPA is " << max << " for " << arr[maxcount].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sortArray(arr, returnvar);
count = 0;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
cout << "After Sort:" << endl;
cout << " Array[0] GPA is " << min << " for " << arr[0].lastName << "." << endl;
cout << " Array[" << (returnvar - 1) << "] GPA is " << max << " for " << arr[(returnvar - 1)].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
return 0;
}
int readArray(ifstream& ifile, Student arr[])
{
int counter = 0;
while ((ifile) && (counter <= ARRSIZE))
{
ifile >> arr[counter].firstName;
ifile >> arr[counter].lastName;
ifile >> arr[counter].id;
ifile >> arr[counter].gpa;
counter++;
}
return (counter - 1);
}
void sortArray(Student arr[], int numberInTheArray)
{
for (int i = 0 ; i < numberInTheArray - 1; i++)
{
for (int j = 0 ; j < numberInTheArray - 1; j++)
{
if ( arr[j].gpa > arr[j + 1].gpa)
{
swapElements(arr, j, j+1);
}
}
}
}
void swapElements(Student arr[], int i, int j)
{
Student temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Please ignore the insanity and comments. Like I said, for an entry level course.
Try replacing counter <= ARRSIZE with counter < ARRSIZE (a rule of thumb in C is: never use <= in operations related to container sizes).
EDIT: also in your main(), you must check that i < ARRSIZE (equivalently, return error if i >= ARRSIZE). At present you seem to accept the case i == ARRSIZE, which is also wrong. And finally, readArray should return counter (that is, one more than the last written index).
This C++ program asks the user to enter the length of the bit sequence he/she will enter next. This length variable is named xx, it is of type int. I am using three dynamic bitset with the initial size of 5, these are inpSeq, operSeq and bit. I am resizing the bitsets by
inpSeq.resize(xx); for example. When compiling the program, a very big list of errors appears, I feel I can't paste it here. but I am sure that these errors are all related to this variable xx, the code was compiled fine before using it as a variable to resize the bitset. What is wrong with the way I am resizing the bitset? And can I make the bitsets of the size of inpSeq without asking the user to enter the length of inpSeq bitset?
#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;
boost::dynamic_bitset<> inpSeq(5);
int polyLoc;
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;
}
cout << "xorArray is: ";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << " ";
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
cout << "x is: " << x << "\n";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << "\n";
}
cout << "bit 3 of initial " << bit[seq_end] << "\n";
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 << "--\n";
}
while ((operSeq != inpSeq) && (turnCount < 20));
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";
}
}
cin.get();
}
This question already has answers here:
Define bitset size at initialization?
(7 answers)
Closed 5 years ago.
I have a working 4 bit linear feedback shift register, using 3 bitsets of length 4: inpSeq, operSeq and bit. I want to make the program accept a variable length bit sequence, so those previous bitsets should be of variable length somehow. The user may enter a sequence ofr inpSeq and the program sets the three bitsets to be of the same length as that sequence provided by the user. Any ideas for how to achieve this? Sample code if I may ask!
Here is the code:
#include <iostream> //Standard library.
#include <bitset> //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;
bitset <4> inpSeq;
int polyLoc;
bitset <4> operSeq;
bitset <4> bit;
vector <int> xorArray;
vector <int> keyReg;
cout << "Enter a 4-bit sequence: \n";
cin >> inpSeq;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
cout << "xorArray is: ";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << " ";
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
cout << "x is: " << x << "\n";
for ( unsigned int i = 0; i < xorArray.size(); i++)
{
cout << xorArray[i] << "\n";
}
cout << "bit 3 of initial " << bit[3] << "\n";
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[3] = operSeq[x];
cout << "bit 3 from prev: " << bit[3] << "\n";
y = xorArray[r];
cout << "opseq[y] is: " << operSeq[y] << "\n";
bit[3] = bit[3] ^ operSeq[y];
cout << "bit[3] after xor: " << bit[3] << "\n";
}
operSeq >>= 1;
cout <<"operSeq after shift: " << operSeq << "\n";
operSeq[3] = bit[3];
cout <<"opserSeq bit 4 after = bit[3]: " << operSeq[3] << "\n";
cout <<"new operSeq: " << operSeq << "\n";
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << "--\n";
}
while ((operSeq != inpSeq) && (turnCount < 20));
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";
}
}
cin.get();
}
std::vector has an optimization for std::vector<bool>, and the size of a vector can be set at runtime.