i'm willing to write a code to create an array with a changeable index(meaning having a static array in a function and adding values to it and then getting out of the loop and coming back again and adding another value to the end of it)
but my code doesn't compile:
#include <iostream>
#include <conio.h>
using namespace std;
void arrarr(int);
int main()
{
for (int i = 1; i < 5; i++)
{
arrarr(i);
}
_getch();
return 0;
}
void arrarr(int y)
{
static int x[y];
x[y] = 5;
cout << x[y];
}
Variables can not have variable size. You have to define explicitly the size of the array x, for example: static int x[5].
Also, arrays are zero-indexed, meaning the first element starts at 0. So your loop condition should be for (int i = 0; i < 5; i++)
C++ doesn't support variable length array, you need to define constant size for the static array x. You can do something like:
void arrarr(int y)
{
static int x[SOME_CONSTANT_SIZE]; //SOME_CONSTANT_SIZE known at compile time
x[y] = 5; //y < SOME_CONSTANT_SIZE
cout << x[y];
}
And as #Bruno pointed out, array indices start from 0 to (size-1)
If you are looking to dynamically increase the size of your array, you cannot do that. Use a vector instead. See here: http://www.cplusplus.com/reference/vector/vector/resize/
Your code doesn't compile because of this:
static int x[y];
The compiler doesn't know what x is, e.g.
int [0]
int [1]
int [2]
So you can do
void arrarr(int y) {
static int x[10];
x[y] = 5;
cout << x[y];
}
but what you were doing won't work.
If you share what the expected output is, we might be able to help you more.
Related
I have passed an array of size 10 to a funtion to sort the array reversely, but it's going wrong after rightly sorting first five elements of the array.
I want to sort the array 'std' reversely here,
# include <iostream>
using namespace std;
int reverse(int a[]); //funtion prototype
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
}
int reverse(int a[]) //funtion defination
{
int index = 0;
for (int i = 9; i >= 0; i--)
{
a[index] = a[i]; //swaping values of the array
cout << a[index] << " ";
index++;
}
}
There's basically three things wrong with your code.
You aren't swapping anything
You have to swap the first half of the array with the second half, not swap the whole array. If you do that then everything gets swapped twice, so that nothing changes
You should print the reversed array after you have finished the reverse, not while you are doing the reverse.
Here's some code that fixes all these problems
# include <iostream>
# include <utility>
void reverse(int a[]);
int main()
{
int std[10] = {0,1,2,3,4,5,6,7,8,9};
reverse(std);
// print the array after reversing it
for (int i = 0; i < 10; ++i)
std::cout << std[i] << ' ';
std::cout << '\n';
}
void reverse(int a[])
{
for (int i = 0; i < 5; ++i) // swap the first half of the array with the second half
{
std::swap(a[i], a[9 - i]); // real swap
}
}
Yes you can.
I usually don't use "C" style arrays anymore (they can still be useful, but the don't behave like objects). When passing "C" style arrays to functions you kind of always have to manuall pass the size of the array as well (or make assumptions). Those can lead to bugs. (not to mention pointer decay)
Here is an example :
#include <array>
#include <iostream>
// using namespace std; NO unlearn trhis
template<std::size_t N>
void reverse(std::array<int, N>& values)
{
int index = 0;
// you only should run until the middle of the array (size/2)
// or you start swapping back values.
for (int i = values.size() / 2; i >= 0; i--, index++)
{
// for swapping objects/values C++ has std::swap
// using functions like this shows WHAT you are doing by giving it a name
std::swap(values[index], values[i]);
}
}
int main()
{
std::array<int,10> values{ 0,1,2,3,4,5,6,7,8,9 };
reverse(values);
for (const int value : values)
{
std::cout << value << " ";
}
return 0;
}
class Solution {
public:
int numSquares(int n) {
int dp[n+1];
for(int i=0;i<=n;i++) dp[i]=0; //initializing all the elements to zero
for(int i=1;i<=n;i++){
int t = INT_MAX;
for(int j=1;j<=(int)sqrt(i);j++){
t = min(t,dp[i-j*j]);
}
dp[i] = t+1;
}
return dp[n];
}
};
The above method works perfectly fine but when I tried to initialize the array like this
int dp[n] = {0} //variable sized array cannot be initialized
I am getting error like variable sized array cannot be initialized .
Is there any why to initialize this array instead of using for loop and please explain me why I am getting this error?.
The problem is that in C++, the size of an array must be a compile time constant. So,
int n = 10;
int arr[n] ; //incorrect
The correct way would be:
const int n = 10;
int arr[n]; //correct
You can solve your problem by using:
const int n = 10;
int arr[n] = {0}; //correct now because n is a constant expression
Some more examples:
void func(int n)
{
int arr[n] = {0}; //incorrect because n is passed as a function argument and is therefore not a compile time constant
}
Another example
int n;
cin >> n;
int arr[n] = {0}; //incorrect
You can use std::vector as it is a dynamic sized container.
what are all the different ways to initialize a c++ array?
They are:
default initialisation (which means "no initialisation" in case of trivial objects)
list initialisation
value initialisation (which is list initialisation with an empty list)
why I am getting this error?.
Your program is ill-formed. The size of an array variable must be compile time constant, but n+1 is not.
You are using a language extension. As the error message implies, the language extension doesn't allow all forms of initialisation to be used. You can use default initialisation i.e. "no" initialisation as you did in the first code example.
but what if you are getting the array size as a parameter in a function in class?
Then create a dynamic array. I recommend using std::vector.
what are all the different ways to initialize a c++ array?
That's described here: Aggregate initialization.
The main problem is that VLA:s (variable length arrays) do not exist in standard C++ so instead of int dp[n+1]; you should use std::vector<int> dp(n+1);
Example:
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
class Solution {
public:
int numSquares(int n) {
std::vector<int> dp(n + 1); // instead of `int dp[n+1];`
// for(int i=0;i<=n;i++) dp[i]=0; // no need
for(int i = 1; i <= n; i++) {
int t = INT_MAX;
for(int j = 1, end = (int) std::sqrt(i); j <= end; ++j) {
t = std::min(t, dp[i - j * j]);
}
dp[i] = t + 1;
}
return dp[n];
}
};
I get an error under "int dArray[size]" saying that size needs to be a constant. Can someone explain what that means exactly?
I want it to be an array of size 4 and output 1, 3, 5, and 7.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int dArray[size];
for (int i = 0; i <= size; i++){
dArray[i] = value;
value + 2;
}
}
int main(){
AllocateArray(4, 1);
}
Solved:
Here is the code that ended up working.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int * Array = new int[size];
for (int i = 0; i < size; i++){
Array[i] = value;
value = value + 2;
}
for (int i = 0; i < size; i++){
cout << Array[i] << endl;
}
return Array;
}
int main(){
int *dArray = AllocateArray(4, 1);
}
In int dArray[size] size is not a constant value. Because of that you are getting that error. What you probably wanted to do was make a new array using a pointer and new like:
int * dArray = new int[size];
C++ requires that the size of arrays are determined at compile-time. As size is determined at runtime, the compiler complains.
If you are interested in having array-like behaviour with a size unknown at compile-time, then consider using std::vector.
The size of array should be a known constant in compile time, so that compiler can allocate correct memory for that array on the stack. Remember that such a declare is for stack variable. If you do want dynamic array, try std::vector.
You have to declare the size of an array using numbers, #define or const unsigned int. Otherwise they are considered variable length arrays.
Example:
const unsigned int MAX_ARRAY_SIZE = 14;
double my_array[MAX_ARRAY_SIZE];
My compiler keeps saying that 'small' and 'x' were not declared in this scope, how do I fix my array so that they are accurately displayed? overall the code is supposed to find the smallest positive nonzero value stored in the array.
#include <iostream>
#include <string>
using namespace std;
int findthesmall( int small[x], int y)
{
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
I think you need:
int findthesmall( int* small, int y) {
Try this:
int findthesmall( int small[], int y) {
for(int i=0; i< y; i++){
for(int j=0; j< y; j++){
int temp = small[i];
if( small[i] > small[j] )
small[i] = small[j];
small[j] = temp;
}
}
return small[0];
}
int main(){
return 0;
}
int small[x]
This is illegal for 2 reasons.
Like your compiler says, X is undefined
Size of the array cannot be set to the value of a non compile time constant.
To fix this you can do what #ajon suggested( pass array as pointer + length), it is historically the way to pass arrays.
There are other better ways in C++ though.
You can consider using std::array or std::vector. Both of them can be passed as you would any other variable, know their own size, and can be accessed like a normal array
Or you could use template code to capture the size of the array automatically.
template<int len>
int findthesmall(int (&small)[len]){
The 2nd option maybe a little convoluted and more complex than other options, especially now that you have got your answer, I'm just including it here for completeness.
Apart from other answers, there is also a bug in the logic. If your function is just to find the smallest element as function name indicated, one for loop should be enough.
Sample code presented below:
int findthesmall( int small[], int y)
{
int temp = small[0];
for(int i=1; i< y; i++)
{
if( temp > small[i] )
temp = small[i];
}
return temp;
}
Or you could use std::min_element algorithm as well
std::cout << *std::min_element(small, small+y) << std::endl;
int M=7;
int N=6;
int i=0;
int x=N*M;
int val3[x] = {};
for(int i=0;i<x;i++)
{
//some calculations
if (my condition)
{
//if this condition ok, change value of val[i]
}
cout << i << " " << val[i] << endl;
}
I want to initialize a zero array(val), I used above codes, but I got an error which says variable size object may not be initialized. is it not possible to initialize zero array? need your help....thanks
C++ does not include variable-length arrays; int val3[ x ] with x non-constant is a feature of C99. Not all C99 features are part of C++. Try using std::vector.
#include <vector>
// contains an array of length x, automatically filled with zeroes
std::vector< int > val3( x );
int val3[x] = {};
C++ doesn't allow arrays to be initialized with a variable that isn't a compile-time constant. Use a const int for all the variables (except i).
Btw, you don't use that first int i (outside the loop).
Alternatively to the std::vector suggested above, you could also do:
int M=7;
int N=6;
int x=N*M;
int* val3 = new int[x];
memset(val3, 0, x * sizeof (int));
for (int i = 0; i < x; i++)
{
// ...
}
// ...
delete [] val3;