Still new to this. What is wrong with this code? I'm trying to make and use a 2 dimensional array. Is my general idea correct? To step through it with nested for loops? What exactly is wrong with my code? It won't compile.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double NUM_MONKEYS = 3;
const double NUM_DAYS = 5;
double monkeys[NUM_MONKEYS][NUM_DAYS];
int row, column;
for (row = 0, row < NUM_MONKEYS, row++)
{
for (column = 0, column < NUM_DAYS, column++)
{
cout << "Input amount of food eaten by monkey: " << row + 1;
cout << " and day: " << column + 1 << endl;
cin >> monkeys[row][column];
}
}
return 0;
}
There's something I'm not getting, thanks!
First of all - size of array should be of integer type and you have defined it as double.
Second - Syntax of for loop is incorrect, there should be ';' instead of ',' in your for loop.
#include <iostream>
#include <iomanip>
int main()
{
const int NUM_MONKEYS = 3;
const int NUM_DAYS = 5;
double monkeys[NUM_MONKEYS][NUM_DAYS];
int row, column;
for (row = 0; row < NUM_MONKEYS; row++)
{
for (column = 0; column < NUM_DAYS; column++)
{
std::cout << "Input amount of food eaten by monkey: " << row + 1;
std::cout << " and day: " << column + 1 << endl;
std::cin >> monkeys[row][column];
}
}
return 0;
}
Though you can store double type values in your array.
Also as said try and avoid 'using namespace std;' see here.
Related
Write a program that reads 12 integers into a 2D integer array with 4 rows and 3 columns. The program then outputs the 2D array in reverse order according to both rows and columns.
Ex: If the input is:
5 7 3
6 4 3
5 6 9
5 2 8
then the output is:
8 2 5
9 6 5
3 4 6
3 7 5
For coding simplicity, output a space after every integer, including the last one on each row.
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
cin>>arr[i][j];
}
}
cout << arr[3][2] << " " << arr[3][1] << " " << arr[3][0] << " " << endl;
cout << arr[2][2] << " " << arr[2][1] << " " << arr[2][0] << " "<< endl;
cout << arr[1][2] << " " << arr[1][1] << " " << arr[1][0] << " "<< endl;
cout << arr[0][2] << " " << arr[0][1] << " " << arr[0][0] << " "<< endl;
return 0;
}
I ended up having to hardcode this question because I couldnt find a way to reverse the 2D array with a loop and get it to be outputted in the form of a graph. Is there a way i could reverse the 2D array using for loops and would it be possible to be able to change the amount of rows and columns and still output the corresponding graph of values?
try this:
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// output the reversed array
for (int i = ROWS - 1; i >= 0; i--) {
for (int j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
You can reverse a 2D array using nested for loops, try
#include <iostream>
using namespace std;
int main() {
const int ROWS = 4;
const int COLS = 3;
int arr[ROWS][COLS];
int i, j;
// Input the values into the 2D array
for(i = 0; i < ROWS; i++) {
for(j = 0; j < COLS; j++) {
cin >> arr[i][j];
}
}
// Reverse the rows and columns of the 2D array
for(i = ROWS - 1; i >= 0; i--) {
for(j = COLS - 1; j >= 0; j--) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
As mentioned in comments below if you don't know ROWS and COLS size at compile time dynamically allocate the memory for 2D array(arr) in C++ using new operator.
There is very little point reading the data into a 2D array for this program. A std::vector would do the trick, sized with ROWS * COLS values. You then have the benefit of being able to read those dimensions from the user, which addresses the second part of your question.
size_t size = ROWS * COLS;
// Read data
std::vector<int> data;
data.reserve(size);
for (int value; std::cin >> value; )
{
data.push_back(value);
}
// Validate data
if (data.size() != size)
{
std::cerr << "Unexpected end of input!\n";
return EXIT_FAILURE;
}
When outputting, you can use a reverse iterator through the vector, and simply write a newline every COLS values.
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it << " ";
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
}
You can even easily fix the "space at the end of the line" problem by adjusting your output loop as follows:
// Output in reverse
int col = 0;
for (auto it = data.rbegin(); it != data.rend(); it++)
{
std::cout << *it;
if (++col == COLS)
{
std::cout << "\n";
col = 0;
}
else
{
std::cout << " ";
}
}
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;
}
This is supposed to be a code for user entering integers in an array and then calling a function that shows if they are even or odd. It then counts how many are even or odd (which I didn't get to yet because I am stuck here and I keep getting this error).
invalid operands of types 'int [20]' and 'int' to binary 'operator%'
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int[], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout<<fixed<<showpoint<<setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
if ( numbers % 2== 0 )
// if the integer when divided by 2 has no remainder then it's even.
cout << numbers << " is even "<<endl;
else
// the integer is odd
cout << numbers << " is odd "<<endl;
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for(index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout<< "Enter an integer " << (index + 1)<< " : ";
cin>> numbers[index];
}
}
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int [], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout << fixed << showpoint << setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
//I added this FOR loop.
for (int i = 0; i < ARRAY_SIZE - 1; i++)
{
//I also added the [i] so that the number is outputted as well
if (numbers[i] % 2 == 0)
// if the integer when divided by 2 has no remainder then it's even.
// and here as well
cout << numbers[i] << " is even "
<< endl;
else
// the integer is odd
cout << numbers[i] << " is odd "
<< endl;
}
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for (index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout << "Enter an integer " << (index + 1) << " : ";
cin >> numbers[index];
}
}
I added a for loop and the array brackets on the output.
You need to loop through your array, just add a loop and check if (numbers[index] % 2 == 0)
Above answers should give you right results.
You can use a range for loop for fixed-size arrays:
for (int value : numbers)
{
if (value % 2 == 0)
{
cout << value << " is even.\n";
}
else
{
cout << value << " is odd.\n";
}
}
First, this is illegal in C++:
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
You need to declare
int numbers[20];
instead.
Second,
if ( numbers % 2== 0 )
numbers is an array of 20 values. What exactly is it meant to be using the % operator on? You probably want a loop that will check each int in the array.
for (int i = 0; i < 20; ++i)
{
if ( numbers[i] % 2== 0 )
...
else
...
}
Earlier I asked how to export a 2D array with random numbers as the data.
Link: Converting 2D array to text using c++ functions
Now I'm trying to write a separate program that can calculate the average of each column of that array.
But now I'm having issues with "uninitialized variables" that I'm pretty sure are initialized.
Not really sure what to do from here. Any help would be appreciated!
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
string Data, FileName;
int row, col, x, y;
float Matrix[50][50], sum, average;
cout << "Enter the name you gave the matrix file.\n";
cout << "(DO NOT INCLUDE ANY SPACES OR EXTENSIONS!)\n";
cin >> FileName;
FileName = "C:\\Users\\Public\\Documents\\" + FileName + ".ascii";
ifstream Fin(FileName);
if (Fin.is_open())
{
row=0;
while(!Fin.eof())
{
getline(Fin, Data);
stringstream ss(Data);
col=0;
while(ss >> Matrix[row][col])
{
col++;
}
row++;
}
Fin.close();
}
else
cout << "Unable to open file";
for (int y = 0; y < col; y++)
{
for (int x = 0; x < row; x++)
{
sum = sum + Matrix[x][y];
}
average = sum / row;
cout << average << " for column " << col << "\n";
}
system("pause");
return 0;
}
UPDATE:
Solved the "uninitialized variables" error.
But now get "-nan(ind)" when I try to calculate the average.
Here's the new code...
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
string Data, FileName;
int row, col;
float Matrix[50][50], sum, average;
sum = 0;
cout << "Enter the name you gave the matrix file.\n";
cout << "(DO NOT INCLUDE ANY SPACES OR EXTENSIONS!)\n";
cin >> FileName;
FileName = "C:\\Users\\Public\\Documents\\" + FileName + ".ascii";
ifstream Fin(FileName);
if (Fin.is_open())
{
row=0;
while(!Fin.eof())
{
getline(Fin, Data);
stringstream ss(Data);
col=0;
while(ss >> Matrix[row][col])
{
col++;
}
row++;
}
Fin.close();
}
else
cout << "Unable to open file";
for (int y = 0; y < row; y++)
{
for (int x = 0; x < col; x++)
{
sum = sum + Matrix[x][y];
}
average = sum / col;
cout << average << "\n";
}
system("pause");
return 0;
}
UPDATE 2:
All I can seem to get is the average for the first column. Can't really work out how to repeat this step. I've tried using do and for loops, but this got me a bunch of errors and losing the only average I get.
If anyone want's to take a look, be warned its very messy...
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
string Data, FileName;
int row, col;
float Matrix[50][50], sum, average;
sum = 0;
cout << "Enter the name you gave the matrix file.\n";
cout << "(DO NOT INCLUDE ANY SPACES OR EXTENSIONS!)\n";
cin >> FileName;
FileName = "C:\\Users\\Public\\Documents\\" + FileName + ".ascii";
ifstream Fin(FileName);
if (Fin.is_open())
{
row=0;
while(!Fin.eof())
{
getline(Fin, Data);
stringstream ss(Data);
col=0;
while(ss >> Matrix[row][col])
{
col++;
}
row++;
}
Fin.close();
}
else
cout << "Unable to open file";
double AvgArray[50];
for (int y = 0; y < 50; y++)
{
for (int x = 1; x < 50; x++)
{
if (Matrix[x][y]<0)
{
break;
}
sum = sum + Matrix[x][y];
average = sum / x;
}
if (Matrix[y][y]<0)
{
break;
}
average = AvgArray[y];
}
cout << average << "\n";
system("pause");
return 0;
}
You forgot to set sum to 0 before the second for-loop. In UPDATE 2 you still don't set sum to 0!?
after the first 'for' and before the second ... before you start adding the sums for a column ...
like this
for (int y = 0; y < col; y++)
{
sum = 0;
for (int x = 0; x < row; x++)
{
sum = sum + Matrix[x][y];
}
average = sum / row;
cout << average << " for column " << y << "\n";
}
You gave this:
for (int y = 0; y < 50; y++)
{
for (int x = 1; x < 50; x++)
{
if (Matrix[x][y]<0)
{
break;
}
sum = sum + Matrix[x][y];
average = sum / x;
}
if (Matrix[y][y]<0)
{
break;
}
average = AvgArray[y];
}
In this part of your code, it appears that you are trying to calculate the average at every row in every column (because you put average = sum / x; inside both of the for loops.) I would recommend calculating the sum of the entire column before calculating the average, in order to save code/time. Furthermore, you also put average = AvgArray[y];. Assuming you're trying to fill this array with the averages for each column, you will want to assign average to AvgArray[y] instead. Currently, you never assign any values to AvgArray[].
cout << average << "\n";
Like in the code Zsolt Marx gave, you will want to put this line inside the larger of the two for loops. Otherwise, if you leave it the way you have it, the code will only display the average for the last column calculated.
I have a 2 part question. I am showing a user defined array. User input is # of rows, columns, and at what interval in the array to put a symbol.
I cannot get an output of the default symbol ****.
Where do I need to insert the interval input to adjust the array accordingly? Inside the function itself or define another function to do this?
I am looking for this result. Input = 1 (row), 4 (columns), 2 (interval). Output would be **?*.
Here is what I have so far.
#include <iostream>
using namespace std;
int rows = 0, columns = 0, interval = 0;
char symbol;
void Display(int rows = 0, int columns = 0, int interval = 0, char symbol = ('*'));
int main()
{
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> columns;
cout << "Enter the number of the question mark interval: ";
cin >> interval;
cout << "\n";
cout << "How many rows do you want? " << rows << "\n";
cout << "How many columns do you want? " << columns << "\n";
cout << "How far between question marks? " << interval << "\n";
Display(rows, columns, interval, symbol);
return 0;
}
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
cout << symbol;
}
cout << endl;
}
system("pause");
}
The problem is you never assigned * to symbol.
Change
char symbol;
to
char symbol = '*';
Did you know about the disadvantages of global variables. The sooner you learn about the cons the better. Here is a starting point.
Modify the Display function as below:
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
if ((x % (interval + 1)) == 0) //<--since you want after every intervals, just do a mod operation
cout << "?";
else
cout << symbol;
}
cout << endl;
}
system("pause");
}
Here is the working example.