Reverse of an array Hackerrank - c++

This is a syntax of a program that I made of hackerrank to reverse an array. The location of the question is Practice < Data Structures < Arrays < Arrays - DS
the program seems to work fine on an online compiler but is showing error over hackerrank.
can anyone guide me where I went wrong?
#include<iostream>
using namespace std;
int main(){
int n,i;
int arr[n];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}

You are creating an array with n elements before you read n, i.e n is having garbage value. Here is correct working code.
#include <iostream>
using namespace std;
int main(){
int n,i;
cout<<"Enter number of elements"<<endl; // Comment it if you don't want debug console outut
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements"<<endl; // Comment it if you don't want debug console outut
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}

I changed your solution and it work fine now , i will tell you some notes for your future:
1 - You have to read size of array first before declare array as mentioned in comments by #HolyBlackCat , otherwise it will give garbage value.
2 - this command int arr[n]; won't work on all Compilers and may give you an Error. Is there a solution to declare array without specific size ? Yes , you can use Vector like that vector<int> arr(n);but you have to include library of vector first #include<vector>
3 - In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. On most operating systems returning 0 is a success status like saying "The program worked fine". So you have to write return 0; in the end of your program.
#include<iostream>
#include<vector> // must include to use Vectors
using namespace std;
int main(){
int n;
cin >> n; // Must read size of array first , otherwise it will give it garbude value
vector<int> arr(n); // instead of int arr[n]
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
for(int i = n-1 ; i >= 0 ; i--)
cout << arr[i] << " ";
cout << endl; // to print new line as mentioned in the problem statement
return 0; // Prefer to use it always
}
Hope that helps you and Good Luck.

The exercise of Hacker Rank needs that you reverse an array of integers, might you have a problem with the variable size array, cause some compilers support this characteristic but others not.
And Hacker Rank do not support some properties in other languages like JS , Hacker Rank do not support prompt() for take an input.
In any case for fix this error you can use vector class.
#include<iostream>
#include<vector>//Include library vector for dynamic size of array
using namespace std;
int main(){
int n;
cin>>n;
vector<int> arr(n);//Declare the vector with a max size n
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i = n-1 ;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
This code has passed al test cases of hackerRank
All the test on hackerRank had passed

Related

timeout: the monitored command dumped core

i am running this code in online compiler showing dumped core error this program finding highest product of two pair.
#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}
int main()
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
while(t--){
for(int i=0; i<n;i++){
cin>>arr[i];
}
}
maximumproductpair(arr,n);
return 0;
}
in code everything fine then why this error?
Mistake 1
The problem is that your t and n variables are uninitialized. This means both t and n have garbage value. And when you wrote:
int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value
You have undefined behavior because n has garbage value.
This is why it is advised that
always initialize built in types in local/block scope.
Mistake 2
Second, note that in C++ the size of an array must be a compile-time constant. So take for example the following code snippets:
int n = 10;
int array[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int array[n]; //CORRECT
Similarly,
int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression
Also note that some compilers provide compiler extension that lets you have variable length array. You can read more about it at Why aren't variable-length arrays part of the C++ standard?.
If you want to take the size of the array as input from the user then you should use dynamic sized containers like std::vector :
int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int
Also see Why should I not #include <bits/stdc++.h>?.

Segmentation fault(code dumped) in c++ after several try I cann't get the solution

#include <iostream>
using namespace std;
int main() {
int T,D;
long long int N;
long long int a[N];
long long int b[D];
cin>>T;
for(int i=0;i<T;i++)
{
cin>>N>>D;
for(int i=0;i<N;i++)
{
cin>>a[i];
}
for(int i=0;i<D;i++)
{
b[i]=a[i];
}
for(int i=0;i<(N-D);i++)
{
a[i]=a[i+D];
}
for(int i=0;i<D;i++)
{
a[i+N]=b[i];
}
for(int i=0;i<N;i++)
{
cout<<a[i];
}
cout <<endl;
}
return 0;
}
Why is this coding having segmentation fault? I have seen many solution but cann't get it right.On visual studio or any other application it is not working but on gfg it is working. Please help me solve this problem
There are several things that are wrong.
C-style arrays must be set at compile time. So if you want to use int a[N], N must to known at compile time. If you want a flexible array, one C++ way is to use std::vector.
Then the array a goes from 0 to N-1. So going a[N] is going too far. So a[i+N] is way out if bounds and will be segfault.
you declare array a with N element, but use index out of the array range.
long long int a[N]; // declare here, maximum element is N
for(int i=0;i<D;i++)
{
a[i+N]=b[i]; // use index out of array a
}

C++ problem where the value assigned to a variable is getting changed even though it hasn't been modified yet [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 1 year ago.
Please help me with this strange problem where the input value is given as 4 (i.e. n = 4) and after a for loop the same value is getting displayed as 2, but why? It was not used anywhere (AFAIK) and it shouldn't get changed (I have no clue about it).
The original problem on HackerRank.
MY CODE >>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int arr[n];
cin >> n; // input given from stdin is 4
cout << n << "\n"; // outputs 4
for(int i=0; i<n; i++){
scanf("%d",&arr[i]);
}
cout << n << "\n"; // outputs 2 (but why?)
for(int i=n-1; i>=0; i--){
printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
}
return 0;
}
Thank you for any help!
int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
First of all, that's not even legal in C++. As a gcc extension to support C style VLA's, what is the value of n when the array declaration is seen? You have not read it yet!!
Instead, use:
int n;
cin >> n;
std::vector arr(n);
Although this still is not the "C++ way" as you are pre-defining the entire collection and then assigning to each element in turn; as opposed to adding each element to the collection. This is not a big deal with an int but more generally you don't want dead unused items in a collection; rather they simply don't exist at all.
std::vector arr; // don't pre-allocate any size
for(int i=0; i<n; i++){
int val;
scanf("%d",&val); //<<< uhhhhhh. you know about `cin` why this?
arr.push_back(val);
}

Reverse an Array but i'm getting a segmentation error

What am I doing wrong ???
It is giving me an error of segmentation fault .
I don't know what memory i'm accessing ??
#include <iostream>
using namespace std;
int main() {
int t;
int n;
int arr[n];
cin>>t;
cin>>n;
// taking array elements from user
for(int i=0; i<n;i++)
{
cin>>arr[i];
}
// reverse of the array
for(int i=n-1; i>=0;i--)
{
cout<<arr[i];
}
//code
return 0;
}
int n;
You've default initialised this variable. Thus, the value is indeterminate.
int arr[n];
Here, you use that indeterminate value. Thus, the behaviour of the program is undefined.
There are "data flow" languages where using a variable will stop execution waiting for you to initialise it later and continue. C++ isn't such language. You must initialise everything before using the value.
Besides that, n isn't a compile time constant expression. Because the size of the array variable isn't compile time conastant, the progarm is ill-formed in C++.
If you want an array to have a dynamic size, you can use dynamic storage. Simplest way to create a dynamic array is to use std::vector.
For starters you are trying to declare a variable length array
int n;
int arr[n];
Variable length arrays is not a standard C++ feature. Moreover you are using an uninitialized variable n as the size of the array.
Either declare the array with an expected maximum size or use standard container std::vector<int>. At least you should write provided that the compiler supports variable length arrays
int t;
int n = 1;
cin>>t;
cin>>n;
if ( n < 1 ) n = 1;
int arr[n];
//...
Also you are not reversing an array. You are trying to output an array in the reverse order.
To reverse an array you could use standard algorithm std::reverse or you can write an appropriate loop yourself as for example
for ( int i = 0; i < n / 2; i++ )
{
// or use std::swap( arr[i], arr[n-i-1] );
int tmp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = tmp;
}
and then you can output the reversed array.
You are not allowed to define array with Unknown size in C++ so int arr[n]; is Wrong! and if you have to use arrays and not know the size of it , you should use dynamic array with Pointers like this : int* a = new int[n] and also Deallocate Heap memory with Delete []array_name at end of your program and if it is possible for you not use arrays It's better for you use vectors because the size of it is dynamic.
look at this with vectors :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//by : Salar Ashgi
int main()
{
int k;
cout<<"Enter number of elements ?\n";
cin>>k;
vector<int> v;
cout<<"--------------------\n";
int x;
for(int i=0;i<k;i++)
{
cout<<"Enter num "<<i+1<<" : ";
cin>>x;
v.push_back(x);
}
reverse(v.begin(),v.end());//algorithm.h
cout<<"Reverse : \n";
for(int i=0;i<k;i++)
{
cout<<v[i]<<" ";
}
}

No output when running program in c++

I wrote a program of Insertion sort in c++ but output screen does not showing any Statement.I am facing this problem in few another program.
This is the code:
#include<iostream>
using namespace std;
int main()
{
int n;
int arr[n];
cout<<"Enter the number of the element of the Array:";
cin>>n;
cout<<"Enter the element of the Array:";
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
int current=arr[i];
int j=i-1;
while(arr[j]>current && j>=0){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=current;
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}cout<<endl;
return 0;
}
You are using the value of n before it has a value. Change your code to this
int n; // n does not have a value
cout<<"Enter the number of the element of the Array:";
cin>>n; // n gets value here
int arr[n]; // n is used here
You cannot use any variable before it has a value. That's a fundamental rule of C++.
You cannot creat variable C-style arrays during run time.
You should either create them with the new operator or switch to STL containers like std::vector.