Week 01 Tutorial
Getting Started and Recap!
1. Class introduction (for everyone, starting with the tutor):

• introduce yourself to the other people in the tute class
• discuss what you learned from COMP1511
• discuss what parts you're still unsure of
• choose lab partners (who you'll work with until week 5)

[show answer]

2. Consider the following program (adapted from Sedgewick):

#include <stdlib.h>#include <stdio.h>#include <assert.h> int main(int argc, char *argv[]){	int i, j, *a;	int N = 0; 	// initialisation	assert(argc > 1);	sscanf(argv[1], "%d", &N);	assert(N > 0);	a = malloc(N*sizeof(int));	assert(a != NULL);	for (i = 2; i < N; i++) a[i] = 1; 	// computation	for (i = 2; i < N; i++) {		if (a[i]) {			for (j = i; i*j < N; j++) a[i*j] = 0;		}	} 	// results	for (i = 2; i < N; i++) {		if (a[i]) printf("%d\n",i);	}	exit(EXIT_SUCCESS);}

Try to answer each of the following questions about this program:

1. there are no braces around the bodies of some for loops; does this matter?
2. what is the line of code sscanf(argv[1],"%d",&N); doing?
3. suggest an alternative for the sscanf(...) statement?
4. for each of the asserts ...
• describe what error is being checked for and why
• suggest a better error message than what you get from assert
5. what are the values of a[0] and a[1] during execution?
6. why don't the values of a[0] and a[1] matter?
7. what is the purpose of this program?

[show answer]

3. A C program has several means of interacting with its run-time environment. Describe what each of the following is and what it is used for: argc, argv, stdin, stdout, stderr, exit().

[show answer]

4. Consider a program called myprog which is invoked as:

\$ ./myprog  hello there,  'John Shepherd'  >  myFile

1. What are the values of argc and argv?

2. Where would the statement printf("%s",argv[1]) place its output?

3. Where would the statement ch = getchar(); get its input?

[show answer]

5. Which of the following statements are equivalent? Which are incorrect? Assume that x is an int variable.

1. scanf("%d", x);

2. scanf("%d", &x);

3. printf("%d", x);

4. fscanf(stdin, "%d", &x);

5. fscanf(stderr, "%d", &x);

6. fprintf(stdout, "%d", x);

7. fprintf(stderr, "%d", x);

[show answer]

6. Define a swap() function that exchanges two elements in an array.

For an array a[] and two indexes i and j, we could exchange the i'th and j'th elements by the call:

swap(a, i, j)


[show answer]

7. Consider the following simple linked-list representation and a function that sums the values in the list:

typedef struct _Node {
int value;
struct _Node *next;
} Node;

typedef Node *List;  // pointer to first Node

Write a function to sum the values in the list. Implement it first using while and then using for. Finally, implement it using recursion.

[show answer]

8. Important: Make sure you can properly understand and effectively use the following topics (covered in COMP1511). In case you have any questions, please discuss them with your tutor.