Declaring array inside 'else' scope gives wrong answer

While using C++ to solve problem CARVANS, the following solutions gave different answers. I don’t know why. I am new to C++, so help me.

Problem Link:
https://www.codechef.com/LRNDSA01/problems/CARVANS

The following codes were tested on sample testcase given in the problem.

1st code:

#include <iostream>
using namespace std;

int main()
{
	int t;
	std::cin >> t;
	int n;
	int slowest;
	int count;
	while (t--)
	{
	    std::cin >> n;
	    if (n == 1) std::cout << 1 << std::endl;
	    else
	    {
	        int nl[n];
	        for (int i = 0; i < n; i++) std::cin >> nl[i];
	        count = 1;
	        slowest = nl[0];
	        for (int i = 1; i < n; i++)
	        {
	            if (slowest >= nl[i]) { count++; slowest = nl[i]; }
	        }
	        std::cout << count << std::endl;
	    }
	}
	return 0;
}

2nd code:

#include <iostream>
using namespace std;

int main()
{
	int t;
	cin >> t;
	
	while (t--)
	{
	    int n;
	    int slowest;
	    cin >> n;
	    
	    int nl[n];
	    for (int i = 0; i < n; i++) cin >> nl[i];
	    
	    int count = 1;
	    slowest = nl[0];
	    
	    for (int i = 1; i < n; i++)
	    {
	        if (slowest >= nl[i]) { count++; slowest = nl[i]; }
	    }
	    cout << count << endl;
	}
	return 0;
}
1 Like

The line which includes the header file has changed to “#include”. Don’t know why.

It’s because you’re not using code formatting :slight_smile:

4 Likes

Thanks for the “code formatting” tip; I’ll use it in future.
But my question is why the two codes above give different answers?

Nothing to do with where the array is declared; everything to do with reading the input wrongly :slight_smile:

In the first code, with the sample Test Input, for the first test case, N=1 so you don’t read the value of the car max speed (10), which means that this 10 will be left unread until the next test case, where it will erroneously be read into N!

To see this, add:

cout << "n: " << n << endl;

immediately after the line:

        std::cin >> n;

and run your code with the sample Test Input.

4 Likes

I got it; It was my mistake. Thank you for the help.

1 Like