0

Why am I not getting any output from this program?

I tried resolving every issue from YouTube and stack as well but no luck. I tried using vs code extensions and I don't if it has anything to do with JSON configurations.

This is not showing any errors but not showing any output as well.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main() {
  int n;
  cin >> n;
  int arr[n];

  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }

  const int N = 1e6 + 2;
  int idx[N];

  for (int i = 0; i < N; i++) {
    idx[i] = -1;
  }

  int minidx = INT_MAX;
  for (int i = 0; i < n; i++) {
    if (idx[arr[i]] != -1) {
      minidx = min(minidx, idx[arr[i]]);
    } else {
      idx[arr[i]] = i;
    }
  }

  if (minidx == INT_MAX) {
    cout << "-1" << endl;
  } else {
    cout << minidx + 1 << endl;
  }

  return 0;
}

Help me find the output of this program.

Jason
  • 36,170
  • 5
  • 26
  • 60
Zemo
  • 3
  • 4
  • 4
    What is your input? What is the expected output? `int idx[N];` is probably too large to allocate on the stack. Consider a `std::vector` instead. – Retired Ninja Jun 02 '21 at 06:08
  • Single-step through the code and examine the variable minidx before cout – StureS Jun 02 '21 at 06:12
  • 3
    VLAs are not part of C++ and are only provided by individual compiler extension. `int arr[n];` creates a VLA. A couple of other critical areas you won't find on youtube are [Why should I not #include ?](https://stackoverflow.com/q/31816095/3422102) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696). – David C. Rankin Jun 02 '21 at 06:16
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Biffen Jun 02 '21 at 06:24

5 Answers5

1

You get no output because your program doesn't run. Instead it crashes because of the too large array you're attempting to allocate on the stack. You would know it crashes if you were to debug it.

const int N = 1e6 + 2;
int idx[N];

One way of fixing it, which I don't recommend, is to allocate it on the heap:

int *idx = new int[N];
// ... continue as you were
delete[] idx;

The necessity of remembering to have to free the heap memory is why I recommend instead you use a vector

std::vector<int> idx(N);
// ... continue as you were

Either way solves the issue of the crash, and your program runs as expected. However, do take note of the advice being given in the comments above about non-standard VLAs and other bad practices.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • Side note: [Why are the terms “automatic” and “dynamic” preferred over the terms “stack” and “heap” in C++ memory management?](https://stackoverflow.com/questions/9181782) – user4581301 Jun 02 '21 at 06:38
  • For a small program like this I would also consider it reasonable to allocate `int idx[N];` with static storage duration. – user4581301 Jun 02 '21 at 06:42
1

Including bits/stdc++ is invalid, see Why should I not #include <bits/stdc++.h>?. Instead, include only the headers required by your code, e.g.

#include <iostream>
#include <climits>      /* for INT_MAX */
#include <algorithm>    /* for std::fill */

You may well be triggering your own error if you have a single invalid character (non-digit) in your input. You cannot use any input function correctly unless you check the stream-state following the input and handle .eof(), .fail() and .bad(). See std::basic_iostream (under Member Functions)

At bare minimum you need something similar to the following that exits the program on bad input. See std::basic_ios::rdstate for the errors corresponding to .eof(), .fail() and .bad() if you want to handle the error more elegantly.

    if (!std::cin >> n) {
        std::cerr << "error: invalid integer input 'n'.\n";
        return 1;
    }
    ...
    for (int i = 0; i < n; i++) {
        if (!std::cin >> arr[i]) {
            std::cerr << "error invalid integer input 'arr[i]'.\n";
            return 0;
        }
    }

Your int arr[n]; creates a C VLA (Variable Length Array). The C++ standard does not provide for VLAs and their use is only provided by non-standard compiler extensions.

As mentioned in the comments and other answers int idx[N]; will attempt to create an array of 1,000,000 integers with automatic storage duration that will exceed the stack size on windows (1M) and equal every bite of the total stack size on Linux (4M). You either need to use a container provided by the STL library like std::vector<int>, of declare idx as a pointer to int and allocate storage for idx with new. (you will then be responsible for freeing the memory with delete[].

If you did want to use allocated storage for both arr and idx, you can easily do so with:

    int *arr = new int[n];    /* VLAs are not part of the C++ standard, 
                               * either allocate for arr, or use std::vector
                               */
    ...
    /* 1e6 will exceed stack stize on windows (1M) and
     * will equal the total stack size on Linux (4M),
     * as with arr, allocate for idx, or use std::vector
     */
    const int N = 1e6 + 2;
    int *idx = new int[N];

You will later need to use delete[] to free the memory you allocated if not allocating in main() (which will be freed on exit).

Instead of looping to fill idx, C++ provides std::fill to handle the job. This reduces filling idx to:

    std::fill (idx, idx + N, -1);   /* use std::fill to initialize */

There are probably additional issues I've glossed over, which you can find and fix by simply using the proper compiler options. (in addition to checking that n <= N)

Always compile with warnings enabled, and do not accept code until it compiles without warning. To enable warnings add -Wall -Wextra -pedantic to your gcc/clang compile string (also consider adding -Wshadow to warn on shadowed variables). For VS (cl.exe on windows), use /W3. All other compilers will have similar options. Read and understand each warning -- then go fix it. All code you write as you learn C++ should compile without a single warning with full warnings enabled.

A full example that allocates as shown above would be:

#include <iostream>
#include <climits>      /* for INT_MAX */
#include <algorithm>    /* for std::fill */

int main()
{
    int n = 0; 
    
    if (!std::cin >> n) {
        std::cerr << "error: invalid integer input 'n'.\n";
        return 1;
    }
    
    int *arr = new int[n];    /* VLAs are not part of the C++ standard, 
                               * either allocate for arr, or use std::vector
                               */

    for (int i = 0; i < n; i++) {
        if (!std::cin >> arr[i]) {
            std::cerr << "error invalid integer input 'arr[i]'.\n";
            return 0;
        }
    }
    
    /* 1e6 will exceed stack stize on windows (1M) and
     * will equal the total stack size on Linux (4M),
     * as with arr, allocate for idx, or use std::vector
     */
    const int N = 1e6 + 2;
    int *idx = new int[N];
    
    std::fill (idx, idx + N, -1);   /* use std::fill to initialize */

    int minidx = INT_MAX;
    for (int i = 0; i < n; i++) {
        if (idx[arr[i]] != -1) {
            minidx = std::min (minidx, idx[arr[i]]);
        }
        else {
            idx[arr[i]] = i;
        }
    }

    if (minidx == INT_MAX) {
        std::cout << "-1\n";
    }
    else {
        std::cout << minidx + 1 << '\n';
    }
    
    delete[] arr;
    delete[] idx;
}

(note: you can #include <limits> and use std::numeric_limits<int>::max() instead of using the C INT_MAX macro)

Look things over and let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

I think that it would be a little bit easier to troubleshoot if you prompted for the inputs. I ran your code, and at first it seemed that nothing was being output, but that's because the input needed to be provided first.

Try changing your code to this:

#include<iostream>
#include<bits/stdc++.h>

using namespace std;

    int main()

{
    int n; 
    cout << "Input a number: ";
    cin >> n;
    int arr[n];

    for (int i = 0; i < n; i++)
    {
        cout << "Input a value: ";
        cin >> arr[i];
    }

    const int N = 1e6+2;
    int idx[N];

    for(int i = 0;i < N; i++)
    {
        idx[i] = -1;
    }

    int minidx = INT_MAX;
    for(int i =0; i < n; i++)
    {
        if (idx[arr[i]] != -1)
        {
            minidx = min(minidx, idx[arr[i]]);
        }
        else
        {
            idx[arr[i]] = i;
        }
    }

    if(minidx == INT_MAX)
    {
        cout << "The answer is " << "-1" << endl;
    }
    else
    {
        cout << "The answer is " << minidx + 1 << endl;
    }
    
    return 0;
    
}

You'll notice that based on the first number you enter, you will need to provide the second input that many times. When I ran it this way, I input 5 for the first number, and then 1, 2, 3, 4, 5. I got the output of "The answer is -1".

  • Also worth noting that `const int N = 1e6+2; int idx[N];` is a stack-killer on a Windows system where the default stack size is 1 megabyte. – user4581301 Jun 02 '21 at 06:32
  • 3
    Also worth explaining [Why should I not #include ?](https://stackoverflow.com/q/31816095/3422102) and why C++ does not support `int arr[n];` (except by non-standard compiler extension) – David C. Rankin Jun 02 '21 at 06:36
  • 1e6+2 is only a million and 2 if I'm not mistaken, that should run just fine. I ran it in an online terminal and it executed in less than a couple of seconds – Tanner Stratford Jun 02 '21 at 06:42
  • 1
    One million times a minimum of 2 bytes per `int` easily blows off the top of a 1 MB stack without any other variables. – user4581301 Jun 02 '21 at 06:45
  • Still there is no output to this program – Zemo Jun 02 '21 at 06:46
  • Even after using your code I am not able to get any output from this – Zemo Jun 02 '21 at 06:46
  • 1
    What are you putting for the inputs? – Tanner Stratford Jun 02 '21 at 06:47
  • https://stackoverflow.com/questions/2338778/what-is-the-maximum-length-of-an-array-in-net-on-64-bit-windows#:~:text=3%20Answers&text=An%20array%20could%20theoretically%20have,single%20object%20restriction%20in%20the%20. – Tanner Stratford Jun 02 '21 at 06:56
  • 1
    C++ and .Net are different things. C++ has no specific limit on the number of elements, though an implementation might. .Net looks like it implies a limit. I don't know my .Net well enough to know if that limit only refers to managed arrays or also applies to unmanaged arrays. – user4581301 Jun 02 '21 at 07:28
  • Regardless, in C++, `idx` is an automatic variable scoped by `main`. It resides in Automatic storage, typically a stack, and the default Windows stack size is 1MB. Other implementations or operating systems may allocate a larger stack. Typical Linux desktop systems default to 8 or 10 MB. So even though the system may allow an array of 2 billion elements, you might run out of storage to hold more elements after a few thousand, a few hundred thousand, a few million, or more, depending on the system. – user4581301 Jun 02 '21 at 07:28
-1

The solution is very simple.

const int N = 1e6 + 2; // in place of this use
const int N = 1e5 + 2; //Use this
Tapesh
  • 1
  • 1
  • 2
  • Please explain your answer. Code only answers are less useful. – Eran Aug 29 '21 at 06:41
  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Aug 29 '21 at 06:42
  • I was also stuck in this code. But after many trials and research, I get to know that arr size 1e6 is much larger. So I reduced the array size to 1e5. – Tapesh Oct 26 '21 at 10:35
-1
const int N=1e2; 

change the size of cont int N = 1e2; or u can apply 1e2 or 1e3 to