Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Final Review

Copyright 2008 W. W. Norton & Company. All rights reserved.

When/Where is the final?


When: April 24, 2013 @ 9:30 - 12:00 Where: A-HS HU-PATE PATI-Z

BN-2N (Clara Benson Building) BN-2S (Clara Benson Building) BN-3 (Clara Benson Building)

Check Final Exam Schedule for changes


2 Copyright 2008 W. W. Norton & Company. All rights reserved.

Post-midterm Topics
Arrays Pointers Pointers and Arrays Relationship Strings Structures Dynamic Memory Allocation

Book chapters: 1-13 (no recursion), 16 (only structures), 17, 22


3 Copyright 2008 W. W. Norton & Company. All rights reserved.

What to expect?
Small questions that test specific parts
Theory; loops, conditionals, number systems, character arithmetic, arrays, strings, pointers, functions, structures, memory management, etc.

Tracing output
Can include any of the concepts

Write a function/program following specifications


Input/Output from keyboard/file Array & String manipulation Pointers Labs & project related
4 Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 8

Arrays

Copyright 2008 W. W. Norton & Company. All rights reserved.

One-Dimensional Arrays
An array is a data structure containing a number of data values, all of which have the same type.
To declare an array, we must specify the type of the arrays elements and the number of elements: int a[10];

To access an array element use subscripting or indexing the array (an array of length n are indexed from 0 to n 1).

Copyright 2008 W. W. Norton & Company. All rights reserved.

One-Dimensional Arrays
Array initialization
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int a[10] = {1, 2, 3, 4, 5, 6}; int a[10] = {0};

Expressions of the form a[i] are lvalues, so they can be used in the same way as ordinary variables:
a[0] = 1; printf("%d\n", a[5]); ++a[i];

Copyright 2008 W. W. Norton & Company. All rights reserved.

Multidimensional Arrays
An array may have any number of dimensions. The following declaration creates a two-dimensional array (a matrix, in mathematical terminology):
int m[5][9];

m has 5 rows and 9 columns. Both rows and columns are indexed from 0:

Copyright 2008 W. W. Norton & Company. All rights reserved.

Multidimensional Arrays
To access the element of m in row i, column j, we must write m[i][j]. C stores arrays in row-major order, with row 0 first, then row 1, and so forth. How the m array is stored:

Copyright 2008 W. W. Norton & Company. All rights reserved.

Multidimensional Arrays
Nested for loops are ideal for processing multidimensional arrays. Consider the problem of initializing an array for use as an identity matrix. A pair of nested for loops is perfect:
#define N 10 double ident[N][N]; int row, col; for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (row == col) ident[row][col] = 1.0; else ident[row][col] = 0.0;
10 Copyright 2008 W. W. Norton & Company. All rights reserved.

Random Number Generator


How to generate random numbers in a determined range using rand()?
use the % of the returned value by the range span add the initial value of the range

Examples:
random = rand() % 100; // range 0 to 99 random = rand() % 100 + 1; // range 1 to 100 random = rand() % 30 + 1985; // range 1985-2014

11

Copyright 2008 W. W. Norton & Company. All rights reserved.

FUNCTIONS AND ARRAYS

12

Copyright 2008 W. W. Norton & Company. All rights reserved.

Functions and Arrays


Function prototype with an array as parameter:
int sum_array(int a[], int n){}

Function call with array argument:


#define LEN 100 int main(void) { int b[LEN], total; total = sum_array(b, LEN); } Copyright 2008 W. W. Norton & Company. 13
All rights reserved.

Array Arguments
A function is allowed to change the elements of an array parameter, and the change is reflected in the corresponding argument. A function that modifies an array by storing zero into each of its elements:
void store_zeros(int a[], int n) { int i; for (i = 0; i < n; i++) a[i] = 0;
14 Copyright 2008 W. W. Norton & Company. All rights reserved.

Array Arguments
A call of store_zeros:
store_zeros(b, 100);

The ability to modify the elements of an array argument may seem to contradict the fact that C passes arguments by value. Chapter 12 explains why theres actually no contradiction (short answer: pass array arguments by reference).

15

Copyright 2008 W. W. Norton & Company. All rights reserved.

Array Arguments
If a parameter is a multidimensional array, only the length of the first dimension may be omitted. If we revise sum_array so that a is a two-dimensional array, we must specify the number of columns in a:
#define LEN 10 int sum_two_dimensional_array(int a[][LEN], int n) { int i, j, sum = 0; for (i = 0; i < n; i++) for (j = 0; j < LEN; j++) sum += a[i][j]; } return sum;
16 Copyright 2008 W. W. Norton & Company. All rights reserved.

Example Programs
Programs
Reversing a Series of Numbers Checking a Number for Repeated Digits Computing Interest Dealing a Hand of Cards

Functions with Array arguments


Print Elements of an Array Reversing the Elements of an Array Bubble Sort

17

Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 11

Pointers

18

Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Variables
If there are n bytes in memory, we can think of addresses as numbers that range from 0 to n 1:
Variables in a program occupy bytes of memory short int i;

19

Copyright 2008 W. W. Norton & Company. All rights reserved.

Working with Pointers


Declaring pointers (the referenced type):
int *p; double *q; char *r; /* points only to integers */ /* points only to doubles */ /* points only to characters */

Initializing pointers
int i; p = &i;

use the * (indirection) operator to access whats stored in the object


printf("%d\n", *p);
20 Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Variables
Addresses can be stored in special pointer variables. When we store the address of a variable i in the pointer variable p, we say that p points to i. A graphical representation:

21

Copyright 2008 W. W. Norton & Company. All rights reserved.

The Indirection Operator


int i;
p = &i; i = 1;

printf("%d\n", i); printf("%d\n", *p); *p = 2;

/* prints 1 */ /* prints 1 */

printf("%d\n", i); printf("%d\n", *p);


22

/* prints 2 */ /* prints 2 */
Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Assignment
Assume that the following declaration is in effect:
int i, j, *p, *q;

Example of pointer assignment:


p = &i;

Another example of pointer assignment:


q = p;

23

Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Assignment
If p and q both point to i, we can change i by assigning a new value to either *p or *q:
*p = 1;

*q = 2;

24

Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 12

Pointers and Arrays

25

Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Arithmetic
Pointers can point to array elements:
int a[10], *p; p = &a[0];

we can store the value 5 in a[0] by writing


*p = 5;

26

Copyright 2008 W. W. Norton & Company. All rights reserved.

Pointer Arithmetic
If p points to an element of an array a, the other elements of a can be accessed by performing pointer arithmetic (or address arithmetic) on p. C supports three forms of pointer arithmetic:
Adding an integer to a pointer Subtracting an integer from a pointer Subtracting one pointer from another

27

Copyright 2008 W. W. Norton & Company. All rights reserved.

Adding an Integer to a Pointer


Assume the following declarations are in effect:
int a[10], *p, *q;

Then:
p = &a[2];

q = p + 3;

p += 6;
28 Copyright 2008 W. W. Norton & Company. All rights reserved.

Using an Array Name as a Pointer


Pointer arithmetic is one way in which arrays and pointers are related. Another key relationship: The name of an array can be used as a pointer to the first element in the array. This relationship simplifies pointer arithmetic and makes both arrays and pointers more versatile.

29

Copyright 2008 W. W. Norton & Company. All rights reserved.

Using an Array Name as a Pointer


Suppose that a is declared as follows:
int a[10];

Examples of using a as a pointer:


*a = 7; /* stores 7 in a[0] */ *(a+1) = 12; /* stores 12 in a[1] */

In general, a + i is the same as &a[i].


Both represent a pointer to element i of a.

Also, *(a+i) is equivalent to a[i].


Both represent element i itself.
30 Copyright 2008 W. W. Norton & Company. All rights reserved.

Example Programs
Swap the values of two integers using pointers Find largest and smallest elements in an array Sum the elements of an array using pointers Process the rows of a multidimensional array using pointers

31

Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 13

Strings

32

Copyright 2008 W. W. Norton & Company. All rights reserved.

How String Literals Are Stored


The string literal "abc" is stored as an array of four characters:

The string "" is stored as a single null character:

33

Copyright 2008 W. W. Norton & Company. All rights reserved.

Initializing a String Variable


A string variable can be initialized at the same time its declared:
char date1[8] = "June 14";

The compiler will automatically add a null character so that date1 can be used as a string:

34

Copyright 2008 W. W. Norton & Company. All rights reserved.

Character Arrays versus Character Pointers


Thanks to the close relationship between arrays and pointers, two ways to declare a string:
char date[] = "June 14"; char *date = "June 14"; In the array version
date is an array name. the characters stored in date can be modified.

In the pointer version


date is a pointer variable that can point to other strings. date points to a string literal that shouldnt be modified.
35 Copyright 2008 W. W. Norton & Company. All rights reserved.

Reading Strings Character by Character


read_line consists primarily of a loop that calls getchar to read a character and then stores the character in str, provided that theres room left:
int read_line(char str[], int n) { int ch, i = 0; while ((ch = getchar()) != '\n') if (i < n) str[i++] = ch; str[i] = '\0'; /* terminates string */ return i; /* number of characters stored */

36

Copyright 2008 W. W. Norton & Company. All rights reserved.

Accessing the Characters in a String


A function that counts the number of spaces in a string:
int count_spaces(const char s[]) { int count = 0, i; for (i = 0; s[i] != '\0'; i++) if (s[i] == ' ') count++; return count; }
37 Copyright 2008 W. W. Norton & Company. All rights reserved.

Accessing the Characters in a String


A version that uses pointer arithmetic instead of array subscripting :
int count_spaces(const char *s) { int count = 0; for (; *s != '\0'; s++) if (*s == ' ') count++; return count; }
38 Copyright 2008 W. W. Norton & Company. All rights reserved.

Arrays of Strings: 2D array


char planets[][8] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};

39

Copyright 2008 W. W. Norton & Company. All rights reserved.

Arrays of Strings: Ragged Array


char *planets[] = {"Mercury", "Venus, "Earth, "Mars", "Jupiter", "Saturn, "Uranus", "Neptune", "Pluto"};

40

Copyright 2008 W. W. Norton & Company. All rights reserved.

Command-Line Arguments
Access to command-line arguments in main
int main(int argc, char *argv[]){}

If the user enters the command line


> ls -l remind.c

then argc will be 3, and argv will be:

41

Copyright 2008 W. W. Norton & Company. All rights reserved.

Using the C String Library


Programs that need string operations should contain the following line:
#include <string.h>

The C library provides a rich set of functions for performing operations on strings.
char *strcpy(char *s1, const char *s2); size_t strlen(const char *s); char *strcat(char *s1, const char *s2); int strcmp(const char *s1, const char *s2);

42

Copyright 2008 W. W. Norton & Company. All rights reserved.

Program Examples
Count the number of spaces in a string (using array or pointer) Checking Planet Names Writing of String functions:
Searching for the End of a String Copying a String

43

Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 16

Structures

44

Copyright 2008 W. W. Norton & Company. All rights reserved.

Declaring Structure Variables


A structure is a logical choice for storing a collection of related data items. A declaration of two structure variables that store information about parts in a warehouse:
struct { int number; char name[NAME_LEN+1]; int on_hand; } part1, part2;

45

Copyright 2008 W. W. Norton & Company. All rights reserved.

Declaring Structure Variables


The members of a structure are stored in memory in the order in which theyre declared. Appearance of part1 Assumptions:
part1 is located at address 2000. Integers occupy four bytes. NAME_LEN has the value 25. There are no gaps between the members.
46 Copyright 2008 W. W. Norton & Company. All rights reserved.

Initializing Structure Variables


A structure declaration may include an initializer:
struct { int number; char name[NAME_LEN+1]; int on_hand; } part1 = {528, "Disk drive", 10}, part2 = {914, "Printer cable", 5};

Appearance of part1 after initialization:

47

Copyright 2008 W. W. Norton & Company. All rights reserved.

Operations on Structures
To access a member of a structure, we use . Statements that display the values of part1:
printf("Part number: %d\n", part1.number); printf("Part name: %s\n", part1.name); printf("Quantity on hand: %d\n", part1.on_hand);

They can appear on the left side of an assignment:


part1.number = 258; part1.on_hand++;

48

Copyright 2008 W. W. Norton & Company. All rights reserved.

Declaring a Structure Tag


A structure tag is a name used to identify a particular kind of structure. The declaration of a structure tag named part:
struct part { int number; char name[NAME_LEN+1]; int on_hand; };

The part tag can be used to declare variables:


struct part part1, part2;
49 Copyright 2008 W. W. Norton & Company. All rights reserved.

Structures as Arguments and Return Values


A function that returns a part structure:
struct part build_part(int number, const char *name, int on_hand) { struct part p; p.number = number; strcpy(p.name, name); p.on_hand = on_hand; return p;

A call of build_part:
part1 = build_part(528, "Disk drive", 10);
50 Copyright 2008 W. W. Norton & Company. All rights reserved.

Structures as Arguments and Return Values


A function with a structure argument:
void print_part(struct part p) { printf("Part number: %d\n", p.number); printf("Part name: %s\n", p.name); printf("Quantity on hand: %d\n", p.on_hand); }

A call of print_part:
print_part(part1);

51

Copyright 2008 W. W. Norton & Company. All rights reserved.

Program Example
Maintaining a Parts Database (Inventory)
Arrays of structures Nested structures Structures that include array members Functions that have structures as parameters Functions that return structures

52

Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 17

Dynamic Memory Management

53

Copyright 2008 W. W. Norton & Company. All rights reserved.

Memory Allocation Functions


The <stdlib.h> header declares three memory allocation functions:
mallocAllocates a block of memory but doesnt initialize it. callocAllocates a block of memory and clears it. reallocResizes a previously allocated block of memory.

These functions return a value of type void * (a generic pointer). If a memory allocation function fails, it returns a null pointer.
54 Copyright 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Memory for a String


A call of malloc that allocates memory for a string of n characters: char * p;
p = (char *) malloc(n + 1);

55

Copyright 2008 W. W. Norton & Company. All rights reserved.

Using malloc to Allocate Memory for an Array


Suppose a program needs an array of n integers, where n is computed during program execution.
int *a; a = malloc(n * sizeof(int));

Or
a = calloc(n, sizeof(int));

56

Copyright 2008 W. W. Norton & Company. All rights reserved.

Deallocating memory
Memory leak and garbage collector Deallocating memory using free: void free(void *ptr); The Dangling Pointer Problem

57

Copyright 2008 W. W. Norton & Company. All rights reserved.

You might also like