CS174: Module 7: C++ Addresses And Pointers: Exercise 2 (1.5 Points)

C++ frontend developed by, Professor Tralie, adopted from code by Todd Fleming. Canvas Autograder Developed by Professor Tralie and Professor Mongan.


Exercise Goals

The goals of this exercise are:
  1. Work with pointers in C++
  2. Return values by reference from methods in C++
The "filter" method defined below takes in an array and creates a new, shorter version of it with only the even numbers from the original array. Modify the method so that it takes a pointer to the size of an array as a reference variable. It should then write the correct size to the value at this pointer's address before the method returns. NOTE: size_t is simply a positive int type, which is used to indicate the size of an array.

Student Code

#include <stdio.h> int* filter(int* x, size_t N) { // Step 1: Count how many elements are even size_t NOut = 0; for (int i = 0; i < N; i++) { if (x[i] % 2 == 0) { NOut++; } } // Step 2: Allocate new array and fill in even elements int* xout = new int[NOut]; int idx = 0; for (int i = 0; i < N; i++) { if (x[i] % 2 == 0) { xout[idx] = x[i]; idx++; } } return xout; }

Main Area

void printArray(int* arr, int N) { for (int i = 0; i < N; i++) { printf("%i ", arr[i]); } } int main() { printf("\n|"); int x1[] = {1, 9, 4, 5, 2, 3, 1, 8, 2, 13}; size_t NOut = 0; int* xout = filter(x1, 10, &NOut); printArray(xout, NOut); delete[] xout; int x2[] = {1, 2, 3, 4, 5, 6, 7, 8}; xout = filter(x2, 8, &NOut); printf("."); printArray(xout, NOut); }

Compiler Feedback

Program Output

Click compile to compile your code. If it succeeds with no syntax errors, then click run to run your code. If it passes the tests, it will automatically submit to Canvas and send you an e-mail. You must be connected to the VPN for submission to be successful! You will receive a copy of your code via e-mail, so you'll know that it was submitted if you receive that e-mail!
Please Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is ctralie (non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit)

Netid