I need to create a program that computes the external elements of a matrix. The matrix should be set by the user.
My idea is to create a first part of the program where the user can write the elements of the matrix, after that this matrix is given to a function that sets the internal elements to 0 and than gives it back to the main() and then launch another function that computes the sum of all elements.
The problem is that I am not able to pass to the function the matrix that's declared in the main {}.
I am almost sure that I need to use pointers, however I have no idea how to use them in this situation... Could you please help?
That's the code I have written so far:
#include <iostream>
#define MAX 10
using namespace std;
int zeroMatrix (int mat [][10], int, int);
int main()
{ //ask the user the number of rows and columns of the matrix.
int rows,cols;
cout << "please insert the number of rows: ";
cin >> rows;
cout << "insert the number of columns: ";
cin >> cols;
//accepting values
int matrix [rows] [cols];
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
cout <<"insert the element A(" << i <<","<< j << ") of the matrix " ;
cin >> matrix[i][j];
}
}
zeroMatrix (matrix [rows][cols]);
}
//change the previous matrix into a new matrix with the internal elements = 0
int zeroMatrix (int mat [][10], int rows, int cols )
{
for (int i=1; i<rows-1; i++)
{ for (int j=1; j<cols-1 ; j++)
{
mat[i][j] = 0;
}
}
}
#include <iostream>
using namespace std;
void zeroMatrix (int **mat, int, int);//makes the inner elements zero
int sumExternals(int **mat, int rows, int cols);//sums the external elements without
//using zeroMatrix
void printMatrix(int **mat, int, int);//prints a matrix on the console window
int main()
{ //ask the user the number of rows and columns of the matrix.
int rows,cols;
cout << "please insert the number of rows: ";
cin >> rows;
cout << "insert the number of columns: ";
cin >> cols;
//accepting values
int **matrix = new int*[rows];
for(int i=0; i<rows; ++i)
matrix[i] = new int[cols];
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
cout <<"insert the element A(" << i <<","<< j << ") of the matrix " ;
cin >> matrix[i][j];
}
}
printMatrix(matrix,rows,cols); //print the matrix
cout<<sumExternals(matrix,rows,cols)<<endl; //get the sum of the external elements
//Just so you can see how to proper call the function zeroMatrix
zeroMatrix(matrix,rows,cols);
printMatrix(matrix,rows,cols);
}
//changes the previous matrix into a new matrix with the internal elements = 0
void zeroMatrix (int **mat, int rows, int cols )
{
for (int i=1; i<rows-1; i++)
for (int j=1; j<cols-1; j++)
mat[i][j] = 0;
}
//calculates the sum of the external elements of a matrix
int sumExternals(int **mat, int rows, int cols)
{
int sum = 0;
for(int j=0;j<cols;++j)
{
sum+=mat[0][j]; // adds the upper bound elements to sum
sum+=mat[rows-1][j]; // adds the lower bound elements to sum
}
//Take caution not to add elements which are already taken into account
for(int i=1;i<rows-1;++i)
{
sum+=mat[i][0]; //adds the left bound elements to sum
sum+=mat[i][cols-1]; //adds the right bound elements to sum
}
return sum;
}
void printMatrix(int **matrix, int rows, int cols)
{
for(int i=0;i<rows;++i)
{
for(int j=0;j<cols;++j)
cout<<matrix[i][j]<<" ";
cout<<endl;
}
}
I added the function sumExternals which calculates the sum of the external matrix elements but without using your zeroMatrix function.
Use vector instead of array. Also, there's no need for two separate functions. One to find the sum of external elements and other to set internal elements to 0. You can achieve both tasks in the same function. Refer function external_elements_sum written below.
# include <iostream>
# include <vector>
using namespace std;
int external_elements_sum(vector<vector<int> >&arr) // function that finds sum of external elements and set internal elements to 0
{
int sum=0;
for(int i=0; arr.size()>0 && i<arr[i].size();i++)
{
for(int j=0;j<arr[i].size();j++)
{
if(i==0 || i==arr.size()-1 || j==0 || j==arr[i].size()-1) // external elements
sum+=arr[i][j];
else arr[i][j]=0; // internal elements
}
}
return sum;
}
int main() {
vector< vector<int> >arr;
int i,j,number,rows=3,cols=4;
for(i=0;i<rows;i++)
{
vector<int>v;
for(j=0;j<cols;j++)
{
cin>>number;
v.push_back(number);
}
arr.push_back(v);
}
int sum = external_elements_sum(arr);
for(i=0;i<arr.size()>0 && arr[0].size();i++) // arr.size()>0 to check corner case like if row is 0
{
for(j=0;j<arr[i].size();j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
cout<<"Sum of externale elements is: "<<sum;
return 0;
}
Input:
1 2 3 4
5 6 7 8
2 5 1 4
Output:
1 2 3 4
5 0 0 8
2 5 1 4
Sum of externale elements is: 35
Related
I am trying to find the sum of the elements of the left diagonal of a 2D matrix. But it shows the following error:
.\sum_matrix.cpp: In function 'int main()':
.\sum_matrix.cpp:44:33: error: invalid conversion from 'int' to 'int (*)[10]' [-fpermissive]
cout<<sum_diagonal(arr[MAX][MAX]);
~~~~~~~~~~~~^
.\sum_matrix.cpp:7:5: note: initializing argument 1 of 'int sum_diagonal(int (*)[10])'
int sum_diagonal(int arr_[][MAX]){
^~~~~~~~~~~~
This is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
//adding the elements of the left diagonal
int sum_diagonal(int arr_[][MAX]){
int sum = 0;
for(int i = 0; i<MAX; i++){
for(int j = 0; j<MAX; j++){
if(i == j){
sum += arr_[i][j];
}
}
}
return sum;
}
int main()
{
int arr[MAX][MAX];
//entering array elements
cout<<"Enter the values of rows and columns of array:\n";
for(int i = 0; i<MAX; i++){
for(int j = 0; j<MAX; j++){
cout<<"arr["<<i<<"]["<<j<<"] = ";
cin>>arr[i][j];
}
}
//displaying array elements
cout<<"The array is:\n";
for(int i = 0; i<MAX; i++){
for (int j = 0; i < MAX; j++)
{
cout<<"\t"<<arr[i][j];
}
}
cout<<endl;
//sum of the left diagonal
cout<<"Sum of diagonal elements: ";
cout<<sum_diagonal(arr[MAX][MAX]);
return 0;
}
I looked up into several websites but couldn't figure it out.
Any kind of help will be appreciated.
There were a few things in your code:
(not a bug) avoid using namespace std;
There was a typo i changed for j in the 2nd loop
(improvement) Sum of matrix was O(N^2) unnecessarily, made O(N)
(not a bug) Printing as a matrix (and not in the same line)
Passing matrix only needs the variable name not matrix size
So the code became
#include <iostream>
const int MAX = 10;
//adding the elements of the left diagonal
int sum_diagonal(int arr_[MAX][MAX]){
int sum = 0;
for(int i = 0; i<MAX; i++){
sum += arr_[i][i];
}
return sum;
}
int main()
{
int arr[MAX][MAX];
//entering array elements
for(int i = 0; i<MAX; i++){
for(int j = 0; j<MAX; j++){
std::cin >> arr[i][j];
}
}
//displaying array elements
std::cout<<"The array is :\n";
for(int i = 0; i<MAX; i++){
for (int j = 0; j < MAX; j++)
{
std::cout<< arr[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
//sum of the left diagonal
std::cout<<"Sum of diagonal elements: ";
std::cout<< sum_diagonal(arr);
return 0;
}
Godbolt: https://godbolt.org/z/TG1exK8Yn
Runs as (I changed MAX=4 in the example to simplify)
Program stdout
The array is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sum of diagonal elements: 34
I have ruby version of this program & trying to do the same in C++
The input must be:
2 # Number of pairs
562 -881 # First pair
310 -385 # Second pair
And output:
-319
-75
It's working fine with one array of 2 numbers and breaks if pairs > 2. What's wrong in my for loops?
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum << endl;
}
return 0;
}
Thanks for any help!
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
}
In first iteration values are entered in arr and again in second iteration previous values are overwritten (similar in next iterations if any ). This is the problem .
Solution -
#include <iostream>
using namespace std;
int main() {
int iter;
cin >> iter;
int arr[2];
int sum[iter]; // declare sum as array with iter number of elements
for(int i=0;i<iter;i++){
sum[i]=0; // initialize elements of sum to 0
}
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n]; // take iput
sum[i]+=arr[n]; // add numbers and store in sum
}
}
for (int i=0; i<iter; i++) {
// Get the sum of numbers
cout << sum[i] << endl; // print values in sum after taing all inputs
}
return 0;
}
You're overwriting the contents of arr on each iteration of the loop. Try something like this (live demo here):
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int iter;
cin >> iter;
int arr[2];
for (int i=0; i<iter; i++) {
for (int n=0; n<2; n++) {
// Enter numbers
cin >> arr[n];
}
for (int num=0; num<2; num++) {
sum+=arr[num];
}
cout << sum << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main (int argc, char ** argv)
{
int c;
int distance=0;
int largestdistance=0;
int sum=0;
cin >> c;
int point[c][2];
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
cin >> point[i][j];
}
}
cout << point[2][0] << " ";
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]);
}
if (sum > largestdistance){
largestdistance=sum;
}
cout << '\n';
return 0;
}
}
This program prints out the value of the absolute value of the first row first number minus the second row first number added to the absolute value of the first row second number minus the second row second number. I was wondering that how do I make the program so that it automatically does the sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]) for all point[][] all the way up to sum += abs(point[c-1][0]-point[c][0])+abs(point[c-1][1]-point[c][1]).
This would be a lot clearer if you introduced a point type:
struct Point {
int x, y;
};
int manhattan_dist(const Point& p, const Point& q) {
return abs(p.x - q.x) + abs(p.y - q.y);
}
Armed with that, it's a lot easier to loop:
int sum = 0;
for (int i = 0; i < c - 1; ++i) { // stop before c-1, so i and i+1 are valid
sum += manhattan_dist(points[i], points[i+1]);
}
Btw int point[c][2]; is non-standard code because c is not a compile-time constant. You need to dynamically allocate the array:
Point* points = new Point[c];
or, preferably:
std::vector<Point> points(c);
I need a function that can take to according to the x-axis of symmetry of the matrix.
input (matrix[i][j]):
1 2 3
4 5 6
7 8 9
output (matrix[i][j]):
7 8 9
4 5 6
1 2 3
How can i do this on the same matrix?
How should I write the inverse function?
void inverse(.......)
{
..
..
..
}
int main(){
int **matrix, i, j, k, row, column;
cout << "Row and column:" ;
cin >> row >> column;
matrix = new int*[row];
for (i=0; i<row; ++i){
matrix[i] = new int[column];
}
cout << "input elements of matrix: " << endl;
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cin >> *(*(matrix+i)+j);
}
}
inverse (........);
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cout << *(*(matrix+i)+j);
}
cout << endl;
}
return 0;
}
In this particular case, you can modify the loop to print the matrix backwards:
for(i = 0; i < row; i++) {
->
for(i = row - 1; i >= 0; i--) {
But if you want to actually do something to the data, my suggestion would be to refactor this code to use std::vector.
std::vector<std::vector<int> > matrix(numberOfRows, std::vector<int>(numberOfColumns));
// You can use std::vector<std::valarray<int> > matrix; alternatively.
You would then flip it simply by using an STL function:
std::reverse(matrix.begin(), matrix.end());
Edit:
Well, if you don't want to use std::vector for the time being and for this particular case, what you would do is this:
void flipMatrix(int** matrix, int rows, int columns) {
int middle = rows/2; // I expect it to truncate for an odd number of rows.
// Temporary row for swapping
int* tempRow;
for (int i = 0; i < middle; i++) {
// swap rows
tempRow = matrix[i];
matrix[i] = matrix[rows - i - 1];
matrix[rows - i - 1] = tempRow;
}
}
i want the user to input values in a 2 dimensional array. he can also choose the size of each dimension
int main()
{
int x;
int y;
int *p;
cout<<"How many items do you want to allocate in dimension x?"<<endl;
cin>>x;
cout<<"How many items do you want to allocate in dimension y?"<<endl;
cin>>y;
p = new int[x,y];
for(int i=0; i<x; i++) //This loops on the rows.
{
for(int j=0; j<y; j++) //This loops on the columns
{
int value;
cout<<"Enter value: "<<endl;
cin>>value;
p[i,j] = value;
}
}
drill1_4 obj;
obj.CopyArray(p,x,y);
}
and then, ill output the two dimensional array via
class drill1_4
{
public:
void CopyArray(int*,int,int);
private:
int *p;
};
void drill1_4::CopyArray(int* a,int x,int y)
{
p = a;
for(int i=0; i<x; i++) //This loops on the rows.
{
for(int j=0; j<y; j++) //This loops on the columns
{
cout << p[i,j] << " ";
}
cout << endl;
}
getch();
}
logic seems fine, but lets say, if the user enters the numbers, the array should look like this
1 2
3 4
but instead, it looks like this:
3 3
4 4
The array is not displaying it correctly.
I don't know if you figured out the answer to your problem. The comments above tell you where you went wrong. Here is a possible answer.
#include <cstdio>
#include <iostream>
using namespace std;
class drill1_4
{
public:
void CopyArray(int**,int,int);
private:
int **p;
};
void drill1_4::CopyArray(int** a,int x,int y)
{
p = a;
for(int j=0; j<y; ++j) //This loops on the rows.
{
for(int i=0; i<x; ++i) //This loops on the columns
{
cout << p[i][j] << " ";
}
cout << endl;
}
cin.get();
}
int main()
{
int x;
int y;
int **p;
cout<<"How many items do you want to allocate in dimension x?"<<endl;
cin>>x;
cout<<"How many items do you want to allocate in dimension y?"<<endl;
cin>>y;
p = new int*[x];
for (size_t i = 0; i < x; ++i)
p[i] = new int[y];
for(int j=0; j<y; ++j) //This loops on the rows.
{
for(int i=0; i<x; ++i) //This loops on the columns
{
int value;
cout<<"Enter value: "<<endl;
cin>>value;
p[i][j] = value;
}
}
drill1_4 obj;
obj.CopyArray(p,x,y);
}
I am not sure I understood what you meant by x-dimmension. If you meant x running horizontally than I think that i and j for-loops shout be reversed as x will represent columns.