Introduction
Announcements

Schedule
Labs
Assignments
TA office hours

Tests, exam

Topic videos
Some course notes
Extra problems
Lecture recordings

Discussion board

Grades so far

3. [6 marks]
a) Write a C function (not an entire program) which takes an array of integers and the size of that array, and reverses them. E.g. if the array is initially [0,1,2,3], the array will end up being [3,2,1,0].

b) Write a C main() function which reads up to 20 integers into an array from the standard input with scanf(), calls the above function to reverse the array, and then outputs them all (one per line). You can assume that the input consists entirely of well-formed integers. If there are more than 20 integers in the input, your program just reads and processes the first 20.

Solutions:

void reverse(int *a, int size)
{
    int i, t;
    for (i = 0; i < size / 2; i++) {
        t = a[size - 1 - i];
        a[size - 1 - i] = a[i];
        a[i] = t;
    }
}

int main()
{
    int a[20];
    int size, i;
    extern void reverse(int *a, int size);

    for (size = 0; size < 20 && scanf("%d", &a[size]) == 1; size++)
	;
    reverse(a, size);
    for (i = 0; i < size; i++)
	printf("%d\n", a[i]);
    return(0);
}


[sample midterm from Fall 2011]