how to initialize an array without any error? [closed] - c++

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 9 years ago.
Improve this question
My code is following for finding maximum in an array
#include <iostream>
using namespace std;
int main(){
int i;
int array[i]={1,2,3,4,5}
int temp;
for(int i=0;i<6;i++)
{
if(array[i]>temp)
temp=A[i];
}
cout<<"the maximum number is "<<temp<<endl;
return 0;
}
but im getting error in line of initializing array why is that so? how do we initialize array?

You can't define the size of an array with a runtime variable.
To fix this you can use constexpr:
constexpr int i = 5;
int array[i]={1,2,3,4,5};
or:
int array[]={1,2,3,4,5};
In the latter the size is deduced by the compiler.
Otherwise, if you need a runtime size, you'll have to use std::vector or any other "dynamic" container from the standard library:
int i = ...;
std::vector<int> array(i); // reserve `i` cells

try this :
int array[]={1,2,3,4,5};

First of all variable i was not initialized
int i;
So it has some arbitrary value.
Secondly the size of a defined array shall be a constant exprssion. So even if i would be initialized this definition
int array[i]={1,2,3,4,5}
is also invalid. Moreover you forgot to place a semicolon after the closing brace.
Also you did not initialized variable temp
int temp;
And at last this control statement of the loop
for(int i=0;i<6;i++)
is also incorrect because the array has only 5 elements.
And one more identifier A was not declared
temp=A[i];
The correct code could look as
#include <iostream>
using namespace std;
int main()
{
const int N = 5;
int array[N] = { 1, 2, 3, 4, 5 };
int max = array[0];
for ( int i = 1; i < N; i++ )
{
if ( max < array[i] ) max = array[i];
}
cout << "the maximum number is " << max << endl;
return 0;
}

Related

How do i set an array to have custom lenght? [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 2 years ago.
Improve this question
I am getting an error when i run this code. The error code is 0xC00000FD and I can't seem to find a fix for what i need. Can someone please help me? Here's the code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n;
int arr[n];
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
There are two major problems in your code. First, C++ does not have "variable length arrays" (VLAs), although some compilers support them as an extension.
More importantly, even if your compiler does support them, you are attempting to define the size of your arr before you have read the value of n.
To fix these issue you should: (a) use the std::vector container, rather than a plain array; and (b) only declare that after you have read in the value of n.
Here's a 'quick fix':
#include <iostream>
#include <conio.h>
#include <vector> // For the "std::vector" definition
using namespace std;
int main()
{
int n;
// int arr[n]; // Here, the value of "n" is undefined!
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
std::vector<int> arr(n); // This can now be used 'almost' like a plain array
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
Standard C++ does not support variable length arrays. std::vector can accomplish what you want. It is also possible to allocate memory of the desired size with new int[size] and use a pointer to reference the data rather than an array. However, this doesn't have any bounds checking, so there is the possibility of memory corruption. And the allocated memory must be explicitly freed with delete[]. So std::vector is my preferred solution.

C++ Array passing to function with size [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 2 years ago.
Improve this question
I am writing C++ code to get the maximum number from an array of integers using a function.
My code is as follows, but it's not working and I can't seem to fix it, I would like to know, if possible, what's wrong with it:
#include<iostream>
using namespace std;
int maxfunc(int myArr, int size);
int main()
{
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
for(int i=0; i<size; i++)
{
cout<<"Value No. "<<i+1<<" : ";
cin>>arr[i];
}
int max = maxfunc(arr,size);
cout<<"max = "<<max;
}
int maxfunc(int myArr, int size)
{
int largest=myArr[0];
for(int i=1; i<size; i++)
{
if(largest<myArr[i])
{
largest=myArr[i];
}
}
return largest;
}
In
int maxfunc(int myArr, int size)
The argument int myArr is an integer but you are using it as an array of integers.
I would use a pointer to the original array:
int maxfunc(int *myArr, int size)
Another problem that stands out is that you are using size variable uninitalized, my gess is that you are missing a cin >> size;:
cout<<"Enterv the size of array: ";
cin >> size;
Finally, and this is opinion based, this is the kind of program you would use in C, for C++ there are better tools for storing a manipulating data. For this case I would recommend std::vector or if the array is ment to have fixed size, std::array.
You did not entered the size of the array
int size;
cout<<"Enterv the size of array: "<<size;
int *arr=new int [size];
So the program has undefined behavior.
Also the function implementation is wrong because in general the user can pass the second argument equal to or less than 0.
The function should be declared like
size_t maxfunc( const int myArr[], size_t size);
^^^^^^^^^^^^^^^^^
and it should return the index of the maximum element.
The function can be implemented like
size_t maxfunc( const int myArr[], size_t size )
{
size_t largest = 0;
for ( size_t i = 1; i < size; i++ )
{
if ( myArr[largest] < myArr[i] )
{
largest = i;
}
}
return largest;
}
And in main you can write
size_t max = maxfunc( arr, size );
cout << "max = " << arr[max] << '\n';
delete []arr;
Do not forget to free the allocated memory.
Pay attention to that in C++ there is the standard algorithm std::max_element declared in the header <algorithm> that does the task. It returns iterator that points to the maximum element.

I have to calculate difference of sum of diagonal elements of a square matrix [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 4 years ago.
Improve this question
In the following program:
#include <iostream>
#include <cmath>
using namespace std;
int diagonalDifference(int x[][],int n)
{
int sum1=0,sum2=0,y;
for(int i=0;i<n;i++)
{
sum1+=x[i][i];
sum2+=x[i][n-1-i];
}
y=abs(sum1-sum2);
return y;
}
int main()
{
int n,**z;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>arr[i][j];
}
}
z=diagonalDifference(arr,n);
cout<<x;
return 0;
}
I get a compilation error I don't understand.
error:declaration of 'x' as multidimensional array must have bounds for all dimensions except the first
Could you help me fix it?
int[][] is not a valid type:
int diagonalDifference(int x[][],int n)
You declare z as an int**:
int n,**z;
But you assign it an int:
int diagonalDifference(int x[][],int n);
z=diagonalDifference(arr,n);
And finally you print x which does not exist:
cout<<x;
As rules of thumb:
declare only one variable per line, and give it a meaningful name;
declare what possibly can as const;
Don't use C-style arrays unless you have to; prefer std::vector for instance;
don't use using namespace std;
much more you need to learn.
.
int diagonalDifference(int x**,int n) { /* .... */ }
int matrix_size = 0;
std::cin >> matrix_size;
std::vector<std::vector<int>> matrix{matrix_size, std::vector<int>{matrix_size}};
/* fill the matrix */
const int diag_diff = diagonalDifference(matrix, matrix_size);
std::cout << diag_diff << '\n';

Cannot convert 'int*' to 'int**' for argument '1'? [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 6 years ago.
Improve this question
I am trying to write a program which prints the cubes of inserted elements of array, and then prints the sum of elements divisible by 2, and not divisible by 3.
#include <iostream>
#include <math.h>
using namespace std;
void kub(int *niz[], int n)
{
int i=0;
while(i<n)
{
*niz[i]=pow(*niz[i],3);
i++;
}
}
void unesi(int* niz[],int n)
{
int i=0;
while(i<n)
{
cin>> *niz[i];
i++;
}
}
void stampaj(int* niz[],int n)
{
int i=0;
while(i<n)
{
if ((*niz[i]%2)==0 && (*niz[i]%2)!=0)
cout<<*niz[i]<<endl;
i++;
}
}
int main()
{
int n;
cin>>n;
int niz[n];
unesi(niz,n); /* <<= here */
kub(niz,n);
stampaj(niz,n);
return 0;
}
Everything is fine, until this line of code (marked "<<= here"): "unesi(niz,n);" What am I doing wrong?
Instead of:
void unesi(int* niz[],int n)
try:
void unesi(int niz[],int n)
niz[] decays to pointer, so no need to pointer to pointer
Same for the other functions. Last note, instead of cin>> *niz[i]; just use cin>> niz[i];
In C++,
int* nix[]
is actually translated into
int** nix
at compile time. To fix this you can use either
int* nix
int nix[]
Also in the function body you would probably need to change
*nix[i]
into
nix[i]

the sum of the first five natural numbers [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 9 years ago.
Improve this question
I wanna get the sum of the first five natural numbers, but there in this this code something is wrong, need to find the misstake ? Help
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i = 1, thesum;
while(i <= 5)
{
thesum += i;
i++;
}
cout << thesum;
return 0;
}
You haven't initialized thesum variable. Initialize it to 0.
int i = 1, thesum = 0;
Otherwise it will invoke undefined behavior.
As it was already pointed out you did not initialize local variable thesum. So it has some arbitrary value.
Also there is no any need to include header <cstdlib> because no one declaration from it is used.
As variable i is not used outside the loop it is better to make it a local variable of the loop.
So I would rewrite the program the following way
#include <iostream>
using namespace std;
int main()
{
const int N = 5;
int theSum = 0;
for ( int i = 0; i < N; i++ ) theSum += i + 1;
cout << "The sum of first " << N << " natural numbers is " << theSum << endl;
return 0;
}