C++- Filling a 2D array from user input - c++

I'm new to programming and was finding transpose of a matrix.
However, I want the input of the matrix from the user and by writing the following code, the complier doesn't take any input values and immediately stops.
I looked into previous questions posted here about the same but found non useful.
#include<iostream>
using namespace std;
int main()
{
int rows,val;
int num[rows][rows];
cin>> rows;
for(int i=1; i<= rows; i++)
{
for(int j = 1; j <= rows; j++)
{
cin>> val;
arr[i][j]= val;
}
cout<<endl;
}

You can't use variables in array length if they aren't defined as one of the comments mentioned.
arr[i][j] inside your nested for loop isn't declared so that would also give an error, I guess you wanted to use num array which you declared.
The rest is all looking good

Related

C++ : Longest Arithmetic Subarray

Given an input array, the output must be the length of the longest arithmetic subarray of the given array.
I am getting a different output other than the desired one. I don't understand where I went wrong, I'm still a beginner so please ignore the rookie mistakes and kindly help me out wherever I'm wrong. Thanks in advance.
Here's the code:
#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int array[n];
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int length = 2;
int cd = array[1] - array[0];
for(int i=2; i<n; i++){
if(array[i] - array[i-1] == cd){
length++;
}
else {
cd = array[i] - array[i-1];
length=2;
}
cout<<length<<" ";
}
return 0;
}
If you are looking for a subsequence then what you did would not accomplish that.
For example:
Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
You would require a nested loop structure (a for loop within the for loop you currently have) to accomplish that as you want to check a certain cd with the entire array and not just the next element.
If you require to find a subsequence/subarray given that the elements must be adjacent to one another then your program would work correctly.
Also a big error in your code is that you are printing the length inside the for loop. Unsure of whether that was for debugging purposes.
The problem here is you're resetting length after every update. You need a variable to store the maximum of every length.
#include <iostream>
using namespace std;
const int maxn = 1e6;
int arr[maxn];
int main ()
{
int n; cin>>n;
for (int i=0;i<n;i++) { cin >> arr[i]; }
int length = 2;
int maxLength = 2; //max variable
int cd = arr[1] - arr[0];
for(int i=2; i<n; i++){
if(arr[i] - arr[i-1] == cd) {length++;}
else {
cd = arr[i] - arr[i-1];
length=2;
}
//cout<<length<<" "; //remove this
maxLength = max(maxLength, length); //update maxLength
}
cout << maxLength;
}
A few more aesthetic notes:
array is a keyword in C++ used to declare std::array. Although the program may still run, it could create unnecessary confusion.
int array[n] is a VLAs (variable length array). It's not a C++ standard. It may or may not work depends on the compiler.
Why is "using namespace std;" considered bad practice?

2-D vector Size

In C++ , I Made A Code That has A 2D Vector in it and Users are Required to give The inputs In 2D vector . I find It difficult To find The no. of rows in 2 vector with the help of size function.
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int diagonalDifference(vector<vector<int>> arr)
{
int d = arr[0].size();
cout << d;
return 0;
}
int main()
{
int size;
cin >> size;
vector<vector<int>> d;
for (int i = 0; i < size; i++)
{
d[i].resize(size);
for (int j = 0; j < size; j++)
{
cin >> d[i][j];
}
}
cout << diagonalDifference(d);
}
The Output Should BE No. Rows , But it is coming NULL
Here
vector<vector<int>> d;
for (int i = 0; i < size; i++)
{
d[i].resize(size);
//...
d is a vector of size 0 and accessing d[i] is out of bounds. You seem to be aware that you first have to resize the inner vectors, but you missed to do the same for the outer one. I dont really understand how your code can run as far as printing anything for arr[0].size(); without segfaulting. Anyhow, the problem is that there is no element at arr[0].
But first, Look at your function argument -> is a copy of your vector ,use (vector<> & my vec) to avoid the copying mechanism of vector class (copy constructor for instance) cause if you put there your vector as a parameter and u will make some changes inside the function brackets you will not see any results ( if you dont wanna change your primary vector from function main, keep it without changes).
Secondly, look at code snippet pasted below.
std::vector<std::vector<typename>> my_vector{};
my_vector.resize(width);
for (size_t i = 0; i < my_vector.size(); ++i)
{
my_vector[i].resize(height);
}
It gives you two dimensional vector
Operator[] for vector is overloaded and you have to use my_vector[0].size() just
my_vector[1].size() and so on ! I recommend for that displaying the size by kind of loops given in c++ standards
Regards!

Error in code while using logical operator '&&' several times in c++

I have done Following code to count X in an array. Here the compliation error which i get.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
char s [n][n] ;
cin>>n;
char c ;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
}
}
int count=0;
for(int i=1;i<n-1;i++)
{
for(int j=1;j<n-1;j++)
{
if( s[i][j]=='X' && s[i−1][j−1] =='X' && s[i−1][j+1]=='X'&& s[i+1][j−1] =='X' && s[i+1][j+1] =='X')
count++;
}
}
cout<<count<<endl;
return 0;
}
prog.cpp: In function ‘int main()’:
prog.cpp:23:34: error: expected ‘:’ before ‘]’ token
{ if( s[i][j]=='X' && s[i?1][j?1] =='X' && s[i?1][j+1]=='X'&& s[i+1][j?1] =='X' && s[i+1][j+1] =='X')
^
There's nothing wrong with the logical ANDs in the if-statement - well, apart from being unreadable. The problem is everywhere else tbh.
using namespace std;
Try to avoid using namespaces like that. This is so that you prevent ambiguity with name collisions.
char s[n][n];
This is not valid C++. It is known as a VLA. Read more about this in this answer here. Instead, use constexpr or a dynamic array such as std::vector.
int n;
char s[n][n];
cin>>n;
Due to the fact that n is a local variable, it is defined using garbage values (193446 or -539646 or ...). This means that you may end up with a 2D array of negative spaces??? It's only after that n is being set to a number from the user input. Assuming that VLAs are not a problem, what you should do is the following:
int n = 0;
cin>>n;
char s[n][n]; //still not valid C++
Furthermore, the 2D array is initialized with garbage values.
This, I have to admit, I do not understand. If the elements of the 2D array are only set when the user input is 'X', then what values will the rest of the array have?
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
Did you just want to fill in the array with user input values? If so, then all you need is the following:
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
std::cin >> s[i][j];
And finally the program counts the X patterns where X needs to be at all four corners of another X. Apart from the fact that having long if-statements is a bad practise, the if-statement would return the correct result.
See a running version of your demo here: https://rextester.com/ASQ26945

Creating matrices in C++

I am relatively new to C++ programming and I wanted to learn more about language by programming matrices. I have this code that works, but I can't figure out how to create code that would work for any amount of columns and rows. I have trouble passing matrices to functions, which have rows and columns determined by user input.
This is what I have:
#include <iostream>
using namespace std;
template <int rows, int cols>
void display(int (&array)[rows][cols]) {
int i, j;
cout<<"\n";
for(i = 0; i<rows; i++) {
for(j = 0; j<cols; j++) {
cout<<" ";
cout<<array[i][j];
}
cout<<"\n";
}
}
int main() {
int M1[3][3];
cout<<"Enter your matrix elements: \n";
int i, j;
for(i = 0; i<3; i++) {
for(j = 0; j<3; j++) {
cout<<"a["<<i<<"]["<<j<<"]: ";
cin>>M1[i][j];
}
}
display(M1);
return 0;
}
Is performing such task possible without complicating the code too much?
Many remarks and comments are okay, but I think that the best strategy is to use a single vector for storage and a vector for the shape. Learn on pythons numpy to understand the concept or search for ndarray, which is how many different platforms name this concept (n dimensional array). A class bundling the data vector, the shape vector and convenient operators and member functions is then the way to go.
The classical answer would have required you to perform dynamic memory allocations for you array. This is a bit overwhelming especially if you are a newbie. (And to the best of my knowledge this is still way to do it in C)
However the recommend way to do something like that in modern C++ is to use the Standard Template Library.
/*
... Stuff where you get input from the user, specifically the num of rows and cols
... Say these vals were stored in 2 ints num_rows and num_cols
*/
std::vector<std::vector<int> > mat(num_rows);
for (int i = 0; i < num_rows; i++) {
mat[i].resize(num_cols); // this will allow you to now just use [][] to access stuff
}
Please see the first comment below, it has a nice way to avoid the loop to set up the vector and takes care of it at initialization time

What is the missing step here to insert random numbers into the array (c++)?

I am trying to insert random numbers [1;100] into this array of 5 elements but so far I've been using only cin>> for inserting, when the user had to put something in. In this case I would like the random function to insert numbers, no user involved.
I show the code below because I am a beginner and the included pieces of codes are mostly what I can use and understand but on the other hand the whole code is useless because I don't know what is to connect with what. Where is rand()%100+1 to put?
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
int a[5];
int r=rand()%100+1;
for(int i=0; i<5; i++)
{
cout<<a[i]<<endl;
}
for(int i=0; i<5; i++)
{
cout<<a[i]<<endl;
}
return 0;
}
In your program you have 2 loops that both print out result. I suppose previously you had one loop that used cin to insert values, like this:
for(int i=0; i<5; i++)
{
cin<<a[i]<<endl;
}
So you want to change from inserting with ci to inserting random number:
for(int i=0; i<5; i++)
{
a[i] = rand()%100+1
}
In your code you are not initializing the values of the array elements using the rand() function.
Your rand function should go inside the first 'for' loop.Something like the following will do the trick.
for (int i = 0; i < 5; i++) {
a[i] = rand()%100+1;
}