How to show numbers in cout without the "e" notation? - c++

I tried to print a 'power table' of numbers without having them displayed using the "e" format but I can't figure out what's wrong. Here's my program:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double num [11][11];
for (int i=0; i<=10; i++)
{
cout << "\t^" << i;
}
cout << endl;
for (int row=1; row<=10; row++)
{
cout << row << "\t";
for (int col=0; col<=10; col++)
{
num [row][col] = pow (row,col);
cout << num [row][col] << "\t";
}
cout << endl;
}
return 0;
}

You can use the setiosflags function with std::ios_base::fixed as its argument to specify that scientific notation (using the 'e') should not be used; you will also (most likely) need to call setprecision with an argument of 0.
Add this line near the start of your main function:
std::cout << std::setiosflags(std::ios_base::fixed) << std::setprecision(0);
Be sure to also add #include <iomanip> to your code. Also note that, using such (fixed) output format will mess up your table when there are more digits in the number than the width of the tab stops (typically 8 characters). Handling such cases is a slightly different issue, though. One way would be to add two tabs for each column, only printing the second for the first column or if the value in the previous column has less than 8 digits; something like this (assuming 8 chars per tab-stop):
#include <iostream>
#include <cmath>
#include <iomanip>
int main()
{
std::cout << std::setiosflags(std::ios_base::fixed) << std::setprecision(0);
double num[11][11];
for (int i = 0; i <= 10; i++) {
std::cout << "\t\t^" << i; // Two tabs per column
}
std::cout << std::endl;
for (int row = 1; row <= 10; row++)
{
std::cout << row << "\t";
for (int col = 0; col <= 10; col++)
{
num[row][col] = pow(row, col);
if ((col == 0) || (num[row][col-1] <= 9999999)) std::cout << "\t"; // Need the extra tab
std::cout << num[row][col] << "\t";
}
std::cout << std::endl;
}
return 0;
}

Related

How can I print 2D arrays with four columns

I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;
The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,

Carrying out a c++ 2d array

My array is supposed to accept 3 values for 3 salespersons, store and print the array but somehow I can't get it going. I'm not too familiar with c++ 2d arrays so this is a tad bit new to me. The code is supposed to accept user input, and then output the prices of the products into table like format.
I had to clean up a lot of code to get this to even begin to compile. There were many cases where the closing } of a block was not present. These mistakes are easy to make, but they're also easy to spot if you're disciplined about maintaining a consistent indentation style.
Once I indented the code it became fairly obvious where the errors were, but identifying these in the original is very hard.
Here's the cleaned up code:
#include <iostream>
#include <iomanip>
int main( ) {
const int salesPersonCount =3, productCount = 3;
int rows = 5, columns = 5;
int sales[rows][columns];
double total;
for (int p = 1; p <= salesPersonCount; p++) {
std::cout << "\n \n Information for SalesPsn"<< p <<" : \n \n";
//Sales Person
for (int m = 1; m <=productCount; m++) {
//Product Number
std::cout << "\n Please enter sales value of product "<< m << ":";
std::cout << "\n ";
for (int i=0;i<rows;i++) {
for (int j=3;j<columns; j++) {
std::cout << "\nThe 2-D Array is:\n";
for (int i=0;i<2;i++) {
for (int j=0;j<2;j++) {
std::cout << "\t" << sales[i][j];
}
std::cout << "Sale " << std::setw (17) << "Salespsn1" << std::setw (22)<< "Salespsn2"
<< std::setw (27)<< "Salespsn3" << std::setw (32) << "Total" << std::endl;
}
std::cout << std::endl;
}
}
}
}
return 0;
}
Note this still has a lot of problems you're going to need to resolve, like how you're capturing sales and information into variables p and m which are also used for iterators, plus how nothing actually puts data into the sales structure, but at least you've got something you can fix.
My advice: When you get into a deep hole, stop digging. If you can't figure out what to do, clean up your code. I've solved many problems in the course of better organizing what I've done, in adding comments to parts that should work yet don't. There's no shame in being stuck, but if you're stuck because of a mess you didn't clean up that's on you.
I went over the code and this is the final product... Turns out no input was needed I was overthinking. Thanks for the help #tadman For anyone who is interested:
#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <math.h>
#define ROW 3 //number of rows
#define COL 3 // number of columns
//Function Prototype section
void enterItems(double salesArray[][COL]);
void getRowTotal (double Sales[][3], double total[][3]);
void getColTotal (double Sales[][3], double total[][3]);
void DisplayArray (double Sales[][3], double total[][3]);
using namespace std;
int main (){ //function main begins program execution
//storing 3 sales person and 3 different product
//Declares Arrays
double Sales[ROW][COL] = { {250,200,300 }, {500,350,220 },{150,600,450 }};
double total[2][3] = {0};
//Calls Functions getRowTotal, getColTotal and DisplayArray
getRowTotal (Sales, total);
getColTotal(Sales, total);
DisplayArray (Sales, total);
//Signifies that program is successfully executed
return 0;
}
//variables
int z = 0, j = 0;
//Declares And Defines getRowTotal
void getRowTotal (double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++)
total[0][z] = Sales[0][z] + Sales[1][z] + Sales[2][z];
}
//Declares and Defines getColTotal
void getColTotal(double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++){
total[1][z] = Sales[z][0] + Sales[z][1] + Sales[z][2];
}
}
//function DisplayArry
void DisplayArray (double Sales[][3], double total[][3]){
//Table Headings
cout << left << setw(10) << "Title" << setw(15) << "SalesPerson1 " << setw(15) << "SalesPerson2 " << setw(15) << "SalesPerson3 " << "Total";
cout << "\n_______________________________________________________________________________________________\n";
cout << fixed << setprecision(2) << showpoint;
//Displays the Sales and row headings
for(z = 0; z < 3; z++){
cout << setw(8) << "Product " << z + 1 << setw(1) << " ";
for(j = 0; j < 3; j++)
cout << setw(17) << Sales[j][z];
cout << setw(17) << total[0][z];
cout << endl;
}
cout << setw(8) << "Total";
for( z = 0; z < 3; z++)
cout << setw(19) << total[1][z];
cout << "\n_______________________________________________________________________________________________\n";
}

Building a Triangle with c++ loops

I am trying to build a triangle, with a user entered base and height.
When these entered values are different (base!=height), the program goes haywire and gets stuck in the triangle draw loop.
I've tried altering the code a couple of times, but please treat me as a programming novice.
//BUILD TRIANGLE//
#include <string>
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "\nEnter base and height:\n";
int height{0}; int base{0};
std::cin >> base >> height;
std::string bottom(base, '*');
std::string top = "*";
int middlerows = height - 1;
int middlespacechars;
std::cout << top << std::endl;
for (middlespacechars = 0;
middlerows != 1 || middlespacechars != base - 2;
++middlespacechars, --middlerows) {
std::string middlespace(middlespacechars, ' ');
std::cout << "*" << middlespace << "*\n";
}
std::cout << bottom << "\n" << std::endl;
std::cout << "^TRIANGLE\n";
std::cout << "BASE = " << base << std::endl;
std::cout << "HEIGHT = " << height << std::endl;
std::cout << "goodbye" << "\n" << std::endl;
}
The output is totally haywire, with asterisks across the screen in no discernible shape.
When I put in values where base=height, though, a pretty little right angle triangle pops up.
With your code, you can only draw well triangles which have base equal to height.
If you change stop condition in your for loop, you can get what you probably want to get:
for (middlespacechars = 0; middlerows != 1 || middlespacechars != base - 2; ++middlespacechars, --middlerows) {
... into ...
for (middlespacechars = 0; middlerows > 1 || middlespacechars < base - 2; ++middlespacechars, --middlerows) {
It was huge probability that if base and height are different then stop condition will not be achieved. For loop in your code will stop if middlerows will be 1 and middlespacechars will be base - 2 at the same moment.
Test it here.
//C++ program to display hollow star pyramid
#include<iostream>
using namespace std;
int main()
{
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++)
{
//for loop to put space in pyramid
for (space = i; space < rows; space++)
cout << " ";
//for loop to print star
for(j = 1; j <= (2 * rows - 1); j++)
{
if(i == rows || j == 1 || j == 2*i - 1)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}

How to display horizontally in C++?

There are two lines of out for every iteration of the loop. I want for line a to be on top of line b in every iteration. Moreover, I want to display the next (i=1) iterated line a and b to be horizontal with the previous (i=0) line a and b.
for (int i = 0; i < 2; ++i){
cout << "LOOP" << endl; //line a
cout << i << endl; //line b
}
Current output:
LOOP
0
LOOP
1
Desired output:
LOOP LOOP
0 1
You can keep the logic of your program as it is and store the output in a buffer before sending it to stdout.
For example you can use a std::ostringstream for every line:
#include <iostream>
#include <sstream>
#include <iomanip>
int main() {
std::ostringstream line_a,
line_b;
for (int i = 0; i < 4; ++i) {
line_a << std::setw(6) << "LOOP";
line_b << std::setw(6) << i;
}
std::cout << line_a.str() << '\n'
<< line_b.str() << '\n';
return 0;
}
You can do
for (int i = 0; i < 2; ++i) {
cout << "LOOP\t";
}
cout << endl;
for (int i = 0; i < 2; ++i) {
cout << i << "\t";
}

How To Change Multidimensional Array Size In Program?

Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}