I am new to C++, and am trying to perform a matrix multiplication taking data from a file. But I am unable to get the multiplication part. Someone please help me to fix this.
While am trying to do the multiplication of 2 matrices but am unable to get the output.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
int d[3][3],e[3][3],f[3][3];
int i=0;
int x=0;
int j=0;
string a[20];
string b[20];
string c[20];
ifstream myfile;
myfile.open("numeric.txt");
while(getline (myfile,line))
{
if(line!=" ")
{
a[x]=line;
b[x]=line;
cout<<a[x]<<endl;
x++;
}
}
cout<<"first Matrix"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<=4;j++)
{
cout<<a[i][j]<<"";
}
cout<<endl;
}
cout<<"Second Matrix"<<endl;
for(i=1;i<4;i++)
{
for(j=0;j<6;j++)
{
cout<<b[i][j]<<"";
}
cout<<endl;
}
cout<<"Multiplication"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<=3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
cout<<"Multiplication Result"<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Here is a complete example on how you write (fixed size) matrices to a file and how you can build them reading from that file:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main() {
const size_t matrixSize = 3;
//
ofstream matrixOutput("matrix.txt");
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
matrixOutput << j*i << ' ';
}
matrixOutput << '\n';
}
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
matrixOutput << j*i * 2 << ' ';
}
matrixOutput << '\n';
}
matrixOutput.close();
//
ifstream matrixData("matrix.txt");
size_t matrixInput[matrixSize][matrixSize];
size_t matrixInput2[matrixSize][matrixSize];
size_t position = 0;
size_t number = 0;
while (matrixData >> number) {
const size_t matrixNumber = size_t(floor(position / (matrixSize*matrixSize)));
const size_t row = size_t(floor(position / matrixSize)) % matrixSize;
switch (matrixNumber) {
case 0:
matrixInput[row][position % 3] = number; break;
case 1:
matrixInput2[row][position % 3] = number; break;
}
position++;
}
matrixData.close();
cout << "Matrices: " << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput[i][j] << ' ';
}
cout << endl;
}
cout << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput2[i][j] << ' ';
}
cout << endl;
}
cout << endl;
cout << "Matrices multiplication: " << endl;
for (size_t i = 0; i < matrixSize; i++) {
for (size_t j = 0; j < matrixSize; j++) {
cout << matrixInput[i][j] * matrixInput2[i][j] << ' ';
}
cout << endl;
}
// ...
}
Note: if you want you can write the matrix size to the file too, so you can retrieve it later and build custom size matrices.
Related
#include <iostream>
#include<fstream>
using namespace std;
int main() {
int a = 1;
if (a == 1) {
int a[1][1];
for (int i = 0; i <= 1; i++) {
for (int j = 0; j <= 1; j++) {
cin >> a[i][j];
}
}
cout << endl;
for (int k = 0; k <= 1; k++) {
for (int l = 0; l <= 1; l++) {
cout << a[k][l] << " ";
}
cout << endl;
}
}
return 0;
}
In this program if we enter input as :
1
2
3
4
it gives output :
1 3
3 1
it should give output as:
1 2
3 4
Please help, I am a beginner.
I am coding in code blocks.
Try this
int main()
{
int arr[2][2]; // declares a 2x2 array
cout << "Enter integers : " << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> arr[i][j]; //inserts at the index i and j in the array
}
}
cout << "Display array : " << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << arr[i][j] << endl; /*displays the value at
index i and j in the array*/
}
}
}
I get a NxM sized matrix and I have to find the max value, the number of max values and the lines that contain it.
I tired using three for{for{}} loops, but it took too long. This method seems to work for small inputs, but when I try it with a 1000x1000 matrix, it finishes before it even takes all the input.
I realise this may be too much of a noob question, but I couldn't find anything else.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
for(int i=0; i<n; i++)
{
for(int p=0; p<m; p++)
{
cin >> vekt[p];
}
for(int j=0; j<m; j++)
{
if(vekt[j] == crnt)
{
lines[cnt] = i + 1;
cnt += 1;
}
if(vekt[j] > crnt)
{
crnt = vekt[j];
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
EDIT : not using vector or [n] was just easier... I simply saved it to a variable and used a bool:
int main()
{
int n, m;
int crnt{-51}, cnt{0};
cin >> n >> m;
int vekt[m];
int lines[n];
int inp;
bool inLine;
inLine = false;
for(int i=0; i<n; i++)
{
inLine = false;
for(int j=0; j<m; j++)
{
cin >> inp;
if(inp == crnt && inLine == false)
{
lines[cnt] = i + 1;
cnt += 1;
inLine = true;
}
if(inp > crnt)
{
crnt = inp;
lines[0] = i + 1;
cnt = 1;
}
}
}
cout << cnt;
for(int i=0; i<cnt; i++)
{
cout << " " << lines[i];
}
return 0;
}
This cut the time by enough so that I went under the limit.
int vekt[m]; is not standard C++, it is a variable length array (which some compilers allow as extension). Use std::vector instead.
That would also fix the bug you currently have: If cnt >= n (i.e. if you find more maxima than the matrix has lines), you will go out of bounds of lines and your program will most likely crash (although anything could happen), which is more likely to happen with larger matrices.
You can do this instead:
Declaration and initialization:
std::vector<int> linesWithMaxima;
When you find another value equal to the current maximum:
linesWithMaxima.push_back(i+1);
When you find a new maximum (larger than current):
linesWithMaxima.clear();
linesWithMaxima.push_back(i+1);
Note that this will list a line with multiple (identical) maxima multiple times. If you want to avoid duplicates, you can either check that you have not already added the current line (linesWithMaxima.back() != i+1) or use std::sort, std::unique and std::vector::erase.
Other than that your code looks fine. I would recommend naming the loop indices better (line instead of i etc.) and possibly merging the p and j loop because separating them seems to have no purpose. And if you want the most negative integer, use std::numeric_limits<int>::lowest().
Check this realization, without STL and vectors:
void input_matrix(int **&matrix, int &lines, int &columns)
{
int m = 0, n = 0;
cout << "input lines count:";
cin >> m;
cout << "input rows count:";
cin >> n;
matrix = new int *[m];
for(int i = 0;i < m;i++)
matrix[i] = new int[n];
cout << endl << "input matrix:" << endl;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> matrix[i][j];
lines = m;
columns = n;
}
void print_matrix(int **&matrix, int &lines, int &columns)
{
for(int i = 0; i < lines; i++)
{
for(int j = 0; j < columns; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
int find_max(int **matrix, int lines, int columns, int &max_count)
{
int max = INT_MIN;
max_count = 0;
for(int i = 0; i < lines; i++)
for(int j = 0; j < columns; j++)
{
if(matrix[i][j] > max)
{
max = matrix[i][j];
max_count = 1;
}
else
if(matrix[i][j] == max)
++max_count;
}
return max;
}
int main()
{
int **matrix = nullptr;
int m=0, n=0, count=0;
input_matrix(matrix, n, m);
cout << endl;
print_matrix(matrix, n, m);
cout << endl;
int max = find_max(matrix, n, m, count);
cout << "max=" << max << " count=" << count << endl;
for(int i = 0; i < n; i++)
delete[]matrix[i];
delete []matrix;
}
As requested by mister Max Langhof I would also like to propose a more modern solution, based on the std::vector container, which does not need pointers and manual memory management. It's a simple class matrix:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;
class matrix
{
private:
vector<vector<int>> m_data;
public:
matrix(int cols, int rows)
{
m_data.resize(cols);
for(auto &r : m_data)
r.resize(rows);
}
int max_element()
{
int max = INT_MIN;
for(auto &row: m_data)
{
auto maxinrow = *std::max_element(row.begin(), row.end());
if(maxinrow > max)
max = maxinrow;
}
return max;
}
int element_count(int elem)
{
int count = 0;
for(auto &row : m_data)
count += std::count_if(row.begin(), row.end(), [elem](int a){return a == elem;});
return count;
}
friend istream& operator>>(istream &os, matrix &matr);
friend ostream& operator<<(ostream &os, matrix &matr);
};
Input and output operators could be realized like this:
istream& operator>>(istream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cin >> matr.m_data[i][j];
cout << endl;
}
return os;
}
ostream& operator<<(ostream &os, matrix &matr)
{
for(int i = 0; i < matr.m_data.size(); i++)
{
for(int j = 0; j < matr.m_data[i].size(); j++)
cout << matr.m_data[i][j] << " ";
cout << endl;
}
return os;
}
And a sample of using of this matrix:
int main()
{
int m = 5, n = 4;
matrix matr(m, n);
cout << "input matrix:" << endl;
cin >> matr;
cout << endl << matr;
int max = matr.max_element();
cout << "max: " << max << " count:" << matr.element_count(max) << endl;
}
Checkout something like this
#include <iostream>
#include <set>
#include <vector>
int main() {
int rowsNo, columnsNo;
std::cin >> rowsNo >> columnsNo;
std::vector<int> matrix(rowsNo*columnsNo);
//Creating matrix
for(auto row = 0; row < rowsNo; ++row) {
for (auto column = 0; column < columnsNo; ++column)
std::cin >> matrix[row*columnsNo + column];
}
auto maxValue = -51;
//Finding positions of maximums
std::set<int> linesWithMaxValue;
for (auto position = 0; position < matrix.size(); ++position) {
if(matrix[position] == maxValue)
linesWithMaxValue.insert(position / columnsNo);
else if(matrix[position] > maxValue) {
linesWithMaxValue.clear();
maxValue = matrix[position];
linesWithMaxValue.insert(position / columnsNo);
}
}
//Print info
const auto numberOfMaxValues = linesWithMaxValue.size();
std::cout << "Number of maxiums: " << numberOfMaxValues << std::endl;
std::cout << "Lines that contains maximum:";
for (const auto& lineId : linesWithMaxValue)
std::cout << " " << lineId;
return 0;
}
I am trying to get the program to run from 4 column of the seasons, and 2 columns for years 2016 and 2017. The input is rainfall for both years for each season. It is allowing me to enter numbers for times for winter and then stops and it is not calculating right. Any help as to what I am doing wrong?
#include <iostream>
#include <string>
using namespace std;
void Read(double rainfall[][4], int row);
void Calculate(double rainfall[][4], int row);
void Write(double rainfall[][4], int row);
int main()
{
double rainfall[2][4];
int row = 2;
Read(rainfall, row);
Calculate(rainfall, row);
Write(rainfall, row);
}
void Read(double rainfall[][4], int row)
{
for (int i = 0; i < row - 1; i++)
{
if (i == 0)
cout << "Enter rainfall for Winter: " << endl;
else if (i == 1)
cout << "Enter rainfall for Spring: " << endl;
else if (i == 2)
cout << "Enter rainfall for Summer: " << endl;
for (int j = 0; j < 2; j++)
{
cout << j + 1 << " : " << endl;
cin >> rainfall[i][j];
}
}
}
void Calculate(double rainfall[2][4], int row)
{
int i, j;
double row_sum;
for (i = 0; i < row; i++)
{
row_sum = 0;
for (j = 0; j < 4; j++)
{
row_sum = row_sum + rainfall[i][j];
}
rainfall[i][4] = row_sum;
}
double col_sum;
for (j = 0; j < 4; j++)
{
col_sum = 0;
for (i = 0; i < row - 1; i++)
{
col_sum = col_sum + rainfall[i][j];
}
rainfall[2][j] = col_sum;
}
}
void Write(double rainfall[][4], int row)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < 4; j++)
cout << rainfall[i][j] << " ";
cout << endl;
}
}
Change this line
for (int i = 0; i < row - 1; i++)
to
for (int i = 0; i < row; i++)
In C++, you should use std::vector or std::array instead and avoid C style arrays, that way you get better help when you go out-of-bounds with your array which I think is happening in more places than one.
I want to print a chart by taking integers from console. I have come up with this syntax. Stuck at a conditional statement.
int main() {
int array[10];
int num;
int size = 0;
for(int i = 0; i < 10; i++)
{
cin >> num;
if(num == 0)
{
break;
}
array[i] = num;
size++;
}
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(*something goes here*)
cout << "*";
else
cout << " ";
}
cout << endl;
}
return 0;
}
Try this
#include <iostream>
using namespace std;
#define MAX 100
int main() {
int values[MAX];
int size = 0;
while (true) {
int num;
cin >> num;
if (num == 0) break;
else values[size++] = num;
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < values[i]; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
After trying a lot of times and thinking again and again.. It feels like a frustrated person.
I'm here to get some suggestions from you guys..
Actually I'm trying to find the maximum of each ROW and COLUMN.
So by using divide and conquer technique, I write two separate functions one for finding max of each row and store it to row vector that i used as an argument. Respectively for columns.
void maxValuesR(int a[][cols], int rv[], int row)
void maxValuesC(int a[][cols], int cv[], int row)
PROBLEM: The code is not even compile, I just don't understnd the errors..
Please Help..
I Really Need Your Help Here!
The code is as follow:
#include <iostream>
using namespace std;
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << "Enter Element: ";
cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << a[i][j] << "\t";
}
cout << endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][[i];// show error here => expected a '{' introducing lambda body
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
cout << "Fill Array_1. " << endl;
getData(a, rows);
cout << "Array_1." << "\n\n";
printData(a, rows); cout << endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
To clarify the compile errors:
You forgot the include (or didn't write it here?) #include <iostream>
You didn't specify the namespace for cin, cout and endl (they are in std namespace)
You had a superfluous "[" in the statement a[j][[i], by all likelihood you wanted to write a[j][i]
The compiling code looks like this:
#include <iostream>
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << "Enter Element: ";
std::cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << a[i][j] << "\t";
}
std::cout << std::endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
std::cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][i];
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
std::cout << "Fill Array_1. " << std::endl;
getData(a, rows);
std::cout << "Array_1." << "\n\n";
printData(a, rows);
std::cout << std::endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
std::cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
Can't tell whether it produces the output you want, though, because you didn't specify any example input (let alone the corresponding expected output)...