example code incompatible with gcc

I am able to run the following code on hackerrank's online compiler but I can't get it to work properly on my macbook's terminal (gcc compiler)

the code is meant to:
first ask for N, which is the number of elements in the array
then, allow you to enter N number of integers
finally, displays the array of integers in REVERSE


after specifying N = 5 (for example), the terminal just keeps accepting new entries beyond the first five.

could anyone advise me what I ought to change to get it to work properly?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
	int N, i=0;
	cin >> N;
	int *A = new int[N];
	while(cin >> A[i++]);
	while(cout << A[--N] << ' ' && N);
	delete[] A;
	
	return 0;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

int main()
{
    // first ask for N, which is the number of elements in the array
    std::size_t N ;
    std::cout << "number of elements in the array: " ;
    std::cin >> N ;

    if( N > 0 )
    {
        // then, allow you to enter N number of integers
        // vector: https://cal-linux.com/tutorials/vectors.html
        std::vector<int> array ;
        std::cout << "enter " << N << " integers\n" ;
        int number ;
        while( array.size() < N )
        {
            std::cin >> number ;
            array.push_back(number) ;
        }

        // finally, displays the array of integers in REVERSE
        // array.rbegin() to array.rend() : iterate in reverse
        for( auto iter = array.rbegin() ; iter != array.rend() ; ++iter )
            std::cout << *iter << ' ' ;
        std::cout << '\n' ;
    }
}
Looking at OP's code, your key problem is that C++ doesn't actually track how long an array of data is. Some compilers may do so for you, but the language itself does not require it.

So you would need some way to count how many loops have been made, and terminate the loop after N is reached. You could use a sentry variable in a while-loop, or you could use a for-loop which creates one specifically for that purpose.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
    int N = 0;
    cin >> N;
    int * A = new int[N];
    for(int i = 0; i < N; i ++)
    {
        cin >> A[i];
    }
    for(int i = N - 1; i >= 0; i --)
    {
        cout << A[i] << " ";
    }
   delete []A;
}


A c-string is tricky in that they are zero terminated which allows counting its length, and that zero termination is done automatically by most compilers when assigning a value to a string.
"this is a zero terminated c string\0"
It is actually possible to create a non-zero terminated c string, and this would wreak havoc on many string related functions that rely on it. It's not possible to zero terminate a regular array because zero is a valid number, so it can't have another meaning... I hope that made sense.

Edit: Looking at OP's username and use of vectors in a previous post, I think this may be a troll post. I ban myself from posting while drowsy.
Last edited on
@newbieg - are you sure about L13?

Perhaps to display in reverse order:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main() {
	size_t N {};

	std::cin >> N;

	const auto A {new int[N]};

	for (size_t i = 0; i < N; ++i)
		std::cin >> A[i];

	for (size_t i = N; i > 0; --i)
		std::cout << A[i - 1] << " ";

	delete[] A;
}

Last edited on
I started with some pseudo code, then edited a couple of times. Not sure what version you saw. I probably shouldn't be posting after taking a sleeping pill, I'm a bit loopy myself. Hmm. Actually I'm still editing my summary as well, so things are still changing there too.

Anyway, my goal is to match the current experience level of OP; I was thinking the the use of vectors, iterators, auto, and size_t might cause confusion on top of the original question. JLBorges gave an excellent, professional answer, I just thought it might be a bit advanced.
Please double check my summary in a couple minutes too, thank you seeplus.

Should I have even mentioned c strings? I mean, they are an array, but ... I give up... Good night guys.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main() {
	int N, i=0;
	cin >> N;
	int *A = new int[N];
	while( cin  >> A[i++]        && N - i );
	while( cout << A[--N] << ' ' && N     );
	delete[] A;
}
> could anyone advise me what I ought to change to get it to work properly?

In addition to getting it tow work properly, it would be a good idea to focus on what you should be prioritising while learning C++.

Koenig and Moo in 'Rethinking How to Teach C++ Part 4: Emphasizing the Library'
We are reviewing our philosophy in some detail in the hope that others interested in teaching—or learning—C++ can understand the motivation behind our approach and consider adopting it themselves.

Three principles underlie our approach:

. Explain how to use language or library facilities before explaining how they work.

. Motivate each facility with a problem that uses that facility as an integral part of its solution. The problem must be interesting in its own right, and not merely constructed to demonstrate the facility.

. Present the most useful ideas first.

Our strategy so far has led us to describe three fundamental standard-library facilities— vector , string , and struct —before even mentioning built-in arrays or pointers. In doing so, we have shown how to write substantial programs.


In particular, even if a whole lot of people here (or elsewhere on the internet) promote it, try and avoid using explicit new and delete for now. Favour vectors over manually allocated dynamic arrays.

Sutter and Alexandrescu in 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices'
Use vector and string instead of arrays.
... Avoid implementing array abstractions with C-style arrays, pointer arithmetic, and memory management primitives. Using vector or string not only makes your life easier, but also helps you write safer and more scalable software.
...
Here are some reasons to prefer the standard facilities over C-style arrays:
• They manage their own memory automatically...
• They have a rich interface: You can implement complex functionality easily and expressively.
• They are compatible with C's memory model...
• They offer extended checking: The standard facilities can implement (in debug mode) iterators and indexing operators that expose a large category of memory errors. Many of today's standard library implementations offer such debugging facilities—use them!
• They don't waste much efficiency for all that...
• They foster optimizations: Modern standard library implementations include optimizations that many of us mere mortals have never thought of.
Last edited on
Instead of using new/delete - and you don't want to use std::vector (??) - then there is std::unique_ptr (and std::shared_ptr for advanced use). Using them means that delete {[]} is not required as the allocated memory is automatically deleted when the object goes out of scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <memory>

int main() {
	size_t N {};

	std::cin >> N;

	const auto A {std::make_unique<int[]>(N)};

	for (size_t i = 0; i < N; ++i)
		std::cin >> A[i];

	for (size_t i = N; i > 0; --i)
		std::cout << A[i - 1] << " ";
}

thanks for your advice, JLBorges
especially for highlighting <<Rethinking How to Teach C++ Part 4: Emphasizing the Library>>
i'll definitely read up on that.

and in addition to newbieg's suspicion that I might be trolling, pls allow me to introduce myself and also to mention how i'm learning.

my name is Lance Lee, i use the nick memepapa coz i own that domain name and the IG handle (plus i'm a dad of three)

and about how I'm learning.

I study the following books
Teach Yourself C++ in One Hour a Day by Siddharta
C++ A Beginners Guide by Herbert Schildt

i occasionally read C++ Primer, but it seems too advanced for my level right now.

i watch youtube videos by The Cherno, CodeBeauty etc

and for the past 5 days, i'v been attempting the coding challenges in Hackerranks

the question i posted here is from Hackerranks.

if you have any advice on how i might improve better, I'll be very appreciative.

Last edited on
We've had a bunch of troll/spammers recently, sorry for my rudeness.

For now you seem to have a good list of resources. I want to add Bucky's channel "ThenewBoston" to your resource list if he's not already there (https://www.youtube.com/playlist?list=PLAE85DE8440AA6B83). One or two of his C++ videos per chapter of your beginner's guide should be a good pace. (I realize you may have gone beyond a lot of his material already, maybe skim through his playlist for areas you haven't gotten to yet?)

One of the hardest parts about programming is that there are a thousand different paths you can study, but your books have a good outline to follow.
Welcome to the community memepapa, please ask any questions and we'll be happy to help.
Last edited on
thanks for welcoming me to the community, newbieg. Grateful

Yes, I'v been watching some of Bucky's youtube videos as well. now that you have mentioned him, I'll prioritize his over others when i search. thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

int main()
{
    int N = 5, i = 0;
    
    cout << "Enter size: ";
    cin >> N;
    int* A = new int[N];
    
    while(i < N)
    {
        cout << "Enter no. " << i << ": ";
        cin >> A[i];
        i++;
    }
    
    i = N;
    while(i > 0)
    {
        cout << A[i - 1] << ' ';
        i--;
    }
    
    delete[] A;
    
    return 0;
}


Enter size: 5
Enter no. 0: 1
Enter no. 1: 2
Enter no. 2: 3
Enter no. 3: 4
Enter no. 4: 5
5 4 3 2 1 Program ended with exit code: 0
thanks againtry,

I have learnt from your example
Topic archived. No new replies allowed.