CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Sep 2018
    Posts
    4

    Question Reversing array in C++

    Hi, I am new on this forum and in this field of programming as well.
    I was facing problems while coding so I searched for forums where I could ask questions related to programming and found this one.

    Please check this piece of code and lemme know what is the fault in it? My purpose is to reverse the array given by the user.

    Code:
    #include <iostream>
    using namespace std;
    void reverseArray(int *arr, int size)
    {
    	int *Copy_arr = new int[size];
    	int temp;
    	for (int i = 0; i < size; i++)
    	{
    		Copy_arr[i] = arr[i];
    	}
    
    	for (int i = 0; i < size; i++)
    	{
    		temp = arr[i];
    		arr[i] = arr[(size - 1) - i];
    		arr[(size - 1) - i] = temp;
    		
    		
    	}
    	
    
    	cout << "Array before function call was: ";
    	for (int i = 0; i < size; i++)
    	{
    		cout << Copy_arr[i] << " ";
    	}
    	cout << endl << "Array after function call is: ";
    	for (int i = 0; i < size; i++)
    	{
    		cout << arr[i] << " ";
    	}
    	cout << endl;
    
    	
    }
    void main()
    {
    	int size;
    	cout << "Enter size of array\n";
    	cin >> size;
    	int *p = new int[size];
    	cout << "Enter the elements of array\n";
    	for (int i = 0; i < size; i++)
    	{
    		cin >> p[i];
    	}
    	reverseArray(p, size);
    	
    
    }
    Last edited by 2kaud; September 14th, 2018 at 10:48 AM. Reason: Added code tags

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Reversing array in C++

    [When posting code, please use code tags so that the code is readable. Go Advanced, select the formatted code and click '#'].

    Cheers!

    What debugging of the code have you done? As this is obviously an assignment, we can't give you the solution but the problem lies with the bounds of the loop that swaps the elements. If you twice swap elements, what happens?

    Also note that reverseArray() has a memory issue in that you are allocating memory with new but not deleting it. The same issue is in main().
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Reversing array in C++

    Just for info, there is a standard c++ function to reverse elements - reverse(). See http://www.cplusplus.com/reference/algorithm/reverse/

    Using this, your code could be

    Code:
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    #include <memory>
    using namespace std;
    
    int main()
    {
    	size_t size;
    
    	cout << "Enter size of array\n";
    	cin >> size;
    
    	auto p = make_unique<int[]>(size);
    	cout << "Enter the elements of array\n";
    
    	for (size_t i = 0; i < size; ++i)
    		cin >> p[i];
    
    	cout << "\nThe original elements are" << endl;
    	copy(p.get(), p.get() + size, ostream_iterator<int>(cout, " "));
    	cout << endl;
    
    	reverse(p.get(), p.get() + size);
    
    	cout << "\nThe elements reversed are" << endl;
    	copy(p.get(), p.get() + size, ostream_iterator<int>(cout, " "));
    	cout << endl;
    }
    Note that main() has a return value of int and not void. To avoid new and hence delete, you can use what's called managed memory so that the allocated memory is automatically deleted when not used. See http://www.cplusplus.com/reference/memory/unique_ptr/

    Also note that in your reverseArray() function, this actually has 3 purposes 1) display the original array, 2) reverse the array 3) display the reversed array. Good practice is for a function to perform one task only. So in this case the function would just reverse the array. The calling function would be responsible for any output display.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Reversing array in C++

    Quote Originally Posted by najum98 View Post
    Hi, I am new on this forum and in this field of programming as well.
    I was facing problems while coding so I searched for forums where I could ask questions related to programming and found this one.

    Please check this piece of code and lemme know what is the fault in it? My purpose is to reverse the array given by the user.

    Code:
    #include <iostream>
    using namespace std;
    void reverseArray(int *arr, int size)
    {
    	int *Copy_arr = new int[size];
    	int temp;
    	for (int i = 0; i < size; i++)
    	{
    		Copy_arr[i] = arr[i];
    	}
    
    	for (int i = 0; i < size; i++)
    	{
    		temp = arr[i];
    		arr[i] = arr[(size - 1) - i];
    		arr[(size - 1) - i] = temp;
    		
    		
    	}
    	
    
    	cout << "Array before function call was: ";
    	for (int i = 0; i < size; i++)
    	{
    		cout << Copy_arr[i] << " ";
    	}
    	cout << endl << "Array after function call is: ";
    	for (int i = 0; i < size; i++)
    	{
    		cout << arr[i] << " ";
    	}
    	cout << endl;
    
    	
    }
    void main()
    {
    	int size;
    	cout << "Enter size of array\n";
    	cin >> size;
    	int *p = new int[size];
    	cout << "Enter the elements of array\n";
    	for (int i = 0; i < size; i++)
    	{
    		cin >> p[i];
    	}
    	reverseArray(p, size);
    	
    
    }
    1. Your code has memory leaks: you new some int arrays at least twice but you never delete them.
    2. You don't need to create additional array within your void reverseArray(int *arr, int size) function (just because you do not use it anymore after returning and you also don't care about the array you are passing into this function), so you could just reverse array elements in place.
    3. You don't need to loop through the whole array to reverse, enough would be to loop up to the size/2
    Victor Nijegorodov

  5. #5
    Join Date
    Feb 2017
    Posts
    677

    Re: Reversing array in C++

    Quote Originally Posted by VictorN View Post
    3. You don't need to loop through the whole array to reverse, enough would be to loop up to the size/2
    It's even necessary to stop at size/2 because continuing up to size will reverse the array a second time and the array will be back where it started.

  6. #6
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Reversing array in C++

    Quote Originally Posted by wolle View Post
    It's even necessary to stop at size/2 because continuing up to size will reverse the array a second time and the array will be back where it started.
    Good point!
    PS: I knew it but just forgot to add ...
    Victor Nijegorodov

  7. #7
    Join Date
    Feb 2017
    Posts
    677

    Re: Reversing array in C++

    Quote Originally Posted by najum98 View Post
    Please check this piece of code and lemme know what is the fault in it?
    The immediate problem is that you reverse the array twice. If you only print the array before and afterwards you will miss this unwanted behavior of your algorithm and it will look like nothing happened. The lesson of course is that when you trace code you should do it at the appropriate level of detail, in this case between each swap.

    There's is nothing wrong with using C++ at a very low level but it's more convenient to raise it just a little bit. In your case I suggest you go for a standard data structure called std::vector. It's a dynamic array implementation and I dare to say that most C++ programmers today would prefer it over allocating C arrays on the heap using new/delete as you do here.

    Finally, array reversing in practice isn't that common because the obvious alternative is simple - just traverse the array in the opposite direction.
    Last edited by wolle; September 15th, 2018 at 06:00 AM.

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Reversing array in C++

    Just correct his assignment......... With my question in post #2, I was trying to get the OP to figure that out for themselves!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Reversing array in C++

    Quote Originally Posted by wolle View Post
    The immediate problem is that you reverse the array twice. If you only print the array before and afterwards you will miss this unwanted behavior of your algorithm and it will look like nothing happened. The lesson of course is that when you trace code you should do it at the appropriate level of detail, in this case between each swap.

    There's is nothing wrong with using C++ at a very low level but it's more convenient to raise it just a little bit. In your case I suggest you go for a standard data structure called std::vector. It's a dynamic array implementation and I dare to say that most C++ programmers today would prefer it over allocating C arrays on the heap using new/delete as you do here.
    But I doubt that the OP has been taught vectors yet. I only included the code in post #3 to let the OP know there was a standard way of doing a reverse.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured