0

When I put 1000000000000 as the input the program terminates, and does not allow the user to enter x.


#include <bits/stdc++.h> 
using namespace std; 
int main(){
  int n;
  cin>>n;
  int arr[n];
  int x;
  cin>>x;
  int k=0;
  for (int i = 1; i <= n; i+=2)
  {
    arr[k]=i;
    k++;
  }

    for (int j = 2; j <= n; j+=2)
    {
      arr[k]=j;
      k++;
    }
  

 cout<<arr[x-1];
}

I was expecting to be able to enter the second input after 1000000000000.

  • 2
    `1000000000000` is way way too large for the stack. Do you really have several TB of virtual memory? – drescherjm Oct 29 '22 at 13:46
  • 3
    Also `1000000000000` is too large for `int` in most environments. – wohlstad Oct 29 '22 at 13:47
  • 2
    Try `std::vector arr(n);` . And make sure to build as a 64-bit application, as you are trying to allocate some 4GB of memory. – Igor Tandetnik Oct 29 '22 at 13:47
  • 2
    Note that VLAs are not part of standard C++. [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/q/1887097/12122460) – kotatsuyaki Oct 29 '22 at 13:48
  • Upon closer inspection, the whole program doesn't make much sense. It's busy filling millions of array elements with predictable values, only to print exactly one of them in the end. It could have easily computed just this one value. You don't need an array at all. – Igor Tandetnik Oct 29 '22 at 13:52
  • *"and does not allow the user to enter x."* This is true. After some input fails, like the value is too big for the type, `cin` enters a "failed state" and will not input anything more until the state is cleared by the program. – BoP Oct 29 '22 at 13:53
  • @wohlstad I tried long long and I faced the same problem – Omar Mokhtar Oct 29 '22 at 13:54
  • @Igor Tandetnik Yes I just noticed that it can be solved using o(1) instead of o(n^2) – Omar Mokhtar Oct 29 '22 at 13:57
  • The algorithm shown is `O(n)`, not `O(n^2)`. But yes, it can be easily done in `O(1)` – Igor Tandetnik Oct 29 '22 at 13:59

1 Answers1

1

Your program has some errors, which even do not allow for compilation.

I added comments to your source code to show yout the problems:

#include <bits/stdc++.h>    // This is not a C++ header. it is a comiler extension. Do not use it
using namespace std;        // Do not use it. Always use scoped identifiers
int main() {
    int n;                  // Too small to hold the expected value
    cin >> n;               // No input check (Try to ebnter "abc"), Always check result of input
    int arr[n];             // This is not C++. No C++ compliant compiler will compile this
    int x;                  // Variable not initialized
    cin >> x;               // No check for valid input and no check for x must be smaller than n  
    int k = 0;              
    // ----- All not necessary. Can be solved mathematically
    for (int i = 1; i <= n; i += 2)
    {
        arr[k] = i;
        k++;
    }

    for (int j = 2; j <= n; j += 2)
    {
        arr[k] = j;
        k++;
    }
    // -------
    cout << arr[x - 1];     // potential out of bounds
}

Then, of course your desired input value is too big. You can most probably not allocate a 4 TeraByte array on your computer. It does not have enough memory. With a "big" machine and "swapping" it could work. But for nomal machines, it will not work.

Then, next, you need always to check the result of an IO operation.

In your case, you try to read a huge number into an int variable. The input stream will fail and do nothing any longer. You cannot read additional values after that. You would need to call std::cin.clear() to continue.

So, always check the result of your IO operation. But how?

You need ot understand the streams >> operator a little bit. Please read here about that. It is especially important to understand that all those "extraction" expressions, like "someStream >> x" always return a reference to a stream. So "someStream >> x" will extract a value from the stream, format it to the expected type given by the varible "x" and then assigns the value to "X".

And, it will always return a reference to the stream, for which it was called with. In this case a reference to "someStream".

If it cannot do this extraction or formatting, because you enter an invalid value, for example "abc" for an integer or a huge number for an integer, then the operation would fail.

And there are 2 functions of the stream, that you can use to check the state of the stream.

  1. operator bool. This will return true, if there is no error
  2. operator!. This will return true, if there was an error

With that: If you write if (cin >> n), then the expression in the brackets is evaluated. It tries to read "n" from "cin". After that it returns a reference to "cin". Now the statement would look like if (cin). The if statement expects a boolean expression. Hence, the bool function of the stream will be called, and give you the information, if the operation was successfull or not.

Summary. Always check the result of IO operations.

Back to your code. Making it compilable would be:

#include <iostream> 
int main() {
    long long n;
    std::cin >> n;
    int* arr = new int[n];
    int x;
    std::cin >> x;
    int k = 0;
    for (int i = 1; i <= n; i += 2)
    {
        arr[k] = i;
        k++;
    }
    for (int j = 2; j <= n; j += 2)
    {
        arr[k] = j;
        k++;
    }
    std::cout << arr[x - 1] << '\n';
    delete[] arr;
}

But this is of course still nonesense. Because we do not need an array or loop at all. We can simply calculate the result.

See the final example code below:

#include <iostream> 
int main() {
    // Define working variables
    long long n{}, x{};

    // Read values and check input
    if ((std::cin >> n >> x) and (n > 0) and (x > 0) and (x <= n))

        // Show result    
        if (x > (n / 2))
            std::cout << ((x - (n / 2)) * 2) << '\n';
        else
            std::cout << (x * 2 - 1) << '\n';
    else
        std::cerr << "\n\n***Error: Invalid input\n\n";
}
A M
  • 14,694
  • 5
  • 19
  • 44