COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

More arrays

Posted by on August 19th, 2012 · Lab

This week’s tut covers two very common activities in programming: mapping and filtering.

  • Write a method mapDouble which takes in an array of integers and returns a new array containing the double of each entry in the first array. Eg:

  • int[] data = {1, 3, 4, 2, 0, 5, -2};
    int[] doubled = mapDouble(data);

    The returned array doubled should contain {2, 6, 8, 4, 0, 10, -4}.

  • Write a method filterEvens which takes in an array of integers and returns a new array containing only the even values. Eg:

    int[] data = {1, 3, 4, 2, 0, 5, -2};
    int[] evens = filterEvens(data);

    The returned array evens should contain {4, 2, 0, -1}.

    Hint 1: You can check if a number is even by testing if the remainder when dividing by 2 is zero.

    Hint 2: You will probably need to do this in two stages. First count the number of even entries to work out how big the returned array should be. Second, go through the list copying entries. If you have trouble writing this in code, try working through examples by hand on paper.

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

You must log in to post a comment.