CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2011
    Location
    Richmond, Va
    Posts
    32

    Remove odd function

    Code:
    #include <iostream>
    #include <conio.h>
    
    using namespace std;
    
    int sum(int arr[], int size);
    int * remove_odd(int arr[]);
    
    void main()
    {
    	int num[10];
    	int *order = new int[10];
    
    	for(int i = 0; i <= 10; i++)
    	{
    		num[i] = i;
    	}
    
    	order = remove_odd(num);
    	for(int i = 0; i <= 10; ++i)
    	{
    		cout << order[i]<<"\r\n";
    	}
    
    	getch();
    }
    
    int sum(int arr[], int size)
    {
    	int * ptr = arr;
    
    	int tot = 0;
    
    	while(*ptr <= size && *ptr >= 0)
    	{
    		tot += *ptr;
    		++ptr;
    	}
    
    	return tot;
    };
    
    int * remove_odd(int arr[])
    {
    	int * ptr = arr;
    
    	while(*ptr <= 10 && *ptr >= 0)
    	{
    		if((*ptr % 2) != 0)
    		{
    			*ptr = 0;
    			++ptr;
    		}
    	}
    
    	return arr;
    };
    Check this code in the "remove odd" function. I don't understand what in the while loop is causing it to not work.

  2. #2
    Join Date
    Mar 2008
    Location
    Turin / Italy
    Posts
    178

    Re: Remove odd function

    what's wrong with remove_if?
    http://www.cplusplus.com/reference/algorithm/remove_if/

    Can't you just use that?

  3. #3
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Remove odd function

    Quote Originally Posted by Amaz1ng View Post
    Check this code in the "remove odd" function. I don't understand what in the while loop is causing it to not work.
    I don’t understand why would it work.
    Could you please explain HOW it is not working?
    Also, please define “remove odd”. What should be done?
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

  4. #4
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Remove odd function

    Check your for loops. You're stepping over the end of the array.

    You should be using for loops, not while loops with your arrays. There's no guarantee that your while condition will suddenly become false just because you reach the end of the array.

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