c programming - review

Upload: karim-boupalmier

Post on 14-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 C Programming - Review

    1/57

    Final Review

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.1

  • 7/29/2019 C Programming - Review

    2/57

    When/Where is the final?When:

    April 24, 2013 @ 9:30 - 12:00

    Where:

    A-HS BN-2N (Clara Benson Building) HU-PATE BN-2S (Clara Benson Building) PATI-Z BN-3 (Clara Benson Building)Check Final Exam Schedule for changes

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.2

  • 7/29/2019 C Programming - Review

    3/57

    Post-midterm Topics Arrays Pointers Pointers and Arrays Relationship Strings Structures Dynamic Memory AllocationBook chapters:

    1-13 (no recursion), 16 (only structures), 17, 22Copyright 2008 W. W. Norton & Company.

    All rights reserved.3

  • 7/29/2019 C Programming - Review

    4/57

    What to expect? Small questions that test specific parts

    Theory; loops, conditionals, number systems, characterarithmetic, 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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.4

  • 7/29/2019 C Programming - Review

    5/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.5

    Chapter 8

    Arrays

  • 7/29/2019 C Programming - Review

    6/57

    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 thearrays elements and the number of elements:int a[10];

    To access an array element use subscriptingorindexingthe array (an array of length n are indexed from 0 to n 1).

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.6

  • 7/29/2019 C Programming - Review

    7/57

    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 theycan 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.7

  • 7/29/2019 C Programming - Review

    8/57

    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.8

  • 7/29/2019 C Programming - Review

    9/57

    Multidimensional Arrays To access the element ofm in row i, column j, we

    must write m[i][j].

    C stores arrays in row-major order, with row 0first, then row 1, and so forth.

    How the m array is stored:

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.9

  • 7/29/2019 C Programming - Review

    10/57

    Multidimensional Arrays Nested for loops are ideal for processing

    multidimensional arrays.

    Consider the problem of initializing an array for use as anidentity 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;

    elseident[row][col] = 0.0;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.10

  • 7/29/2019 C Programming - Review

    11/57

    Random Number GeneratorHow 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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.11

  • 7/29/2019 C Programming - Review

    12/57

    FUNCTIONS AND ARRAYS

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.12

  • 7/29/2019 C Programming - Review

    13/57

    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.All rights reserved.

    13

  • 7/29/2019 C Programming - Review

    14/57

    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 zerointo each of its elements:

    void store_zeros(int a[], int n){

    int i;for (i = 0; i < n; i++)

    a[i] = 0;}

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.14

  • 7/29/2019 C Programming - Review

    15/57

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

    The ability to modify the elements of an arrayargument may seem to contradict the fact that C

    passes arguments by value.

    Chapter 12 explains why theres actually nocontradiction (short answer: pass array arguments

    by reference).

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.15

  • 7/29/2019 C Programming - Review

    16/57

    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-dimensionalarray, we must specify the number of columns in a:#define LEN 10

    intsum_two_dimensional_array(inta[][LEN],intn)

    {int i, j, sum = 0;

    for (i = 0; i < n; i++)for (j = 0; j < LEN; j++)

    sum += a[i][j];

    return sum;}

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.16

  • 7/29/2019 C Programming - Review

    17/57

    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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.17

  • 7/29/2019 C Programming - Review

    18/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.18

    Chapter 11

    Pointers

  • 7/29/2019 C Programming - Review

    19/57

    Pointer Variables If there are n bytes in memory, we can think of

    addresses as numbers that range from 0 to n 1:

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.19

    Variables in a program

    occupy bytes of memory

    short int i;

  • 7/29/2019 C Programming - Review

    20/57

    Working with Pointers Declaring pointers (the referenced type):

    int *p; /* points only to integers */

    double *q; /* points only to doubles */

    char *r; /* points only to characters */

    Initializing pointersint i;

    p = &i;

    use the * (indirection) operator to access whatsstored in the objectprintf("%d\n", *p);

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.20

  • 7/29/2019 C Programming - Review

    21/57

    Pointer Variables Addresses can be stored in specialpointer

    variables.

    When we store the address of a variable i in thepointer variable p, we say that p points to i.

    A graphical representation:

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.21

  • 7/29/2019 C Programming - Review

    22/57

    The Indirection Operator int i;

    p = &i;

    i = 1;

    printf("%d\n", i); /* prints 1 */

    printf("%d\n", *p); /* prints 1 */

    *p = 2;

    printf("%d\n", i); /* prints 2 */

    printf("%d\n", *p); /* prints 2 */Copyright 2008 W. W. Norton & Company.

    All rights reserved.22

  • 7/29/2019 C Programming - Review

    23/57

    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;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.23

  • 7/29/2019 C Programming - Review

    24/57

    Pointer Assignment Ifp and q both point to i, we can change i by

    assigning a new value to either*p or*q:

    *p = 1;

    *q = 2;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    24

  • 7/29/2019 C Programming - Review

    25/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    25

    Chapter 12

    Pointers and Arrays

  • 7/29/2019 C Programming - Review

    26/57

    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;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    26

  • 7/29/2019 C Programming - Review

    27/57

    Pointer Arithmetic Ifp points to an element of an array a, the other

    elements ofa can be accessed by performingpointer arithmetic (oraddress 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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    27

  • 7/29/2019 C Programming - Review

    28/57

    Adding an Integer to a PointerAssume the following declarations are in effect:

    int a[10], *p, *q;

    Then:

    p = &a[2];

    q = p + 3;

    p += 6;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    28

  • 7/29/2019 C Programming - Review

    29/57

    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 andmakes both arrays and pointers more versatile.

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    29

  • 7/29/2019 C Programming - Review

    30/57

    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 ofa.

    Also, *(a+i) is equivalent to a[i]. Both represent element i itself.

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    30

  • 7/29/2019 C Programming - Review

    31/57

    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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    31

  • 7/29/2019 C Programming - Review

    32/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    32

    Chapter 13

    Strings

  • 7/29/2019 C Programming - Review

    33/57

    How String Literals Are Stored

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

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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    33

  • 7/29/2019 C Programming - Review

    34/57

    Initializing a String Variable

    A string variable can be initialized at the sametime its declared:

    char date1[8] = "June 14";

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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    34

  • 7/29/2019 C Programming - Review

    35/57

    Character Arrays versus Character Pointers

    Thanks to the close relationship between arraysand pointers, two ways to declare a string:

    char date[] = "June 14";

    char *date = "June 14";

    In the array versiondate is an array name. the characters stored in date can be modified.

    In the pointer versiondate is a pointer variable that can point to other strings.date points to a string literal that shouldnt be modified.

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    35

  • 7/29/2019 C Programming - Review

    36/57

    Reading Strings Character by Character

    read_line consists primarily of a loop that callsgetchar 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 */}

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    36

  • 7/29/2019 C Programming - Review

    37/57

    Accessing the Characters in a String

    A function that counts the number of spaces in astring:

    int count_spaces(const char s[])

    {int count = 0, i;

    for (i = 0; s[i] != '\0'; i++)

    if (s[i] == ' ')

    count++;return count;

    }

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    37

  • 7/29/2019 C Programming - Review

    38/57

    Accessing the Characters in a String

    A version that uses pointer arithmetic instead ofarray subscripting :

    int count_spaces(const char *s)

    {int count = 0;

    for (; *s != '\0'; s++)

    if (*s == ' ')

    count++;return count;

    }

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    38

  • 7/29/2019 C Programming - Review

    39/57

    Arrays of Strings: 2D array

    charplanets[][8]={"Mercury","Venus","Earth",

    "Mars","Jupiter","Saturn",

    "Uranus","Neptune","Pluto"};

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    39

  • 7/29/2019 C Programming - Review

    40/57

    Arrays of Strings: Ragged Array

    char *planets[] = {"Mercury", "Venus, "Earth,

    "Mars", "Jupiter", "Saturn,

    "Uranus", "Neptune", "Pluto"};

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    40

  • 7/29/2019 C Programming - Review

    41/57

    Command-Line Arguments

    Access to command-line arguments in mainint 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:

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    41

  • 7/29/2019 C Programming - Review

    42/57

    Using the C String Library

    Programs that need string operations should contain thefollowing line:

    #include

    The C library provides a rich set of functions forperforming 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);

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    42

  • 7/29/2019 C Programming - Review

    43/57

    Program Examples

    Count the number of spaces in a string (usingarray or pointer)

    Checking Planet Names Writing of String functions:

    Searching for the End of a String Copying a String

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    43

  • 7/29/2019 C Programming - Review

    44/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    44

    Chapter 16

    Structures

  • 7/29/2019 C Programming - Review

    45/57

    Declaring Structure Variables

    A structure is a logical choice for storing acollection of related data items.

    A declaration of two structure variables that storeinformation about parts in a warehouse:struct {

    int number;

    char name[NAME_LEN+1];

    int on_hand;} part1, part2;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    45

  • 7/29/2019 C Programming - Review

    46/57

    Declaring Structure Variables

    The members of a structure arestored in memory in the order in

    which theyre declared.

    Appearance ofpart1 Assumptions:

    part1 is located at address 2000. Integers occupy four bytes.NAME_LEN has the value 25. There are no gaps between the

    members.

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    46

  • 7/29/2019 C Programming - Review

    47/57

    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 ofpart1 after initialization:

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    47

  • 7/29/2019 C Programming - Review

    48/57

    Operations on Structures

    To access a member of a structure, we use . Statements that display the values ofpart1:

    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++;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    48

  • 7/29/2019 C Programming - Review

    49/57

    Declaring a Structure Tag

    A structure tagis a name used to identify aparticular 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;

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    49

  • 7/29/2019 C Programming - Review

    50/57

    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 ofbuild_part:part1 = build_part(528, "Disk drive", 10);

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    50

  • 7/29/2019 C Programming - Review

    51/57

    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 ofprint_part:print_part(part1);

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    51

  • 7/29/2019 C Programming - Review

    52/57

    Program Example

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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    52

  • 7/29/2019 C Programming - Review

    53/57

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    53

    Chapter 17

    Dynamic Memory Management

  • 7/29/2019 C Programming - Review

    54/57

    Memory Allocation Functions

    The header declares three memoryallocation 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* (ageneric pointer).

    If a memory allocation function fails, it returns anull pointer.

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    54

  • 7/29/2019 C Programming - Review

    55/57

    Using malloc to Allocate Memory for a String

    A call ofmalloc that allocates memory for astring ofn characters:

    char* p;

    p = (char *) malloc(n + 1);

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    55

  • 7/29/2019 C Programming - Review

    56/57

    Using malloc to Allocate Memory for an Array

    Suppose a program needs an array ofn integers,where n is computed during program execution.

    int *a;

    a = malloc(n * sizeof(int));

    Or

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

    Copyright 2008 W. W. Norton & Company.

    All rights reserved.

    56

  • 7/29/2019 C Programming - Review

    57/57

    Deallocating memory

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

    The Dangling Pointer Problem

    Copyright 2008 W. W. Norton & Company.

    All i ht d

    57