C++ mistake in finding a 'x' number in 2D array [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
In my code below, I try to find an 'x' in a 2D array and display its row and column. But it always shows the a[0][1] in the result. Can someone tell me where did I wrong and why is that? I tried other code but there is no difference. Thanks
My code:
#include <iostream>
using namespace std;
int main(){
int m, n, i, j, a[m][n], sum, x, sl=0;
cout<<"insert array number of rows: "; cin>>m;
cout<<"insert array number of columns: "; cin>>n;
for(i=0;i<m;i++){
sum=0;
for(j=0;j<n;j++){
cout<<"insert board["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
sum+=a[i][j];
}
cout<<"the summary of rows "<<i<<" is: "<<sum<<endl;
}
cout<<"search x= "; cin>>x;
for (i=0; i<=m-1; i++){
for (j=0; j<=n-1; j++){
if (a[i][j]==x){
sl++;
cout<<"x is at "<<"a["<<i<<"]["<<j<<"]"<< endl;
}
}
}
if(sl==0){
cout<<"there is no x in the array";
}
cout<<sl;
return 0;
}
My results:

Sources of error in your code:
You were using a variable length array (which is not a part of C++ standard). Moreover you were setting its rows and columns before even initializing/inputting n and m.
Fixed Code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n, x, sl = 0;
cout << "Insert number of rows in the array: ";
cin >> m;
cout << "\nInsert number of columns in the array: ";
cin >> n;
// put the below line after cin >> m; cin >> n;
vector<vector<int>> a(m, vector<int>(n, 0)); // <-- Use this instead of int a[m][n];
cout << endl;
for (int i = 0; i < m; ++i) {
int sum = 0;
for (int j = 0; j < n; ++j) {
cout << "\nInsert board[" << i << "][" << j << "]: ";
cin >> a[i][j];
sum += a[i][j];
}
cout << "\nThe sum of the row " << i << " is: " << sum << endl;
}
cout << "\nSearch x = ";
cin >> x;
cout << '\n' << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (a[i][j] == x) {
sl++;
cout << "x is at a[" << i << "][" << j << "]\n";
}
}
}
if (sl == 0) { cout << "\nThere is no x in the array!"; }
else cout << '\n' << sl;
return 0;
}
Sample Input :
2
2
3
4
7
3
3
Sample Output :
Insert number of rows in the array:
Insert number of columns in the array:
Insert board[0][0]:
Insert board[0][1]:
The sum of the row 0 is: 7
Insert board[1][0]:
Insert board[1][1]:
The sum of the row 1 is: 10
Search x =
x is at a[0][0]
x is at a[1][1]
2
For interactive run, you can remove the newline characters at your wish.

Related

How to print values in descending order for every number entered?

I need to create a program that asks the user for N unique values and print the values in descending order for every number entered. The problem is it only outputs the number 0. Can anyone point out what is wrong with my code?
#include <iostream>
using namespace std;
int main(){
//declare the variables
int N, j, i, k, z, desc, temp, sorter[N];
bool found;
//Ask the user for N size array
cout << "Enter array size: ";
cin >> N;
while(N<5){
cout << "Invalid value. N must be greater than five(5)" << endl;
cout << "Enter array size: ";
cin >> N;
}
int list[N];
//Printing how many values they need to enter
cout << " " << endl;
cout << "Please enter " << N << " values" << endl;
//Code of the program
for (int i = 0; i < N; i++){
do{
found = false;
cout << "\n" << endl;
cout << "Enter value for index " << i << ": ";
cin >> temp;
for (int j = 0; j < i; j++)
if (list[j] == temp)
found = true;
if (found == true)
cout << "Value already exist";
else{
for(int k = 0; k < i; k++){
int key = sorter[k];
j = k - 1;
while(j >= 0 && key >= sorter[j]){
sorter[j + 1] = sorter[j];
j--;
}
sorter[j + 1] = key;
}
cout << "\nValues: ";
for(int z = 0; z <= i; z++){
cout << sorter[z] <<" ";
}
}
} while(found == true);
sorter[i] = temp;
}
You shouldn't be defining the array 'sorter[N]', the position, where you are currently, because you don't have the value of 'N', during compilation the arbitrary amount of space will be allocated to the the array.
solve the other compiling errors in your code.
What you want is just a 3-line code:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> vecOfNumbers = { 1,3,5,7,9,8,6,4,2 }; // scan these numbers if you want
std::sort(vecOfNumbers.begin(), vecOfNumbers.end());
std::copy(vecOfNumbers.rbegin(), vecOfNumbers.rend(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Make sure you understand it before using it

C++ [Error] invalid conversion from 'int' to 'int (*)[2]' [-fpermissive] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a beginner and I keep getting an error when I am calling my function. I am trying to get the user to input a value for the array and then get it to display it in a table format. Also, I am trying to display a 3x3 matrix in the end.
void DMMatrix(int DM[2][2]){
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[2][2];
DMMatrix(DM[2][2]);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] + DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0){
cout << "\nSum is " << sum;
}
}
There are 3 problems in your program.
Mistake 1
You are calling the function DMMatrix incorrectly. The correct way to call DMMatrix would be:
DMMatrix(DM);//CORRECT WAY OF CALLING DMMatrix
Mistake 2
Your 2D array DM has 2 rows and 2 columns and you're accessing 3rd row and 3rd column of the array DM. But since the 3rd row and 3rd column doesn't exist, you have undefined behavior in your program. To solve this you can create a 3x3 2D array as shown below:
#include <iostream>
using namespace std;
void DMMatrix(int DM[3][3]){//2 CHANGED TO 3
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[3][3]; //2 CHANGED TO 3
DMMatrix(DM);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
sum += DM[i][j];//CALCULATE SUM HERE
}
cout << "\n";
}
cout << "\nSum is " << sum;
}
Mistake 3
You don't need to calculate the sum by writing each element of the array explicitly. You can calculate the sum inside the for loop in my modified above program. Also note that in your original code, while calculating the sum you were going out of bounds which leads to undefined behavior. The above shown program corrected this.
First, the size of the array that you have given to DM is 2x2 but your loop runs for 9 times considering the loop runs for 0, 1 and 2 which will cause a stack smash or Segmentation Fault
#include <iostream>
using namespace std;
void DMMatrix (int DM[3][3])
{
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << "DM[" << i << "]" << "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main ()
{
int i, j, sum = 0;
int DM[3][3];
DMMatrix (DM);
cout << "\n\nOutput (table format)\n\n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] +
DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0)
{
cout << "\nSum is " << sum;
}
}

wrong output in common number array program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I need my code to output the common numbers from two arrays but I can't seem to find the issues in my code. Here are some more words so I can fill the quota for stack's post requirement.
Here's the code.
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5], list2[5];
cout << "Enter numbers for List No.1" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list2[i];
}
{
cout << "common elements" << endl;
for (int i = 0; list1; i < i++) {
for (int i = 0; list2; i < i++)
if (list1[i] == list2[i]) {
cout << " " << list1[i];
}
}
}
return 0;
}
You should use different counter for each loop and also your loop has wrong parameters. Do it like:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (list1[i] == list2[j]){
cout<<" "<<list1[i];
}
}
}
Also for initial values start from zero index([0]) as zero index is the first element for each array:
for (int i = 0; i < 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
Another way to do this is by using std::array. It acts very similar to a normal array but it is much better to work with.
for example if you want a char array of length of 10 you can simply write:
std::array<char, 10> My_happy_array.
First please read this to understand why you should not using namespace std. Second consider reading about Range-based for loop
Third, here is the modified version of your program which uses std::array instead of a normal array:
#include <iostream>
#include <array>
int main() {
std::array<int,5> list1;
std::array<int,5> list2;
std::cout << "Enter numbers for List No.1" << std::endl;
for (int i = 0; i < list1.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list1[i];
}
std::cout << "Enter numbers for List No.2" << std::endl;
for (int i = 0; i < list2.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list2[i];
}
for(auto i : list1){
for(auto j : list2){
if(i==j){
std::cout << " " << i;
}
}
}
return 0;
}
Here's fixed code
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5] ,list2[5];
cout << "Enter numbers for List No.1" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list2[i];
}
cout<<"common elements"<<endl;
for (int i = 0;i<5; i++)
{
for (int j = 0;j<5; j++)
{
if (list1[i] == list2[j])
{
cout<<" "<<list1[i];
}
}
}
return 0;
}
mistakes in code:
you used for loops wrongly whole the time.
array of 5, stores values in index (0,1,2,3,4) not (1,2,3,4,5), so always start loop from 0 and ends before max index (for this case '4' ie. use 'i<5')
while using for loop inside other for loop never use same iterable variable like you used i in both loops use i and j different for each loop,
take a look in my code..
ask me if you get any difficulties.

Rotating an array:Segmentation Fault (SIGSEGV)

Given an array of N size. The task is to rotate array by d
elements where d is less than or equal to N.
Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 200 1 ≤ A[i] ≤ 1000
Example input:
1
5
1 2 3 4 5
2
Output
3 4 5 1 2
The program I wrote seems legit but when I tried to run it is giving me segment fault. I even ran the above example I'm getting the correct output.
The source is GeeksforGeeks: Rotating and Array.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cin >> test_case;
while (test_case--) {
cin >> numb;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cin >> from;
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
What are the changes which my code needs? What can I do to avoid such errors in the future?click_to_see_segment_fault
Just submitted your exact code on Rotating an Array | Geek for Geeks (site given in the question) . It works perfectly , and no run time error was encountered .
Run the following input and will see weird results. The problem is when the from is greater than the number of elements itself. Basically you need to do a check to see whether the from itself is more than the number of elements or not numb.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<<"\nEnter number of test cases:";
cin >> test_case;
cout<<"Test cases = "<<test_case<<endl;
while (test_case--) {
cout<<"Enter count of elements:";
cin >> numb;
cout<<"Count= "<<numb<<endl;
cout<<"Enter the elements:";
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Entered elements are :";
for (int i = 0; i < numb; i++) {
cout << arr[i]<<" ";
}
cout<<"\nHow many times to rotated? :";
cin >> from;
cout<<"\nRotate it "<<from<<" times:\n";
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Lets provide the input as follows:
Enter number of test cases:1
Test cases = 1
Enter count of elements:1
Count= 1
Enter the elements:2
Entered elements are :2
How many times to rotated? :2
Rotate it 2 times:
2 32666
You see the mistake? The location where 32666 is a problem here. It could crash too in your case.
#include <bits/stdc++.h>
using namespace std;
int main() {
int test_case, numb, from, arr[200];
cout<< "Enter the numbe of test cases"<<endl;
cin >> test_case;
if(test_case > 200)
{
cout<<"Number of test cases above limit";
return 0;
}
while (test_case--) {
cout<<"START TEST CASE"<<test_case<<endl;
cout<<"Enter the number of elements in the array"<<endl;
cin >> numb;
if(numb > 200)
{
cout<<"Array size more than expected skipping testcase"<<endl;
continue;
}
cout<<"Enter the elements of array"<<endl;
for (int i = 0; i < numb; i++) {
cin >> arr[i];
}
cout<<"Enter the number of rotations"<<endl;
cin >> from;
if(from > numb || from < 0)
{
cout <<"rotation index out of range skipping testcase"<<endl;
continue;
}
for (int i = from; i < numb; i++) {
cout << arr[i] << " ";
}
for (int j = 0; j < from; j++) {
cout << arr[j] << " ";
}
cout << "\n";
}
return 0;
}
Extending #Charlie's answer,
The program checks for numbs ranges and from's range.

Summing 2D array columns in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to sum up columns of a predefined 2 D array, but my code seems not to work. E. g. for a 2D array with rows 2 3 and 4 5
I am getting following column sums:
-117393687 and -113194156
Here is the part of my code where I sum up the columns:
//sum columns
for(i=0; i<m; i++)
{
for(ii=0; ii<m; ii++)
{
sum += myarray[i][ii];
}
cout <<"column sum: "<<sum<<endl;
{
Rest of my code:
#include <iostream>
using namespace std;
int main()
{
int i, ii, n, m, sum;
int array[n][m];
sum=0;
cout <"no. of rows"<<endl;
cin>>n;
cout <"no. of columns"<<endl;
cin>>m;
for(i=0; i<n; i++)
{
for(ii=0; ii<n; ii++)
{
cout<<"row "<<i+1<<" column "<<ii+1<<endl;
cin>>array[n][m];
}
}
}
//sum columns
for(i=0; i<m; i++)
{
for(ii=0; ii<m; ii++)
{
sum += myarray[i][ii];
}
cout <<"column sum: "<<sum<<endl;
{
There are quite a few errors on your code, and it has quite a weird structure, but trying not to change it too much (so it's still easy for you to follow the fixes), let's see it fixed then I'll explain it (please note that this version will compile and run in practice):
#include <iostream>
using namespace std;
int main()
{
int i, ii, n, m, sum;
cout << "no. of rows" << endl;
cin >> n;
cout << "no. of columns" << endl;
cin >> m;
int array[n][m];
for (i=0; i<n; i++)
{
for (ii=0; ii<m; ii++)
{
cout << "row " << i+1 << " column " << ii+1 << endl;
cin >> array[i][ii];
}
}
sum=0;
for (i=0; i<n; i++)
{
for (ii=0; ii<m; ii++)
{
sum += array[i][ii];
}
}
cout << "Sum: " << sum << endl;
}
Ok, so, first, you should only declare the array after you know what "n" and "m" variables are. Edit: also, not all compilers will accept declaring the dynamic array that way, but again, I tried to keep your original structure as much as possible.
Second, in your input loop, you should index the array by "i" and "ii", but you were always indexing by "n" and "m", that is, only writing to the latest index, which would even cause an exception.
Last, while summing, again you should use "i" and "ii" as array indices, so you correctly scan the array.
And that is it.
You're not declaring your array size properly. When you create the array n and m aren't set yet. You need to determine their size first. And even then you have to pass in constants to an array because arrays in C++ cannot be dynamically sized. If you want the user to determine container size like this then use a vector of vectors. Arrays are to be used when you know the size from the beginning of the program.
According to the code shown above:
You are mistaking while taking the iputs. Try this:
for(i=0; i<n; i++)
{
for(ii=0; ii<n; ii++)
{
cout<<"row "<<i+1<<" column "<<ii+1<<endl;
cin>>array[i][ii];
}
}
You are initializing the 2D array in a wrong way, you need to define the size first, m and n are not initalized when declaring the array.
On C++ using containers like vector is better.
You also had a error in the input code (2 n instead of n and m in the for loop).
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rows, cols, sum = 0;
std::vector<std::vector<int>> array;
cout << "No. of rows: ";
cin >> rows;
cout << "No. of columns: ";
cin >> cols;
for(int i = 0; i< rows; i++)
{
std::vector<int> v;
for(int j = 0; j < cols; j++)
{
cout << "Value for row " << i + 1 << " and column "<< j + 1 << ": ";
int val;
cin >> val;
v.push_back(val);
}
array.push_back(v);
}
for (auto i: array)
{
for(auto j: i)
{
sum += j;
}
}
cout << "The sum is: " << sum << endl;
}