algorithm help

closed account (i8bjz8AR)
So I have to implement this algorithm void print(int* first, int* limit);, and output the first and last elements in the array with a space character between consecutive elements. This is what I have. I'm a little confused and not sure if i'm doing this right.

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

using namespace std;


void print(int* first, int* limit){
  std::cout << *first << std::endl;
}

int main(){

  int a = {1, 2, 3,4,5};
  print(0,4);

}
Last edited on
Your code does not even compile. A compiler says:
 In function 'int main()':
12:23: error: scalar object 'a' requires one element in initializer
13:12: error: invalid conversion from 'int' to 'int*' [-fpermissive]
6:6: note: initializing argument 2 of 'void print(int*, int*)'

Your compiler should be able to point out the same issues. Make it verbose and then make use of that feedback.

What are the 'first' and 'limit' supposed to represent?

Are you sure that the output has to contain only first and last element, but no intervening elements?
closed account (i8bjz8AR)
The first and last limit are supposed to be 1 and 5. So how would i just output those now?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;


void print(int* first, int* limit){
  while (first != limit){
    std::cout << *first << ' ';
    ++first;
  }
}

int main(){

  int a[] = {1, 2, 3,4,5};
  int* first = a;      // Points to the first object in a
  int* limit = a + 5;
  print(a, a + 5);

}
Topic archived. No new replies allowed.