vectors and arithmetic progression

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vix290788
    New Member
    • Oct 2008
    • 4

    vectors and arithmetic progression

    Hi, I have been attempting a question for hours now and don't seem to be getting anywhere. I have to return a vector of <long> containing the arithmetic progression up to N terms, with a and d long arguments, so
    a_n = a+n*d

    I have created the function vector<long>ari th_prog(long, long, int) like follows:

    vector<long> arith_prog(long a, long d, int N)
    {
    vector<long>ari th_vec;
    long x = 0;
    for( int i = 0; i < N; i++)
    {
    x = a + i*d;
    arith_vec.push_ back;
    x = arith_vec[i];
    }
    return arith_vec;
    }

    Can anyone tell me where I am going wrong?
    Quick reply would be great!
    Thanks
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Code:
    arith_vec.push_back;
    x = arith_vec[i];
    You have to pass an argument to push_back. Maybe you meant to push x into the vector?
    Code:
    arith_vec.push_back(x);
    By the way, it would be helpful if you used code tags around your code. Put [CODE] before the code and [/CODE] after it, so it shows up in a code box and the indentation isn't wrecked. Thanks.
    Hope this helps.

    Comment

    • vix290788
      New Member
      • Oct 2008
      • 4

      #3
      Thanks, but no unfortunately that still doesn't make it work. I realised this mistake just after I had posted my original message. So can anyone help me as to whats wrong. I get loads of error messages when I try to compile it, which I have no idea what they mean.
      Code:
      vector<long> arith_prog(long a, long d, int N)
      	{
      	vector<long>arith_vec;
      	long x = 0;
      	for( int i = 0; i < N; i++)
      		{
      		x = a + i*d;
      		arith_vec.push_back(x);
      		x = arith_vec[i];
      		}
      	return arith_vec;
      	}

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Please post the error messages here so it's easier for people to help you.
        Thanks.
        Edit:
        I have put your function in a program that calls it, and it works fine. The errors must be from something else. Maybe you forgot to include vector.
        This line of code
        Code:
        x = arith_vec[i];
        is unnecessary. x is already equal to arith_vec[i], and at that point in your loop it doesn't matter what x equals anyway.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Did you #include <vector> ??

          Comment

          • vmpstr
            New Member
            • Nov 2008
            • 63

            #6
            and are you using namespace std?

            Comment

            Working...