Click here to Skip to main content
15,889,874 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Define a function that takes m and n integers as input and print odd numbers between m and n

C++
vector < int > oddNumbers(int m,int n)
{


}


What I have tried:

C++
vector <int> oddNumbers(int l,int r)
    
        {
        oddNumbers.push_back();
    cout<<"Enter second number";
            oddNumbers.push_back();

        for(unsigned int i=l+1;i<r;i++)
        {
            if (i%2!=0)
                oddNumbers.push_back()
                cin>>i;
        }
Posted
Updated 21-Sep-17 15:31pm
v2
Comments
Patrice T 20-Sep-17 23:37pm    
Where are you stuck?
Advice: reread your requirement.
Member 13420756 21-Sep-17 0:05am    
at the pushback statements
Patrice T 21-Sep-17 0:07am    
why you want to use pushback statements in first place ?
Member 13420756 21-Sep-17 0:24am    
how can we do it or else can u please tell me.. i m a beginner
Member 13420756 21-Sep-17 0:25am    
the vector function was predefined in the question. i have to use it compulsarily

If you have to fill the proposed function, namely
Quote:
vector < int > oddNumbers(int m,int n)
{
}


Then
C++
vector < int > oddNumbers(int m,int n)
{
  vector<int> v;
  if ( m % 2 == 0) ++m;

  while ( m <= n )
  {
    v.push_back(m);
    m+=2;
  }
  return  v;
}
 
Share this answer
 
You dont need such vector as return. The code should really be easy:
C++
void printOddNumbers(int l, int r)
{
 for( int i = l; i < r; i++)
 {
   if( i % 2 == 0 ) 
   {
     cout << i;
   }
 }
}


The code only work if r > l. Think what error handling or "healing" to do, if l < r.
 
Share this answer
 
Comments
CPallini 21-Sep-17 5:19am    
It's rather odd, but that doesn't work even if l<r.
Advice: use proper indentation to see code structure, it helps reading and can highlight some problems. See the cin.
C++
vector <int> oddNumbers(int l,int r)

{
	oddNumbers.push_back();
	cout<<"Enter second number";
	oddNumbers.push_back();

	for(unsigned int i=l+1;i<r;i++)
	{
		if (i%2!=0)
			oddNumbers.push_back()
		cin>>i;
	}
}


Problems in your code:
C++
vector <int> oddNumbers(int l,int r)

{
	// where did you defined/declared oddNumbers ?
	oddNumbers.push_back(); // you have to tell what value to want to push back
	cout<<"Enter second number"; // which second number ?
	oddNumbers.push_back(); // you have to tell what value to want to push back

	for(unsigned int i=l+1;i<r;i++)
	{
		if (i%2!=0)
			oddNumbers.push_back() // a ; is missing here
		// you want to output i
		// because of not using {}, the cin is not in test
		cin>>i;
	}
	// you code do not return anything.
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900