I'm trying to just make a simple program where the user inputs every value of a matrix, then the program prints the matrix. So far I have
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "A is an nxn matrix.\nn=";
cin >> n;
int matrix[n-1][n-1];
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> matrix[i][j];
}
}
cout << "[[ ";
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout << matrix[i][j] << " ";
}
if (i!=n-1) //Just to make the output pretty
cout << "]\n [ ";
else
cout << "]]";
}
}
`
However, whenever I put in a matrix of any size, for instance [[1,2,3][4,5,6][7,8,9]], the program returns [[1,2,4][4,5,7][7,8,9]].
Can anyone tell me why this is happening and how to fix it?
You're getting an undefined behavior for accessing out of range in matrix[i][j] when i or j equals n-1 for your matrix declared as matrix[n-1][n-1]
Use:
int matrix[n][n]; // will say 0 to n-1
instead of
int matrix[n-1][n-1];
Should be int matrix[n][n]. Generally, an array A[n] has indexes from 0 to n-1.
You are overflowing the boundaries of the row, for example, if you have int matrix[2][2] and set matrix[0][2] = 42, you are actually assigning matrix[1][0], and when you set matrix[2][0] you are writing beyond the array boundaries potentially destroying some other variables or even call stack, which may cause undefined behavior.
Related
#include <iostream>
using namespace std;
int main()
{
int x, y, z;
cout << "how many elements? " << endl;
cin >> x;
int arr[x];
for(int i = 0; i < x; i++)
{
cout << "give number" << endl;
cin >> arr[i];
}
cout << endl;
y = 0;
z = 0;
// for(int i = y; i >= 0; i-z)
while (z < x)
{
for(int i = y; i < x; i++)
{
for(int i = z; i < x-y; i++)
{
cout << arr[i] << " ";
}
cout << endl;
y++;
}
z++;
cout << z;
}
// while (z < x);
return 0;
}
I want my parameter z, which is in the while loop, to link with parameter i=z in the second for loop. I want the program to print numbers from 1 to n, then from 2 to n, and so on, to the moment it will print only n.
Don't mind this cout<<z; in line 30, I was checking if this even works.
I don't know what you mean by "link with z", but here is what the loop should be to do what you want it to:
for (int z = 0; z < x; ++z) // NOTE: get rid of outside z
{
for(int i{z}; i < x; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
}
The inner loop loops through all of the values of the array, starting with z and ending at x-1. Since z is incremented, the next loop will start at the next position, starting at what was z plus one and ending at x-1.
Also change:
int arr[x];
To:
int* arr = new int[x];
and add this line at the end:
delete [] arr;
This should be added and changed because C++ doesn't support variable length arrays. However, it does support pointers to blocks of memory treated as arrays. You also should delete memory you use when you are done with it.
In c++, while declaring an array either the size or the elements must be known at the time of compilation, if you want to declare an array during run time, you can do one of the following
you can use std::vector, which is a dynamically growing array, and can be initialized without the size or elements, it is included in the vector header file.
use the new keyword to dynamically allocate a block of memory on the heap which returns a pointer and will act as your array (refer to #captainhatteras 's answer)
However it is better to use vector in this case as it is much more easier to understand and use
And you don't need the nested loop here, (not sure if you were keeping it for future reference, i removed it for the sake of simplicity)
How it works
Here with each iteration of the while loop, we're incrementing the value of int z which is taken as the starting point of our for-loop, therefore with each passing iteration the range of the for-loop is decreased by 1. ultimately the value of int z will be equal to int x and the code will exit the while loop
so your code would look something like this
#include <iostream>
#include <vector>
using namespace std;
int main() {
int x, z = 0;
cout << "how many elements? " << endl;
cin >> x;
vector<int> arr;
for (int i = 0; i < x; i++) {
int choice;
cout << "give number" << endl;
cin >> choice;
arr.push_back(choice);
}
cout << endl;
while (z < x) {
for (int i = z; i < x; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
z++;
}
return 0;
}
std::vector has a method called push_back() which adds an element passed in to the end of the array
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.
I tried to write this code but it says expression did not evaluate to a constant. I learn that this is because VS does not allow an undeclared array, as "n" is not understood by VS. How can i fix this code with a declared array?
#include<iostream>
using namespace std;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
int a[n];
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
How can i fix this code with a declared array?
Option 1
Declare the array with sufficiently large size and make sure that n is less than or equal to the size before using the array.
int i, n;
int a[1000];
cout << "Enter size of array (less than or equal to 1000):";
cin >> n;
if ( n > 1000 )
{
// Deal with the problem.
}
else
{
// Use the array.
}
Option 2
Use std::vector.
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
Variable length arrays (VLAs) are not part of the C++ language, although some compilers (like g++) support them as an extension.
You should be using the std::vector container from the Standard Template Library, instead. Once declared and properly initialized, a std::vector can be used much like a plain array:
#include<iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
You have to allocate the array on the heap like this:
int* a = new int[n];
But when you do heap allocations, always remember to delete the allocated memory after you are done using it:
delete[] a;
If you don't want to worry about deleting the memory, you can look into std::vector.
The strange problem appears in my program. It is working, but in debugging it shows the "Exception thrown" in random places at the outputting
cout<<"Average value:"<<u3.apr();
_getch();
Sometimes, it even throws this error after the main function (Behind the {})
It is quite annoying because the program just closes after 3 seconds because of these errors.
(Maybe that's because of class, but I'm trying to learn it ;) )
Have tried already changing lines order, rewriting class name and array name.
#include <iostream>
#include <conio.h>
using namespace std;
class vid
{
private:
int i, j;
double rez, sum=0;
public:
int size;
double *arr = new double[size];
double apr()
{
for (i = 0; i < size; i++)
{
sum += (*(arr + i));
}
return sum / size;
}
};
int main()
{
vid u3;
cout << "Enter array length:";
cin >> u3.size;
for (int i = 0; i < u3.size; i++)
{
cout << "Enter array's " << i << " element:" << endl;
cin >> *(u3.arr+i);
}
cout << "Your array:" << endl;
for (int i = 0; i < u3.size; i++)
{
cout << *(u3.arr + i) << "\t";
}
cout << endl;
cout<<"Average value:"<<u3.apr();
_getch();
}
Thanks for any help ;)
arr is initialised when u3 is constructed.
But you didn't populate u3.size until later.
So, your array has indeterminate length (which is already UB), and your accesses later may be invalid.
You're going to have to manage your class's member a bit more cleverly!
Such classes generally have a "resize" function that performs the allocation per the requested size. Don't forget to safely kill any prior allocation, transplanting data if necessary. You can find online plenty of examples of a vector implementation.
Certainly renaming classes and randomly re-ordering the lines of your program's source code is not going to solve anything.
u3.size is not set until after u3 is constructed. By setting u3.size you can avoid this compiler-time error.
It seems that as an alternative solution, you might want to consider how to get rid of the new call and the need to write a destructor that will delete arr.
By creating a constructor that takes a size parameter AND by switching arr to a std::vector, you can allow the class to hold the vector and handle memory allocation and deallocation:
#include <iostream>
#include <vector>
using namespace std;
class vid
{
private:
int i, j;
double rez, sum=0;
public:
int size;
std::vector<double> arr;
// constructor requires size to be passed in;
// constructor initializes the arr array with the passed in size to zeroes.
vid(int argSize) : size(argSize), arr(argSize, 0.0){ }
double apr()
{
for (i = 0; i < size; i++)
{
sum += arr[i];
}
return sum / size;
}
};
int main()
{
uint size;
cout << "Enter array length:";
cin >> size;
vid u3(size);
for (int i = 0; i < u3.size; i++)
{
cout << "Enter array's #" << i << " element:" << endl;
cin >> u3.arr[i];
}
cout << "Your array:" << endl;
for (int i = 0; i < u3.size; i++)
{
cout << u3.arr[i] << "\t";
}
cout << endl;
cout<<"Average value:"<<u3.apr();
char ch;
cin >> ch;
}
I am trying to create a program that asks the user for a set of numbers, first asking for the quantity of numbers, then having them input all the numbers. The program then checks the numbers, and determines whether or not the numbers given are in ascending order or not. Then, simply print out "yes ascending" or "no not ascending" and print out the array on one line..So far, my code will just always say that "yes, this is an increasing array!" Please look below for my code. Thanks in advance!..
tested: 1 2 3 4 5 6 --> pass
1 3 5 2 4 6 --> fail (still says it is an ascending array)
#include <iostream>
#include <string>
using namespace std;
bool isAscending(int arr[], int size)
{
for (int i=0; i < size-1; i++)
{
if (arr[i] > arr[i+1])
{
return false;
}
}
return true;
}
int main()
{
int arraysize = 0;
string numbers;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1)
{
cout << "ERROR: you entered an incorrect value for the array size!" << endl;
}
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
int arr[arraysize];
if ( isAscending(arr, arraysize))
{
cout << "This IS an increasing array!" << endl;
}
else
{
cout << "This is NOT an ascending array!" << endl;
}
for (i = 0; i < arraysize - 1; i++)
{
cout << arr[i];
}
return 0;
}
You're reading in "numbers", which you created as type String.
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
Your numbers+= line isn't doing anything except adding a space to your numbers string before your cin happens... I know what you're trying to accomplish, and that won't do it.
Then you're suddenly making an array which, without initializing is filled with garbage, and immediately running isAscending on it:
int arr[arraysize];
if ( isAscending(arr, arraysize)){....}
I advise you declare your array before receiving input, read the input line and process it into INTEGERS, and then add each integer to your array. Here is a (crude) correction of the first section of code in your main that just reads in whitespace separated integers and fills the array with them:
int main(){
int arraysize = 0;
int number = 0;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1) // you should really have this loop until you get correct input
{ cout << "ERROR: you entered an incorrect value for the array size!" << endl; }
int* arr = new int[arraysize];
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
int i = 0;
while(i < arraysize){
cin >> number;
arr[i] = number;
i++;
};
if ( isAscending(arr, arraysize)){ cout << "This IS an increasing array!" << endl; }
else{ cout << "This is NOT an ascending array!" << endl;}
for (int i = 0; i < arraysize; i++){
cout << arr[i];
if( (i+1) == arraysize){ cout << ". ";}
else cout << ", ";
}
return 0;
}
If you're going to whine about somebody giving partial answers that only address the asker's question, maybe you should take the time to write something yourself.