Static array and Dynamic array in a function - c++

I have a question as below C++ code.
this is the code(No function) that can successful execute.
#include <iostream>
using namespace std;
int main()
{
int size_3 = 3;
//arr1 is a static array
int arr1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
//arr2 is a dynamic array
int** arr2 = new int* [size_3];
for (int i = 0; i < size_3; i++) {
arr2[i] = new int[size_3];
}
int val = 9;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
arr2[i][j] = val--;
}
}
cout << "Elements in matrix 1: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Elements in matrix 2: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
int** prod_arr = new int* [size_3];
for (int i = 0; i < size_3; i++) {
prod_arr[i] = new int[size_3];
}
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
prod_arr[i][j] = 0;
for (int k = 0; k < size_3; k++) {
prod_arr[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
cout << "Elements in the product of 2 matrices: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << prod_arr[i][j] << " ";
}
cout << endl;
}
}
However, I am gonna to use the function for the multiplication of the 2 matrices.
how could I move it to function, since the first array is static array, the second array is dynamic array.
I have try different way to use pointer , pass-by reference in the function, but still can't work.
My invalid code as below.
#include <iostream>
using namespace std;
int** function(int farr1, int farr2, int size3) {
int** prod_arr = new int* [size3];
for (int i = 0; i < size3; i++) {
prod_arr[i] = new int[size3];
}
for (int i = 0; i < size3; i++) {
for (int j = 0; j < size3; j++) {
prod_arr[i][j] = 0;
for (int k = 0; k < size3; k++) {
prod_arr[i][j] += farr1[i][k] * farr2[k][j];
}
return prod_arr[i][j];
}
}
}
int main()
{
int size_3 = 3;
//arr1 is a static array
int arr1[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
//arr2 is a dynamic array
int** arr2 = new int* [size_3];
for (int i = 0; i < size_3; i++) {
arr2[i] = new int[size_3];
}
int val = 9;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
arr2[i][j] = val--;
}
}
cout << "Elements in matrix 1: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Elements in matrix 2: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << arr2[i][j] << " ";
}
cout << endl;
}
cout << endl;
int** prod_arr = function(farr1, farr2, size_q3);
cout << "Elements in the product of 2 matrices: " << endl;
for (int i = 0; i < size_3; i++) {
for (int j = 0; j < size_3; j++) {
cout << prod_arr[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
I want to use the function to execute the code.
I got 2 array, one is static and another is dynamic,
How to use pointer and pass to function with this different arrays.
Thanks a lot for your help.

Some C++ array examples to get you started :
A 2D dynamically array can be modeled as std::vector<std::vector<int>>
#include <array> // static array
#include <vector> // dynamic array, can resize at runtime
#include <iostream>
// https://en.cppreference.com/w/cpp/container/array
// accept a modifiable static array (content can be changed
// the & means by reference, the array will not get copied
// https://isocpp.org/wiki/faq/references
void func1(std::array<int, 4>& values)
{
values[2] = 3;
}
// array cannot be modified in body of func2 only used : const
void func2(const std::array<int, 4>& values)
{
std::cout << values[2] << "\n";
}
// https://en.cppreference.com/w/cpp/container/vector
// return a dynamically allocated array of integers
// it will have a size of 5 when returned
std::vector<int> get_values()
{
return std::vector<int>{1, 2, 3, 4, 5};
}
int main()
{
auto values = get_values();
values.push_back(6); // add another value
// https://en.cppreference.com/w/cpp/language/range-for
// prefer to use those if you don't need indices
// (which is not as often as you think)
for (const int value : values)
{
std::cout << value << " ";
}
return 0;
}

Related

Square matrix in c ++

I did the above code to calculate the matrix of a square matrix but it does not work, can someone explain the error to me please
#include <iostream>
using namespace std;
int main() {
int M[3][3]={{2, 4, -6}, {1, 5, 3}, {1, 3, 2}};
int n, mult;
n=3;
cout << "Matrix: " << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << M[i][j] << "\t";
cout << "\n";
}
for (int i=0; i<n; i++){
for (int j=i+1; j<n; j++){
mult=M[j][i]/M[i][i];
for (int k=i; k<n; k++){
M[j][k]=M[j][k]-mult*M[i][k];
}
}
}
cout << "Echelon matrix: " << endl;
for (int i=0; i<n; i++){
for (int j=i+1; j<n; j++){
for(int k=i; k<n; k++){
cout << M[j][k] << "\t";
cout << "\n";
}
}
}
return 0;
}
In this code, I replaced int by double, even if that, for this particular matrix, it would work with int.
The main problem was that the output of the result was broken, 3 loops when two only are needed.
Note that you don't check that the Gauss pivot M[i][i] is not null. The code should be completed to handle this case.
Output:
Matrix:
2 4 -6
1 5 3
1 3 2
Echelon matrix:
2 4 -6
0 3 6
0 0 3
#include <iostream>
//using namespace std;
int main() {
double M[3][3]={{2, 4, -6}, {1, 5, 3}, {1, 3, 2}};
int n = 3;
std::cout << "Matrix: " << std::endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
std::cout << M[i][j] << "\t";
std::cout << "\n";
}
for (int i = 0; i < n; i++){
for (int j = i+1; j < n; j++){
double mult = M[j][i]/M[i][i];
for (int k = i; k < n; k++){
M[j][k] = M[j][k] - mult*M[i][k];
}
}
}
std::cout << "Echelon matrix: " << std::endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << M[i][j] << "\t";
}
std::cout << std::endl;
}
return 0;
}

Add the Edges of 2D array and return its answer

What's wrong with my code
I Have to add all the edge values of the 2D Array.
The Function is not returning what I want. Its returning garbage value.
Program Req Output : Add all the edges value of the 2D Array and return its answer.
You are not allowed to use Vector etc.
Here is my Code :
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
int k = 0;
int l = 0;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= cols; j++)
{
if (i == 1 || i == rows || j == 1 || j == cols)
{
sum = arr[k][l];
totalOfEdges = sum + totalOfEdges;
}
l++;
}
k++;
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}
My Output :
Leaving the Correct Code in Case Any one need it .
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (i == 0 || i == (rows-1) || j == 0 || j == (cols-1))
{
sum = arr[i][j];
totalOfEdges = sum + totalOfEdges;
}
}
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
cout << "--------" << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}

How to fill a 2D through input and then read back as output in a C++. Here is the code which I wrote. I gives wrong output.I am a beginner

#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*/
}
}
}

Nested for loop not looping through second array

How do I get the second array to be properly looped through? It is a simple matrix multiplication operation (using Visual Studio 2019) and arr is being looped through, but arr2 isn't being looped through completely. Only the first 2 elements are being multiplied by all elements of arr.
#include <iostream>
using namespace std;
int main() {
int r1 = 2, c1 = 3, r2 = 3, c2 = 3;
int** arr = new int* [r1];
for (int i = 0; i < c1; i++) {
arr[i] = new int[c1];
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
arr[i][j] = j;
}
}
int** arr2 = new int*[r2];
for (int i = 0; i < c2; i++) {
arr2[i] = new int[c2];
}
for (int i = 0; i < c2; i++) {
for (int j = 0; j < r2; j++) {
arr2[i][j] = j;
}
}
int** arr3 = new int*[r1];
for (int i = 0; i < c2; i++) {
arr3[i] = new int[c2];
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
arr3[i][j] = 0;
}
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int g = 0; g < c1; g++) {
arr3[i][j] += arr[i][g] * arr2[g][j];
cout << "[" << i << "][" << g << "] " << arr[i][g] << "\tX\t" << "[" << g << "][" << j << "] " << arr2[g][j] << " => " << arr3[i][j] << endl;
}
}
}
cout << "\n" << endl;
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
cout << "New Array Element: [" << i << "][" << j << "] => " << arr3[i][j] << endl;
}
}
return 0;
}
You make the same basic mistake in all of your loops -- that mistake being that you are not iterating over the rows correctly.
You are using the column count when you should be using the row count:
int** arr = new int* [r1];
for (int i = 0; i < c1; i++) { // <-- This should be i < r1, not i < c1;
arr[i] = new int[c1];
}
Second, you could have written a function to lessen the chance of error, and also have a better chance of finding bugs like this:
int **createArray(int rows, int cols)
{
int** arr = new int* [rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = j;
}
}
return arr;
}
int main()
{
int r1 = 2, c1 = 3, r2 = 3, c2 = 3;
int** arr = createArray(r1, c1);
int** arr2 = createArray(r2,c2);
int** arr3 = createArray(r1,c2);
//...
}
Now the creation code is not repeated over and over again, plus the issue of using the wrong variables becomes minimized, if not eliminated.
Having said this, this way of creating 2D arrays is one of the worst ways of doing this. Right now, your code has memory leaks (it still is considered a leak, even though the program will terminate -- memory tools such as valgrind and others would indicate the errors as soon as your program exits).
Ideally, you would use a container class such as std::vector<int> to handle the dynamic memory management automatically.
But even if this is an exercise where you must use int**, it is still a very bad way of creating two-dimensional arrays under those constraints. Here is an answer that goes in detail about this issue, why it's bad, and how it can be alleviated.

Using Multidimensional Arrays to Keep Track of Indices in C++

I'm working on a project where I need to sort an array from least to greatest, but save the values of the indices. For example, with the array {2, 7, 8, 1, 3}, the sorted indices would be {3, 0, 4, 1, 2}. I thought that I could use a two dimensional array to accomplish this; I would add the index to each component, sort the array, then retrieve the original index from the second element. It hasn't been working for me as well as I hoped though, I have my current code below and it keeps giving me a segmentation fault. I don't know what I'm doing wrong, but I'm assuming its something in my for loops.
#include <iostream>
#include <algorithm>
using namespace std;
const int SIZE = 7;
int main()
{
int intArray[SIZE] = {5, 3, 32, -1, 1, 104, 53};
int i, j, k, l = 0;
int temp[SIZE][2];
//fills multidimensional array temp with data from intArray or index #
for(i = 0; i < 7; i++){
for(j = 0; j < 2; j++){
switch (j)
{
case '0':
temp[i][j] = *intArray;
break;
case '1':
temp[i][j] = i;
break;
}
}
}
sort(intArray, intArray + SIZE);
//prints each component of temp individually
cout << "Sorted Array looks like this." << endl;
for (k = 0; i < 7; i++){
for (l = 0; j < 2; i++){
cout << &temp[k][l] << endl;
}
}
return 0;
}
The following loop is much simpler and does what it should:
for(i = 0; i < 7; i++){
temp[i][0] = intArray[i];
temp[i][1] = i;
}
One error in your code is the line
temp[i][j] = *intArray;
This always assigns the 1st element of intArray.
The thing that causes the segmentation fault is probably the & in the output statement, just remove it.
Aside from that, I agree with the recommendation in the comment by RyanP.
Use std::map. The code will be the easiest. Test on cpp.sh
#include <iostream>
#include <map>
int main()
{
std::map<int,int>arr = {{5,0}, {3,1}, {32,2}, {-1,3}, {1,4}, {104,5}, {53,6}};
for(auto&x:arr) std::cout << x.first << " - > " << x.second << std::endl;
return 0;
}
I ended up using what Frank Puffer said and chose to use a simple bubble sort instead of using any of the built in functions. Here is a link to what my final program looked like http://ideone.com/cpEgGA
#include <iostream>
#include <algorithm>
using namespace std;
const int SIZE = 7;
int main()
{
int intArray[SIZE] = {5, 3, 32, -1, 1, 104, 53};
int i, j, k, l, m = 0;
int temp2[SIZE][2];
int indices[SIZE] = {};
for(i = 0; i < 7; i++){
temp2[i][0] = intArray[i];
temp2[i][1] = i;
}
cout << "Unsorted Array looks like this." << endl;
for (j = 0; j < 7; j++){
cout << temp2[j][0];
cout << " : ";
cout << temp2[j][1] << endl;
}
for(k = 0; k < SIZE; k++)
{
for(j = 0; j < SIZE-1-k; j++)
{
if(temp2[j+1][0] < temp2[j][0])
{
l = temp2[j][0];
temp2[j][0] = temp2[j+1][0];
temp2[j+1][0] = l;
l = temp2[j][1];
temp2[j][1] = temp2[j+1][1];
temp2[j+1][1] = l;
}
}
}
cout << "Sorted Array looks like this." << endl;
for (m = 0; m < SIZE; m++)
{
cout << temp2[m][0];
cout << " : ";
cout << temp2[m][1] << endl;
}
for(i = 0; i < SIZE; i++){
indices[i] = temp2[i][1];
}
cout << "Indices of Sorted Array look like this." << endl;
for(i = 0; i < SIZE; i++){
cout << indices[i] << endl;
}
return 0;
}