I'm very new to programming, and I have a project where I need to take in two 6-by-2 matrices from a separate data file containing the life expectancy of black and white males/females in each decade from 1950 to 2000, then subtract the matrices to form a third 6-by-2 matrix containing the difference between the life expectancy of males and females of the same race in each decade. We didn't cover multidimensional arrays in class, and I'm a bit confused by this. I get a lot of errors saying undeclared identifier. I also know there has to be a better way to get the arrays from the data file, but I'm not sure how. Sorry if this is a stupid question.
#include <iostream>
#include <fstream>
using namespace std;
void getMatrixFemaleW();
void getMatrixFemaleB();
void getMatrixMaleW();
void getMatrixMaleB();
void matrix_diff();
int main()
{
float matrixFemale[6][2];
getMatrixFemaleW;
getMatrixFemaleB;
float matrixMale [6][2];
getMatrixMaleW;
getMatrixMaleB;
float matrixDifference[6][2];
matrix_diff;
for (int x=0; x<6; x++)
{
for (int y=0; y<2; y++)
{
cout << matrixFemale[x][y] << " ";
}
cout << endl;
}
}
void getMatrixFemaleW()
{
ifstream inputFile;
inputFile.open("MatrixFemaleW.txt");
int count = 0;
while (count < 6 && inputFile >> matrixFemale[count][0])
count++;
}
void getMatrixFemaleB()
{
ifstream inputFile;
inputFile.open("MatrixFemaleB.txt");
int count = 0;
while (count < 6 && inputFile >> matrixFemale[count][1])
count++;
}
void getMatrixMaleW()
{
ifstream inputFile;
inputFile.open("MatrixMaleW.txt");
int count = 0;
while (count < 6 && inputFile >> matrixMale[count][0])
count++;
void getMatrixMaleB()
{
ifstream inputFile;
inputFile.open("MatrixMaleB.txt");
int count = 0;
while (count < 6 && inputFile >> matrixMale[count][1])
count++;
}
void matrix_diff()
{
for (i=0; i<6; i++)
{
matrixDifference[i][0] = matrixFemale [i][0] - matrixMale[i][0];
}
for (i=0 i<6; i++)
{
matrixDifference [i][1] = matrixFemale [i][1] - matrixMale [i][1];
}
}
first these lines should be
getMatrixFemaleW();
getMatrixFemaleB();
getMatrixMaleW();
getMatrixMaleB();
matrix_diff();
because they are fuctions not variables you need to call them not declear them
then if you wanna reach a variable from outher function it should be global variable or a pointer that means
float matrixFemale[6][2];
float matrixMale [6][2];
float matrixDifference[6][2];
make these variables global variable or pointers
Related
#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.
So, I need to make a function that is going to return the chromatic number of a graph. The graph is given through an adjecency matrix that the function finds using a file name. I have a function that should in theory work and which the compiler is throwing no issues for, yet when I run it, it simply prints out an empty line and ends the program.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int Find_Chromatic_Number (vector <vector <int>> matg, int matc[], int n) {
if (n == 0) {
return 0;
}
int result, i, j;
result = 0;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
if (matg[i][j] == 1) {
if (matc[i] == matc[j]) {
matc[j]++;
}
}
}
}
for (i = 0; i < n; i++) {
if (result < matc[i]) {
result = matc[i];
}
}
return result;
}
int main() {
string file;
int n, i, j, m;
cout << "unesite ime datoteke: " << endl;
cin >> file;
ifstream reader;
reader.open(file.c_str());
reader >> n;
vector<vector<int>> matg(n, vector<int>(0));
int matc[n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
reader >> matg[i][j];
}
matc[i] = 1;
}
int result = Find_Chromatic_Number(matg, matc, n);
cout << result << endl;
return 0;
}
The program is supposed to use an freader to convert the file into a 2D vector which represents the adjecency matrix (matg). I also made an array (matc) which represents the value of each vertice, with different numbers corresponding to different colors.
The function should go through the vector and every time there is an edge between two vertices it should check if their color value in matc is the same. If it is, it ups the second vale (j) by one. After the function has passed through the vector, the matc array should contain n different number with the highest number being the chromatic number I am looking for.
I hope I have explained enough of what I am trying to accomplish, if not just ask and I will add any further explanations.
Try to make it like that.
Don't choose a size for your vector
vector<vector<int> > matg;
And instead of using reader >> matg[i][j];
use:
int tmp;
reader >> tmp;
matg[i].push_back(tmp);
OK I'm still a beginner, and i have alot to learn. Still in my first programming class and was wondering if i could get some help on an assignmet. I DON'T WANT YOU TO DO IT FOR ME just some help. I'm supposed to making a lottery type game using arrays and functions. Here's what i have so far:
#include<iostream>
#include<random>
#include<ctime>
using namespace std;
void getPlayersNumbers(int playerArray[], int size);
void getComputersNumbers(int computerArray[], int size);
bool WinningNumber(int playerArray[], int computerArray[], int size);
int main() {
const int SIZE = 5;
int userNumbers[SIZE];
int computerNumbers[SIZE];
getComputersNumbers(computerNumbers, SIZE);
return 0;
}
void getPlayersNumbers(int playerArray[], int size) {
int playersNumbers;
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
cin >> ???
}
}
void getComputersNumbers(int computerArray[], int size) {
mt19937 randomGenerator(time(0));
uniform_int_distribution<int> randomNumbers(1, 5);
int computerNumbers;
for (int i = 0; i < size; i++) {
computerNumbers = randomNumbers(randomGenerator);
computerArray[i] = computerNumbers;
cout << computerNumbers << " ";
}
cout << endl;
}
bool winningNumbers(int playerArray[], int computerArray[], int size) {
}
My getComputerNumbers function is working just fine. The one I'm having trouble with is my getPlayerNumbers function. How would i go about getting the uses numbers from them, and keeping them so when i call the function i can compare them to the random numbers in my getComputerNumbers function? Now i already know how I'm going to go about comparing the numbers. That's what my that third function winningNumbers is for. I just Need help with the getPlayersNumbers.
Also if you see anything else that i can do to make this code better let me know.
Thanks again!!
If you want to store user's number into an array:
for (int i = 0; i < size; i++) {
cin >> userNumbers[i]
}
when you want to access a particular number out of the five, you use:
userNumbers[n], where n ranges from 0 to 4
Just do:
void getPlayersNumbers(int* playerArray, int size)
{
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
cin >> playerArray [i];
}
}
Thanks to #user4581301 for pointing out a better solution using std::vector
std::vector getPlayersNumbers(int size)
{
std::vector myNumberList;
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
int number;
cin >> number;
myNumberList.push_back (number);
}
return myNumberList;
}
STL makes working with arrays a whole lot easier and also it provides additional functions that are optimized for their use case
I am new to programming and c++. I am working on an assignment which requires me to read data from a data file and store it into a 2D array. Every line in the text file is in the following format(data type is int)
XXXX XX XX XX XX ...(and so on)
The four digit number is actually student ID and is to be stored in a separate 1D array. I have done this part and I don't have any issues. Now the rest 2 digit numbers are to be stored in a 2D array with 4 columns and X rows, where X is the number of lines in the data file.
I have written the following code to try to read into the file. It gives no error and compiles correctly but when I try to print the 2D array, using cout, I don't get anything. Nothing. Please look at the following code and try to help me.
I am new to stackoverflow and programming so please forgive me if the code is not formatted correctly or is not as per the tradition.
//___CODE____
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
//Global
const int SIZE = 1000;
int const col = 4;
string fileName;
//Function Prototypes
int readId(int id[], int size);
int readScores(int scores[][col], int size);
//Main
int main()
{
int examScores[SIZE][col];
int id[SIZE] = {};
cout<<endl;
readId(id, SIZE);
readScores(examScores, SIZE);
}
//Declarations
int readId(int id[], int size)
{
ifstream inputFile;
int count = 0;
int total = 0; //Size of id [] OR no. of students.
int temp = 0;
//Takes the name of the data file from the user.
//NOTE: The filename should include its extension.
cout<<"Enter the name of the data file (including the extension):";
cin>>fileName;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 == 0)
{
id[total] = temp;
total++;
}
++count;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the content of array. Check.
for(int i=0; i < total; i++)
cout<<id[i]<<endl;
return total;
}
int readScores(int scores[][col], int size)
{
ifstream inputFile;
int count = 0;
int c = 0; //Counter for column.
int total = 0; //No. of students.
int temp = 0;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 != 0)
{
if (c < col)
{
scores[total][c] = temp;
}
else
total++;
c = 0;
scores[total][c] = temp;
}
++count;
c++;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the contents of 2D array. Check.
for (int r = 0; r < total; r++)
{
for (c = 0; c < col; c++)
{
cout<<setw(8)<<scores[r][col];
}
cout<<endl;
}
return total;
}
Your else-Statement is wrong, there are some brackets missing (now you always reset c to zero)
I've tried to debug my program yet it isn't helping. I've only used WHILE loops to put data into arrays but I figured using a FOR loop here would be easier.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct record
{
int item_id;
string item_type;
int item_price;
int num_stock;
string item_title;
string item_author;
int year_published;
};
void read_all_records(record records[]);
int num_inventory_of_type(record records[]);
const int max_array = 100;
int main()
{
record records[max_array];
read_all_records(records);
cout << records[1].item_author;
num_inventory_of_type(records);
return 0;
}
void read_all_records(record records[])
{
ifstream invfile;
invfile.open("C:\\Users\\acsindle\\Dropbox\\Prog2\\Asg22\\Asg22\\inventory.dat");
if (!invfile.is_open())
{
cout<<"file open failed";
exit(1);
}
int slot = 0;
for (int count = 0; count<max_array; count++)
{
invfile >> records[slot].item_id >>
records[slot].item_type >>
records[slot].item_price >>
records[slot].num_stock >>
records[slot].item_title >>
records[slot].item_author >>
records[slot].year_published;
slot++;
}
invfile.close();
}
int num_inventory_of_type(record records[])
{
int slot = 0;
int book = 0;
int dvd = 0;
int cd = 0;
for (int count = 0; count>max_array; count++);
{
if (records[slot].item_type == "book")
book++;
if (records[slot].item_type == "dvd")
dvd++;
if (records[slot].item_type == "cd")
cd++;
}
return book, dvd, cd;
}
My .dat file is as follows:
123456 book 69.99 16 Problem_Solving_With_C++ Walter_Savitch 2011
123457 cd 9.99 32 Sigh_No_More Mumford_and_Sons 2010
123458 dvd 17.99 15 Red_State Kevin_Smith 2011
123459 cd 9.99 16 The_Church_Of_Rock_And_Roll Foxy_Shazam 2012
123460 dvd 59.99 10 The_Walking_Dead_Season_1 Robert_Kirkman 2011
They're all separate on a single line with no spaces so there is no need to splice them. It should just be as easy as cin and stored. Not sure if it's my FOR loop that is messed up or if it's an issue with passing the array. Also my array is tied into my struct, is there a term for this? Is this what is considered a multidimensional array?
The terminating condition is incorrect and there is a trailing semi-colon:
for (int count = 0; count>max_array; count++);
Change to:
for (int count = 0; count<max_array; count++)
Also slot is not incremented in the for, and only cd will be returned by the num_inventory_of_type() function: you can't return three values like that from a function.
A possible implementation:
void num_inventory_of_type(record records[], int& book, int& dvd, int& cd)
{
for (int slot = 0; slot<max_array; slot++)
{
if (records[slot].item_type == "book")
book++;
if (records[slot].item_type == "dvd")
dvd++;
if (records[slot].item_type == "cd")
cd++;
}
}
You should check the state of invfile during read to ensure no failures.
Should have count<max_array; rather than count>max_array;
Your for condition doesn't seem right, plus you got a semicolon that shouldn't be there at the end of the for
for (int count = 0; count>max_array; count++);
The test will return false at the first iteration
for (int count = 0; count<max_array; count++)