C++ Placing Random Values In A Multiplication Chart (Nested Loop) - c++

I created a multiplication table for the integers 1...10. Here is the code:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
std::cout << "\t" << i * j;
}
std::cout << std::endl;
}
And my output is this:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The problem I am struggling with is that I need to insert a random number that represents an error value inside the multiplication table. For example:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 13 15 18 21 24 27 30
As you can see in this example, the error value is 13 where 3 x 4 = 12, but instead there is the number 13.
Should I use another loop to insert the random number? If so, how to go about it?

You can use <random> header file for this.
std::random_device rd;
std::mt19937 gen(rd());
// it produces uniformly distributed random integers in the range [a, b] (both inclusive)
std::uniform_int_distribution<> dis(0, 1); // either add 0 or 1 (1 will be the error -- can change a,b according to your need)
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
std::cout << "\t" << i * j + dis(gen); // just add the error value to your multiplication
}
std::cout << std::endl;
}

#include <iostream> // input/output
#include <random>
struct FieldData {
using Row = unsigned int;
using Col = unsigned int;
const Row rows{10};
const Col cols{10};
Row err_row;
Col err_col;
unsigned int err_value;
FieldData() {} // use default values for rows/cols
FieldData(Row max_row, Col max_col) : rows(std::move(max_row)), cols(std::move(max_col)) {} // use given values for rows/cols
};
void print_field(const FieldData& data)
{
for (FieldData::Row row=1;row <= data.rows; row++)
{
for (FieldData::Col col = 1; col <= data.cols; col++)
{
if (row == data.err_row && col == data.err_col)
std::cout << "\t" << data.err_value;
else
std::cout << "\t" << row*col;
}
std::cout << std::endl;
}
}
FieldData get_field(std::mt19937& generator)
{
FieldData data;
std::uniform_int_distribution<FieldData::Row> dist_rows(1, data.rows); // random for row
std::uniform_int_distribution<FieldData::Row> dist_cols(1, data.cols); // random for col
std::uniform_int_distribution<FieldData::Row> dist_result(1, data.rows*data.cols); // random for result
data.err_row = dist_rows(generator);
data.err_col = dist_cols(generator);
data.err_value = dist_result(generator);
if (data.err_value != data.err_row*data.err_col)
data.err_value--; // avoid correct value on error pos
return data;
}
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
while (true)
{
auto field = get_field(generator);
print_field(field);
// some code to ask the user and so on.... (std::cin ...)
std::cout << "Error value '" << field.err_value << "' is on row " << field.err_row << ", col " << field.err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
As requested by the questioner, a version without further constructs:
#include <iostream> // input/output
#include <random>
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
unsigned int rows = 10;
unsigned int cols = 10;
std::uniform_int_distribution<unsigned int> dist_rows(1, rows); // random for row (1 to value of field_rows)
std::uniform_int_distribution<unsigned int> dist_cols(1, cols); // random for col (1 to value of field_cols)
std::uniform_int_distribution<unsigned int> dist_result(1, rows * cols); // random for result
while (true) // infinite loop - must be interrupted explicitly with break or similar
{
unsigned int err_row = dist_rows(generator); // Generate the random number that defines the row
unsigned int err_col = dist_cols(generator); // Generate the random number that defines the col
unsigned int err_value = dist_result(generator); // Generate the random value
if (err_value != err_row * err_col)
err_value--; // avoid correct value on error position - simple decrement the value
// print_field
for (unsigned int row = 1; row <= rows; row++)
{
for (unsigned int col = 1; col <= cols; col++)
{
if (row == err_row && col == err_col) // condition to insert the error value
std::cout << "\t" << err_value;
else
std::cout << "\t" << row * col;
}
std::cout << std::endl;
}
//
// some code to ask the user and so on.... (std::cin ...)
//
std::cout << "Error value '" << err_value << "' is on row " << err_row << ", col " << err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
I hope this answer helps you, I have separated the different parts a little bit to make it more clearly arranged for you. The code should at least give you a rough idea how something like this could be implemented. Depending on the use case, a separate class or something similar would of course be appropriate.
The code in the second variant differs from the functionality only in that the uniform_int_distributions are outside the while(true) scope and thus are not always "rebuilt" as is the case in the first variant (since more dynamic and modularity would have been possible in principle).

Should I use another loop to insert the random number? If so, how to go about it?
You're only inserting one error, so it doesn't make much sense to a loop for that.
Well, why don't you first decide where the random number goes? Once you know that, you can modify the inner loop body, as follows:
int value = i * j;
if ((i == error_location.row) and (j = error_location.column)) {
value = // code for introducing an error, e.g. sample a random answer,
// or a random offset added to the correct answer etc.
}
std::cout << "\t" << i * j;
The decision of a position for the erroneous values can be made using the C++ header, as explained in this question. In your case it would be something like the following:
constexpr const int table_leg { 10 };
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> coordinate_distribution(0, table_leg - 1);
struct { int row, col; } error_location =
{ coordinate_distribution(gen), coordinate_distribution(gen) };
Notes:
I suggest replacing i with row or row_index and j with col or column or column_index; also, using the named constant instead of repeating the "magic number" 10.
I've assumed you don't want to store your multiplication table in a buffer, then replace one value in there with an error. If you are storing the table somewhere, you could avoid the complicated inner loop and just set the error after filling in all the correct values.

So thank's to everyone's input - especially #Wolfgang.
I did read up on C++11's random header file and it's functions.
I did create a source code with random functions and one without.
Any feed would be appreciated on how to make my source code more efficient.
Other than that, it achieves what I needed it to do.
#include <iostream>
#include <ctime>
#include <iomanip>
const unsigned int ROWS = 10;
const unsigned int COLUMNS = 10;
void randomValue(unsigned int &, unsigned int &, unsigned int &);
int main()
{
unsigned int rValue;
unsigned int cValue;
unsigned int pValue;
unsigned int rowError;
unsigned int columnError;
unsigned int productError;
unsigned int userRowGuess;
unsigned int userColumnGuess;
char choice;
do
{
randomValue(rValue, cValue, pValue);
std::cout << "\033[2J\033[0;0H"; // This code clears the screen
std::cout << std::endl << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::setw(35) << "+ Multiplication Table +" << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::endl << std::endl;
while (true)
{
rowError = rValue;
columnError = cValue;
productError = pValue;
if (productError == rowError * columnError)
{
productError--;
}
for (unsigned int row = 1; row <= ROWS; row++)
{
for (unsigned int column = 1; column <= COLUMNS; column++)
{
if (row == rowError && column == columnError)
{
std::cout << "\t" << "" << productError;
}
else
{
std::cout << "\t" << row * column;
}
}
std::cout << std::endl;
}
break;
}
std::cout << std::endl << std::endl;
std::cout << "\t\t" << "Type in the column number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userColumnGuess;
std::cout << std::endl;
std::cout << "\t\t" << "Type in the row number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userRowGuess;
std::cout << std::endl;
if (userRowGuess != rowError && userColumnGuess != columnError)
{
std::cout << "\t\t" << "Your answer was incorrect!" << std::endl << std::endl;
std::cout << "\t\t" << "Error value '" << productError << "' is located" << std::endl;
std::cout << "\t\t" << "on row " << rowError << ", column " << columnError << "." << std::endl;
}
else
{
std::cout << "\t\t" << "You are correct! You win!" << std::endl;
}
std::cout << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N'" << std::endl;
std::cout << "\t\t" << "for no & then press [Enter]: ";
std::cin >> choice;
while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N')
{
std::cout << std::endl;
std::cout << "\t\t" << "Invalid entry. Only 'Y' or 'N'" << std::endl;
std::cout << "\t\t" << "are accepted answers." << std::endl << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N' for" << std::endl;
std::cout << "\t\t" << "no & then press [Enter]: ";
std::cin >> choice;
}
std::cout << std::endl;
} while (choice == 'y' || choice == 'Y');
std::cout << "\t\t" << "Press [Enter] to continue....." << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
void randomValue(unsigned int &rValue, unsigned int &cValue, unsigned int &pValue)
{
srand((unsigned)time(NULL));
unsigned int r = rValue = (rand() % ROWS) + 1;
unsigned int c = cValue = (rand() % COLUMNS) + 1;
unsigned int p = pValue = (rand() % (ROWS * COLUMNS)) + 1;
}

Related

cargo transportation system we are not sure how to display the last part of our task

Here is our code for the task we are almost finishing just the last part we are stuck at
"Fastest: 3 trips (1 Van, 3 Mini-lorry, $645) "
we are not sure how to display the values in the bracket we only able to display 3 trips.
Is there a way to also display the values in the bracket stated as well?
we use
int min = *min_element(vTrips.begin(), vTrips.end());
cout << "Fastest: " << min << " trips" << endl;
but this only display the 3 trips.
#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>
#include<algorithm>
using namespace std;
class CTS //cargo transport system
{
int i;
int cargo, lorryprice, vanprice, lorrysize, vansize, allOps;
public:
void set_cargo(int);
void set_lorryprice(int);
void set_vanprice(int);
void set_lorrysize(int);
void set_vansize(int);
};
void CTS::set_cargo(int total_cargo) {
cargo = total_cargo;
}
void CTS::set_lorryprice(int lorryP) {
lorryprice = lorryP;
}
void CTS::set_vanprice(int vanP) {
vanprice = vanP;
}
void CTS::set_lorrysize(int lorryS) {
lorrysize = lorryS;
}
void CTS::set_vansize(int vanS)
{
vansize = vanS;
}
int main()
{
int cargo, lorryprice, vanprice, lorrysize, vansize, options, i, no_lorry, no_van, cost, trips;
ifstream infile;
infile.open("size.txt");
if (infile.is_open()) {
infile >> cargo;
infile >> lorryprice;
infile >> vanprice;
infile >> lorrysize;
infile >> vansize;
}
CTS run;
run.set_cargo(cargo);
run.set_lorryprice(lorryprice);
run.set_vanprice(vanprice);
run.set_lorrysize(lorrysize);
run.set_vansize(vansize);
infile.close();
options = (cargo / lorrysize) + 1;
no_lorry = (cargo / lorrysize);
no_van = (cargo / vansize) + 3;
if (cargo % lorrysize == 0) {
no_van = -3;
}
if (cargo % lorrysize != 0) {
no_van = ((cargo % lorrysize) / 10) - 3;
}
/*it = numbervan.begin();
for (auto ir = numbervan.rbegin(); ir != numbervan.rend(); ++ir) {
cout << *ir << endl;
}*/
vector<int> vCost, vVan, vTrips, vLorry;
vector <int>::iterator it;
for (i = 1; i < options + 1; i++)
{
int numberlorry = no_lorry;
cout << "Option " << i << ":" << endl;
cout << "Number of Mini-Lorries : " << no_lorry-- << endl;
if (no_van >= -3) {
no_van += 3;
}
cout << "Number of Vans : " << no_van << endl;
int numbervan = no_van;
if (numberlorry > numbervan) {
trips = numberlorry;
}
else {
trips = numbervan;
}
cout << "Trips Needed : " << trips << endl;
cost = (numberlorry * lorryprice) + (no_van * vanprice);
cout << "Total Cost : $" << cost << endl;
vCost.push_back(cost);
vLorry.push_back(numberlorry);
vVan.push_back(numbervan);
vTrips.push_back(trips);
}
int counter = vCost.size() - 1;
//std::vector<int>::reverse_iterator ir = vCost.rbegin();
for (i = 1; i < 4; i++) {
//cout << "Lowest #" << i << ": "<<cost<<endl;
cout << "Lowest #" << i << ": $" << vCost[counter] << "(" << vVan[counter] << " Vans, " << vLorry[counter] << " Mini-Lorry, " << vTrips[counter] << " Trips)" << endl;
counter--;
}
int min = *min_element(vTrips.begin(), vTrips.end()); // this line of code we figured out how to
cout << "Fastest: " << min << " trips" << endl; //display the number of trips using algorithm
return 0;
}
Your design is awkward; you create an instance of CTS run; and never use it.
Assuming that you do your calculations right, you need to know at what index you found min. If you store the iterator returned by min_element(), you can get an index by subtracting vTrips.begin() from it. Then the corresponding elements in your vCost, vLorry and vVan vectors will contain the data you want.
However, it would be easier if you define a struct containing your pre-calculated values, and push that into some vector. In that case, all related data is kept together.

Integer overflow and std::stoi

if x > INT_MAX or if x > INT_MIN the function will return 0... or that's what i'm trying to do :)
in my test case i pass in a value that is INT_MAX + 1... 2147483648 ... to introduce integer overflow to see how the program handles it.
i step through... my IDE debugger says that the value immediately goes to -2147483648 upon overflow and for some reason the program executes beyond both of these statements:
if (x > INT_MAX)
if (x < INT_MIN)
and keeps crashes at int revInt = std::stoi(strNum);
saying out of range
Must be something simple, but it's got me stumped. Why isn't the program returning before it ever gets to that std::stoi() given x > INT_MAX? Any help appreciated. Thanks! Full listing of function and test bed below: (sorry having trouble with the code insertion formatting..)
#include <iostream>
#include <algorithm>
#include <string> //using namespace std;
class Solution {
public: int reverse(int x)
{
// check special cases for int and set flags:
// is x > max int, need to return 0 now
if(x > INT_MAX)
return 0;
// is x < min int, need to return 0 now
if(x < INT_MIN)
return 0;
// is x < 0, need negative sign handled at end
// does x end with 0, need to not start new int with 0 if it's ploy numeric and the functions used handle that for us
// do conversion, reversal, output:
// convert int to string
std::string strNum = std::to_string(x);
// reverse string
std::reverse(strNum.begin(), strNum.end());
// convert reversed string to int
int revInt = std::stoi(strNum);
// multiply by -1 if x was negative
if (x < 0)
revInt = revInt * -1;
// output reversed integer
return revInt;
}
};
Main:
#include <iostream>
int main(int argc, const char * argv[]) {
// test cases
// instance Solution and call it's method
Solution sol;
int answer = sol.reverse(0); // 0
std::cout << "in " << 0 << ", out " << answer << "\n";
answer = sol.reverse(-1); // -1
std::cout << "in " << -1 << ", out " << answer << "\n";
answer = sol.reverse(10); // 1
std::cout << "in " << 10 << ", out " << answer << "\n";
answer = sol.reverse(12); // 21
std::cout << "in " << 12 << ", out " << answer << "\n";
answer = sol.reverse(100); // 1
std::cout << "in " << 100 << ", out " << answer << "\n";
answer = sol.reverse(123); // 321
std::cout << "in " << 123 << ", out " << answer << "\n";
answer = sol.reverse(-123); // -321
std::cout << "in " << -123 << ", out " << answer << "\n";
answer = sol.reverse(1024); // 4201
std::cout << "in " << 1024 << ", out " << answer << "\n";
answer = sol.reverse(-1024); // -4201
std::cout << "in " << -1024 << ", out " << answer << "\n";
answer = sol.reverse(2147483648); // 0
std::cout << "in " << 2147483648 << ", out " << answer << "\n";
answer = sol.reverse(-2147483648); // 0
std::cout << "in " << -2147483648 << ", out " << answer << "\n";
return 0;
}
Any test like (x > INT_MAX) with x being of type int will never evaluate to true, since the value of x cannot exceed INT_MAX.
Anyway, even if 2147483647 would be a valid range, its reverse 7463847412 is not.
So I think its better to let stoi "try" to convert the values and "catch" any out_of_range-exception`. The following code illustrates this approach:
int convert() {
const char* num = "12345678890123424542";
try {
int x = std::stoi(num);
return x;
} catch (std::out_of_range &e) {
cout << "invalid." << endl;
return 0;
}
}

C++ Fibonacci sequence

The program I am trying to make is supposed to calculate and display each entry of the fibonacci sequence up to the 40th.
I believe I'm nearly there in terms of getting this done. The issue is: after the numbers 1 and 2, the sequence just seems to reset itself and leaves every subsequent number 1 place behind in the sequence.
This is the code:
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i==1)
{
cout << i << " " << b << endl;
}
else if (i==2)
{
cout << i << " " << b*2 << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}
I pre-programmed the first couple of numbers in the sequence because I couldn't get them to work properly, but after doing this, it seems to throw off the rest of the program.
The output from the code is this:
0 1
1 1
2 2
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144
13 233
14 377
15 610
16 987
17 1597
18 2584
19 4181
20 6765
21 10946
22 17711
23 28657
24 46368
25 75025
26 121393
27 196418
28 317811
29 514229
30 832040
31 1346269
32 2178309
33 3524578
34 5702887
35 9227465
36 14930352
37 24157817
38 39088169
39 63245986
It seems that I have solved this issue instantly after creating the post.
I decided to try pre-program the very first entry in the sequence (0) to be one, and completely remove the other pre-programmed parts in the sequence. This solved the entire thing.
Here's the working code:
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i == 0)
{
cout << i << " " << b << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}
You forgot to set a for the second case.
So when b = 2, c uses previous value of a which is 0.
Therefore, c = a+b = 0 + 2 = 2.
Set a = 1 in you second case:
else if (i==2)
{
a = 1 // This
cout << i << " " << b*2 << endl;
}
I pre-programmed the first couple of numbers in the sequence.. If you wish to go along this way, the following could be another method..
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 1;
cout << 0 << " " << a << endl;//simply display the preprogrammed numbers
cout << 1 << " " << b << endl;
for (int i = 2; i < 40; ++i)//apply the formula for remaining elements
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
return 0;
}
Try the following changes in your program.
#include <iostream>
using namespace std;
int main() {
int a = 0;
int b = 1;
for (int i = 0; i < 40; ++i)
{
if (i==0)
{
cout << i << " " << a << endl;
}
else if (i==1)
{
cout << i << " " << b << endl;
}
else
{
int c = a + b;
a = b;
b = c;
cout << i << " " << c << endl;
}
}
return 0;
}

(C++) Need help resolving Output file error

Priority:
I am quite new at this obviously. I have tried reading other peoples errors for what I have and can't find a fix. When I take out the ofstream bit and switch fOut for cout then program works fine but I cant seem to get it to output to a file. I did make the file in advance.
Secondary:
I am suppose to also somehow use 1 loop for the range of x should be 0 to 10 in steps of 1, 10 to 50 in steps of 5( In the SquareMachine function). Same rule of 1 loop for the bit in main with 0 to 15 in 1 degree increments and 15 to 45 in 5 degree increments. I am sure there is a technique I am simply not seeing to combine my loops or perhaps a loop... hole.. hah get it? Anyway, primarily need assistance with the output file.
Thank you for any advice/assistance
Error(s):
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
week4.cpp: In function ‘int main()’:
week4.cpp:44: error: ‘struct std::ofstream’ has no member named ‘is’
week4.cpp: In function ‘int SquareMachine()’:
week4.cpp:92: error: ‘fOut’ was not declared in this scope
Code:
#include <cmath>
#include<stdlib.h>
#include <iostream>
#include t<ime.h>
#include<cstdlib>
#include<unistd.h>
#include<iomanip>
#include<fstream>
using namespace std;
//Global Variable(s)
long fact(long n);
// Prototype(s)
int SquareMachine();
// Program Header
void ShowProgramHeader()
{
fOut << "Name" << endl;
fOut << "Class and Date \n\n\n" << endl;
}
//Command Center
int main()
{
ofstream fOut( "sTable.out", ios::out| ios::trunc);
if( fOut.is.open())
{
ShowProgramHeader();
SquareMachine();
fOut << "Value---Output\n"<<endl;
for( long t =0; t <=15; t++)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
}
for( long t =20; t <=45; t=t+5)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
fOut.close();
}
}
else
cout<<"Unable to Open the file: sTable.out";
exit(-1);
}
long fact(long n)
{
if( n ==0 || n==1 )
return 1;
else if( n==2 || n <= 15)
return n * fact( n-1);
else if( n <=15 || n <=45)
return n * fact (n-5);
}
int SquareMachine()
{
double x = 10;
int n = 2;
double z;
fOut << "\nNumber Sqrt Exp Pow\n";
for ( z=0; z<=x; ++z)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
for ( z=15; z<=50; z= z+5)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
fOut << " \n End of Part 1\n"<< endl;
}
You have numerous errors in your code. Mostly optimization errors, also some typos. But always, you should listen to your compiler first, because it helps you find the problem. It is designed to do so!
Sometimes it literally says what you should do (or what not) in a case of error.
For example your compiler says:
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
It means that in that function's scope fOut cannot be seen. It is because it was declared in the main() function, so it is a local variable (only avaiable in a scope) and not global (avaiable from everywhere). If you want to use this variable in other functions too, it is a good practice to use references or pointers. (I would recommend you using global variables only if you really need to do so, in special cases)
Included headers: (don't include unnecessary headers)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath> // for Mathematical functions
Function prototypes:
void ShowProgramHeader(std::ofstream&);
long fact(long);
int SquareMachine(std::ofstream&);
Client code:
int main() {
std::ofstream f_out("sTable.txt", std::ios::out | std::ios::trunc);
if(f_out.is_open()) {
ShowProgramHeader(f_out);
SquareMachine(f_out);
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Output" << std::endl;
long i = 0; // for fact(long)
while(i <= 45) {
if(i <= 15 || i >= 20) {
f_out << std::left << std::setw(10) << i;
f_out << std::left << std::setw(10) << fact(i) << std::endl;
if(i <= 15) i++;
else i += 5;
} else i++;
}
f_out.close();
}
else {
std::cerr << "Unable to Open the file: sTable.out";
return -1;
}
return 0;
}
Function implementations from here!
Header (I'm not really sure what you are planning to do with this function):
void ShowProgramHeader(std::ofstream& f_out) { f_out << "Name\nClass and Date\n"; }
Square machine:
int SquareMachine(std::ofstream& f_out) {
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Square";
f_out << std::left << std::setw(20) << "Exp";
f_out << std::left << std::setw(10) << "Power" << std::endl;
float i = 0;
while (i <= 50) {
if(i <= 10 || i >= 15) {
f_out << std::left << std::setw(10) << std::setprecision(2) << i;
f_out << std::left << std::setw(10) << std::setprecision(3) << std::sqrt(i);
f_out << std::left << std::setw(20) << std::setprecision(10) << std::exp(i);
f_out << std::left << std::setw(10) << std::setprecision(4) << std::pow(i, 2) << std::endl;
if(i <= 10) i++;
else i += 5;
} else i++;
}
f_out << std::endl << "End of Part 1" << std::endl;
}
And finally the recursive factorial function! (You overcomplicated your solution, if you meant to use the factorial method). Also note that when your factorial's value becomes so big, you have to handle it. You should find a type that can store larger numbers than long!
long fact(long n) {
if(n <= 1) return 1;
return n * fact(n - 1);
}
Output (I used sTable.txt instead of sTable.out)
Name
Class and Date
Number Square Exp Power
0 0 1 0
1 1 2.718281746 1
2 1.41 7.389056206 4
3 1.73 20.08553696 9
4 2 54.59814835 16
5 2.24 148.4131622 25
6 2.45 403.4288025 36
7 2.65 1096.633179 49
8 2.83 2980.958008 64
9 3 8103.083984 81
10 3.16 22026.46484 100
15 3.87 3269017.25 225
20 4.47 485165184 400
25 5 7.200490291e+010 625
30 5.48 1.068647422e+013 900
35 5.92 1.586013445e+015 1225
40 6.32 2.353852703e+017 1600
45 6.71 3.493427058e+019 2025
50 7.07 5.184705458e+021 2500
End of Part 1
Number Output
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 1932053504 // long storage problem starts from here
14 1278945280 // wrong!
15 2004310016 // wrong!
20 -2102132736 // wrong!
25 2076180480 // wrong!
30 1409286144 // wrong!
35 0 // wrong!
40 0 // wrong!
45 0 // wrong!
Since long can contain a value up to ~2,1*10^9, however 13! ~ 6*10^9!

Histogram Formatting

I am writing a program to create a horizontal histogram from an array of type double data. I was able to get the program to display the boundaries of each sub-interval along with the correct number of asterisks. However, the data is not formatted.
Here's the part of the program responsible for the output:
// endpoints == the boundaries of each sub-interval
// frequency == the number of values which occur in a given sub-interval
for (int i = 0; i < count - 1; i++)
{
cout << setprecision(2) << fixed;
cout << endPoints[i] << " to " << endPoints[i + 1] << ": ";
for (int j = frequency[i]; j > 0; j--)
{
cout << "*";
}
cout << " (" << frequency[i] << ")" << endl;
}
Here's what my output looks like:
0.00 to 3.90: *** (3)
3.90 to 7.80: * (1)
7.80 to 11.70: * (1)
11.70 to 15.60: (0)
15.60 to 19.50: ***** (5)
Here's what I would like it to look like:
00.00 to 04.00: *** (3)
04.00 to 08.00: * (1)
08.00 to 12.00: * (1)
12.00 to 16.00: (0)
16.00 to 20.00: ****** (6)
I've looked up C++ syntax and have found things like setw() and setprecision(). I tried to use both to format my histogram but have not been able to make it look like the model. I was hoping someone could tell me if I'm on the right track and, if so, how to implement setw() and/or setprecision() to properly format my histogram.
Assuming that all numbers are in the [0,100) interval, what you want is a chain of manipulators like:
#include <iostream>
#include <iomanip>
int main() {
std::cout
<< std::setfill('0') << std::setw(5)
<< std::setprecision(2) << std::fixed
<< 2.0
<< std::endl;
return 0;
}
Which will output:
02.00
This is for a single value, you can easily adapt it to suit your needs.
You could, for instance, turn this into an operator and use it like:
#include <iostream>
#include <iomanip>
class FixedDouble {
public:
FixedDouble(double v): value(v) {}
const double value;
}
std::ostream & operator<< (std::ostream & stream, const FixedDouble &number) {
stream
<< std::setfill('0') << std::setw(5)
<< std::setprecision(2) << std::fixed
<< number.value
<< std::endl;
return stream;
}
int main() {
//...
for (int i = 0; i < count - 1; i++) {
std::cout
<< FixedDouble(endPoints[i])
<< " to "
<< FixedDouble(endPoints[i + 1])
<< ": ";
}
for (int j = frequency[i]; j > 0; j--) {
std::cout << "*";
}
std::cout << " (" << frequency[i] << ")" << std::endl;
//...
}