CS1010E Programming Methodology
This tutorial explores key concepts in CS1010E Programming, focusing on variable declarations, especially pointer variables, and their implications in code. We discuss how to reference values versus addresses, specifically in the context of arrays. The tutorial includes detailed discussions on the implementation of a swap function, the printing of arrays, and iterating through structures with example code snippets. By the end, solidify your understanding of pointer manipulation and pattern printing in arrays through practical examples and exercises.
CS1010E Programming Methodology
E N D
Presentation Transcript
Tutorial 8 Question 1 CS1010EProgramming Methodology
Discussion • *variable (in declaration) means the variable is a pointer variable • *variable (in statement) refers to the value of the variable, NOT the address • NOTE: There is a missing information where the initial value of variable “i” is assigned as 0.
Discussion (cont’d) while (i < 5) { if (list[i] != i) { j = list[i]; swap(&list[i], &list[j]); printArray(list, 5); } else i++; }
Discussion (cont’d) void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; return; }
Discussion (cont’d) voidprintArray(int list[], int size) { for (i = 0; i < size; i++) { printf(“%d“, *list); list++; } printf(“\n”); return; }
Discussion (cont’d) Answer (so far) : 1 2 4 3 0 2 1 4 3 0 4 1 2 3 0 0 1 2 3 4 Pattern printing…
Discussion (cont’d) voidprintPattern(int list[], int size) { inti; for (i = 1; i <= size; i++) printArray(list+(size-i), i); return; }
Discussion (cont’d) printArray(list+(size-i), i); list+(size-i) refers to an address (array is a pointer where the address of each member is adjacent to the member next to it)
Discussion (cont’d) list[5] = {0, 1, 2, 3, 4}
Discussion (cont’d) Answer (final) : 1 2 4 3 0 2 1 4 3 0 4 1 2 3 0 0 1 2 3 4 Pattern printing… 4 3 4 2 3 4 1 2 3 4 0 1 2 3 4