Copy part of a matrix and paste on another one C++ - c++

The user input a matrix, and the output must be a new matrix with an additional column of zeros. If we apply the script to a 2 square matrix like : {1,2,3,4} the new matrix output will be a 2 rows & 3 columns : {1,2,32,3,4,0}. I don't understand the number 32 output.
#include <iostream>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
int A[m][n]={};
int M[m][n+1]={0};
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}

Variable length arrays (VLAs) are a non-portable gcc extension and evidently don't initialise as you would expect.
One solution is to use std::vector instead which is portable and will do what you want, something like this:
#include <iostream>
#include <vector>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
std::vector <std::vector <int>> A;
std::vector <std::vector <int>> M;
A.resize (m);
M.resize (m);
for (int i = 0; i < m; ++i)
{
A [i].resize (n);
M [i].resize (n + 1);
}
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
std::cout << "\n";
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
}
Live demo

In the bad old days of C, you could realloc() the array bigger and memset() the new column (only good for the last dimension, where items are adjacent).

Related

What should be the proper declaration of array while finding the largest number in array?

C++ This is my code in C++ for finding the largest number in array. When I was running in my IDE then there was no compilation error but it was not giving me output. I think the problem is in the declaration of array at line 8. I replaced the array declaration from line 8 to line 11 then it is working fine in my IDE. So I didn't get it that why the declaration of array was not working at line 8?
#include <bits/stdc++.h>
using namespace std;
int largest_in_array(int a[], int n);
int main() // main function
{
int n; // User will enter the size of array
int arr[n]; // Line 8
cout << "Enter the size of array: " << endl;
cin >> n;
// Line 11
cout << "\nEnter the elements of array: " << endl;
for (int i = 0; i < n; i++) // This loop will run for each element of array that user wants to enter
{
cout << "Enter the " << (i + 1) << " element:";
cin >> arr[i];
cout << endl;
}
cout << "Elements are: [";
for (int i = 0; i < n; i++) // Prints the elements of array
{
// cout << "Enter the " << (i + 1) << " element:";
cout << arr[i] << " ";
// cout << endl;
}
cout << "]";
int res = largest_in_array(arr, n); //Function call
cout << "\nLargest element in array is: " << arr[res] << endl;
return 0;
}
int largest_in_array(int a[], int n) // function that will return the index of largest element in array
{
int max = 0;
for (int i = 1; i < n; i++)
{
if (a[max] < a[i])
{
max = i;
}
}
return max;
}
You declare int arr[n]; before the user has entered a value into n. n has an indeterminate value when you read it and create arr.
You don't check that the user enters a positive value into n. Zero and negative sized arrays are not valid.
Other points:
bits/stdc++.h is not a standard header which makes your program not portable. Use the proper header files, like iostream etc.
arr[n] is a Variable Length Array (VLA) which is not part of standard C++. Make it a std::vector<int> arr(n); instead.
The use of std::endl is unnessesary. There is no need to flush the output streams here. Use \n instead.
Example:
#include <iostream>
#include <limits>
#include <vector>
int largest_in_array(const std::vector<int>& a) {
int max = 0;
for(int i = 1; i < a.size(); i++) {
if(a[max] < a[i]) {
max = i;
}
}
return max;
}
int main() // main function
{
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
// check that input succeeds and that the value is valid
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++)
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(int i = 0; i < n; i++)
{
std::cout << arr[i] << " ";
}
std::cout << "]";
int res = largest_in_array(arr); // Function call
std::cout << "\nLargest element in array is: " << arr[res] << '\n';
}
That said, you could however use the standard algorithm std::max_element instead of writing your own. It returns an iterator to the maximum element.
You could also make use of range-based for loop when you don't need to know the index in the array, as in your second loop.
Example:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main() {
int n; // User will enter the size of array
std::cout << "Enter the size of array:\n";
if(!(std::cin >> n) || n < 1) return 1;
std::vector<int> arr(n);
std::cout << "\nEnter the elements of array:\n";
for(int i = 0; i < n; i++) // This loop will run for each element of
// array that user wants to enter
{
std::cout << "Enter the " << (i + 1) << " element:";
if(!(std::cin >> arr[i])) {
std::cout << "invalid input, bye bye\n";
return 1;
}
}
std::cout << "Elements are: [";
for(auto value : arr) { // a range-based for loop
std::cout << value << ' ';
}
std::cout << "]\n";
auto res = std::max_element(arr.begin(), arr.end());
std::cout << "Largest element in array is: " << *res << '\n';
std::size_t index = std::distance(arr.begin(), res);
std::cout << "which has index " << index << '\n';
}
When you have int n on line 8 it is initialized when you use it to create the array. When n is initialized explicitly, it's value is undefined behavior. You may be creating an array larger than the n you inputted on line 10, resulting in the array having extra random junk, it may be smaller meaning your program read memory it really shouldn't, etc.

Fill up a vector with input from a user

I am learning c++ and i have a problem with filling a vector with the input from the user. wWenever i try to run my code, a window pops-up with 'vector subscript out of range' written in it.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int s(0), values(0);
vector <int> grades;
cout << "Enter the number of grades you want to enter: \n";
cin >> s;
cout << "Enter the values:";
for (int i(0); i < s; i++)
{
cin >> values;
grades.push_back(values);
}
int grades_size(grades.size());
int average(0);
for (int m(0); m <= grades_size; m++)
{
average += grades[m];
}
average /= grades_size;
cout << "Your average is" << average;
return 0;
}
You can read things from input using streams.
The following example shows how to use the succinct syntax of ranges to do that:
#include <iostream>
#include <range/v3/view/istream.hpp>
#include <range/v3/range/conversion.hpp>
int main()
{
auto vec = ranges::istream<int>(std::cin) | ranges::to_vector;
for (auto elem : vec) {
std::cout << elem << std::endl;
}
}

I got infinite loop while practicing array in C++ to find reversed number

Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.

2D x 2D when the rows and columns are set by a user, random

My task was to write a program that multiplies two matrices. The program should retrieve information from the user how many rows and columns he has
the first of the matrix and how much the second of the matrix (by which we will multiply). Then enter the range of numbers for the first and second matrices. The tables are filled with random numbers from the given ranges. Then we do the multiplication
matrix. We display matrices filled with random numbers and the resulting matrix. So I did it, but the answer is not right. Can anybody help me out with this stuff ? Many thanks in advance...
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
cout << "Provide first matrix dimensions (rows, cols):\n";
int TWier1, TKol1, za;
cin >> TWier1 >> TKol1;
int taba[TWier1][TKol1];
cout << "Provide matrix max value:\n";
cin >> za;
for(int i=0;i<TWier1;i++)
{
for(int j=0;j<TKol1;j++)
{
taba[i][j] = rand() % za;
}
}
for(int i=0;i<TWier1;i++)
{
for(int j=0;j<TKol1;j++)
{
cout << taba[i][j] << " ";
}
cout << "\n";
}
cout << "Provide second matrix dimensions (rows, cols):\n";
int TWier2, TKol2;
cin >> TWier2 >> TKol2;
int tabb[TWier2][TKol2];
for(int i=0;i<TWier2;i++)
{
for(int j=0;j<TKol2;j++)
{
taba[i][j] = rand() % za;
}
}
for(int i=0;i<TWier2;i++)
{
for(int j=0;j<TKol2;j++)
{
cout << tabb[i][j] << " ";
}
cout << "\n";
}
int tabc[TWier1][TKol2];
for(int i=0;i<TWier1;i++)
{
for(int j=0;j<TKol2;j++)
{
tabc[i][j]=0;
}
}
for(int i=0;i<TWier1;i++)
{
for(int j=0;j<TKol2;j++)
{
for(int k=0;k<TWier1;k++)
{
tabc[i][j] += taba[k][j]*tabb[i][k];
}
}
}
for(int i=0;i<TWier1;i++)
{
for(int j=0;j<TKol2;j++)
{
cout << tabc[i][j] << " ";
}
cout << "\n";
}
system("pause");
return 0;
}
You have a typo in second matrix initialization:
int TWier2, TKol2;
std::cin >> TWier2 >> TKol2;
int tabb[TWier2][TKol2];
for(int i=0;i<TWier2;i++)
{
for(int j=0;j<TKol2;j++)
{
taba[i][j] = rand() % za; <--- here should be tabb instead of taba
}
}
Otherwise should be OK, unless you want to have different max values for the matrices.

C++: Dynamically create array named after for loop iterator

Hey so I want to create n arrays (based off user input) of size x (also off user input). The way I was thinking of doing it was having a for loop perform n iterations and inside the loop ask the user for x. The problem is I'm not sure how to name the array using the variable n, I was thinking something like:
cout << "Enter n: ";
cin >> n
for (i = 0; i < n; i++)
{
cout << "Enter x: ";
cin >> x;
double*array+i;
array+i = new double[x]
}
To sum up my question is: can you create/name an array using a variable in C++?
Unfortunately, you can't do this in C++. Try something like this...
std::cout << "Enter n: ";
std::cin >> n
std::vector<std::vector<double> > arrays(n);
for (std::size_t i = 0; i < n; i++)
{
std::cout << "Enter x: ";
std::cin >> x;
arrays[i].reserve(x);
}
reserve only allocates, but does not construct the objects in the std::vector; if you want to construct them too, use resize.
PS Never use using namespace std; it makes your code harder to read and debug.
Since you are programming in C++, you should use STL containers (especially std::vector) instead of C-style arrays.
If you need to access an array by using the string that has been created in runtime, then you could use std::map< std::string, std::vector<double> >, which is pretty crazy idea though:
typedef std::vector<double> MyVector;
std::map<std::string, MyVector> myVectors;
// create an array:
std::string arrayName;
arrayName = std::string("someArray"); // could be: std::cin >> arrayName;
myVectors[arrayName] = MyVector(10, 1.23); // new vector of size 10
std::cout << myVectors["someArray"][4]; // prints 1.23
I'm not sure what exactly is what you are trying to achieve, but there are most likely more appropriate solutions. Is it really necessary to access these arrays via their names? I'm pretty sure that common std::vector< std::vector<double> > would suffice here.
Here's 3 solutions: the first is closest to your example code, the second is an improvement in order to be able to correctly retrieve the array elements within bounds, and the third is the reason why you are better served with vectors.
Solution 1:
It looks like you want your arrays to have names that are distinguishable by your loop iterator. Like Joe said, you could have an array of an array, so the inner arrays will be named array[0], array[1], ..., array[n - 1]. This will be achieved by using a pointer to pointer to double. Each of the inner pointers will be used to dynamically allocate arrays of double. Don't forget to delete the dynamically allocated memory.
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Enter number of arrays: ";
std::cin >> n;
double** array = new double*[n];
for (int i = 0; i < n; ++i)
{
unsigned int size;
std::cout << "Enter size of array " << i << ": ";
std::cin >> size;
array[i] = new double[size];
for (int j = 0; j < size; ++j)
{
int element;
std::cout << "Enter element " << j << " of array " << i << ": ";
std::cin >> element;
array[i][j] = element;
}
}
for (int i = 0; i < n; ++i)
{
delete [] array[i];
}
delete[] array;
return 0;
}
Solution 2:
However, with the above code, you will have trouble accessing the elements of each inner array. Unless you memorized the size of each inner array you create with this, you might access something out of bounds. Therefore, an update to this code would be to add yet another array, let's call it sizeOfInnerArrays, where each of its element i keeps track of the size of inner array array[i]. Here's the update:
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Enter number of arrays: ";
std::cin >> n;
double** array = new double*[n];
unsigned int* sizeOfInnerArrays = new unsigned int[n];
for (int i = 0; i < n; ++i)
{
std::cout << "Enter size of array " << i << ": ";
std::cin >> sizeOfInnerArrays[i];
array[i] = new double[sizeOfInnerArrays[i]];
for (int j = 0; j < sizeOfInnerArrays[i]; ++j)
{
int element;
std::cout << "Enter element " << j << " of array " << i << ": ";
std::cin >> element;
array[i][j] = element;
}
}
//prints out each array as curly-brace enclosed sets of doubles
for (int i = 0; i < n; ++i)
{
std::cout << "{";
for (int j = 0; j < sizeOfInnerArrays[i] - 1; ++j)
{
std::cout << array[i][j] << ", ";
}
std::cout << array[i][sizeOfInnerArrays[i] - 1] << "}" << std::endl;
}
// free dynamically allocated memory
for (int i = 0; i < n; ++i)
{
delete [] array[i];
}
delete[] array;
delete[] sizeOfInnerArrays;
return 0;
}
Solution 3:
However, that is too complicated, so you are better off using a container, like vector, as Joe suggested, whose data member keeps track of its size.
#include <iostream>
#include <vector>
int main()
{
unsigned int n;
std::cout << "Enter number of vectors: ";
std::cin >> n;
std::vector<std::vector<double> > myVec;
// ^ space between closing angle brackets not needed
// if using C++11 conforming compiler
for (int i = 0; i < n; ++i)
{
unsigned int size;
std::cout << "Enter size of vector " << i << ": ";
std::cin >> size;
std::vector<double> temp;
temp.reserve(size);
for (int j = 0; j < size; ++j)
{
double value;
std::cout << "Enter next value of vector " << i << ": ";
std::cin >> value;
temp.push_back(value);
}
myVec.push_back(temp);
}
for (int i = 0; i < myVec.size(); ++i)
{
std::cout << "{";
for (int j = 0; j < myVec.at(i).size() - 1; ++j)
{
std::cout << myVec.at(i).at(j) << ", ";
}
std::cout << myVec.at(i).back() << "}" << std::endl;
}
return 0;
}