unit4 slides

47
Arrays: Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size. Structure: Purpose and usage of structures, declaring structures, assigning of structures. Pointers to Objects: Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists. UNIT IV

Post on 18-Oct-2014

1.822 views

Category:

Technology


0 download

DESCRIPTION

I am working as a Assistant Professor in ITS, Ghaziabad. These 'C' language slides are very useful for students of any university.

TRANSCRIPT

  • Arrays: Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size.

    Structure: Purpose and usage of structures, declaring structures, assigning of structures.

    Pointers to Objects: Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists.

    UNIT IV

    *

  • Introduction

    Arrays Structures of related data itemsStatic entity same size throughout program

    *

  • *

    6.2Arrays

    ArrayGroup of consecutive memory locations Same name and typeTo refer to an element, specifyArray namePosition numberFormat:

    arrayname[ position number ]

    First element at position 0n element array named c:c[ 0 ], c[ 1 ]...c[ n 1 ]

    c[6]

    -45

    6

    0

    72

    1543

    -89

    0

    62

    -3

    1

    6453

    78

    c[0]

    c[1]

    c[2]

    c[3]

    c[11]

    c[10]

    c[9]

    c[8]

    c[7]

    c[5]

    c[4]

    Name of array (Note that all elements of this array have the same name, c)

    Position number of the element within array c

    *

  • *

    6.2Arrays

    Array elements are like normal variables

    c[ 0 ] = 3;

    printf( "%d", c[ 0 ] );

    Perform operations in subscript. If x equals 3

    c[ 5 - 2 ] == c[ 3 ] == c[ x ]

    *

  • *

    6.3Declaring Arrays

    When declaring arrays, specifyNameType of arrayNumber of elements

    arrayType arrayName[ numberOfElements ];

    Examples:

    int c[ 10 ];

    float myArray[ 3284 ];

    Declaring multiple arrays of same typeFormat similar to regular variablesExample:

    int b[ 100 ], x[ 27 ];

    *

  • *

    6.4Examples Using Arrays

    Initializers

    int n[ 5 ] = { 1, 2, 3, 4, 5 };

    If not enough initializers, rightmost elements become 0

    int n[ 5 ] = { 0 }

    All elements 0If too many a syntax error is produced syntax errorC arrays have no bounds checkingIf size omitted, initializers determine it

    int n[ ] = { 1, 2, 3, 4, 5 };

    5 initializers, therefore 5 element array

    *

  • *

    2 /*Histogram printing program */

    3#include

    4#define SIZE 10

    5

    6int main()

    7{

    8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

    9 int i, j;

    10

    11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );

    12

    13 for ( i = 0; i

  • Element Value Histogram

    0 19 *******************

    1 3 ***

    2 15 ***************

    3 7 *******

    4 11 ***********

    5 9 *********

    6 13 *************

    7 5 *****

    8 17 *****************

    9 1 *

    *

  • *

    6.4Examples Using Arrays

    Character arraysString first is really a static array of charactersCharacter arrays can be initialized using string literals

    char string1[] = "first";

    Null character '\0' terminates stringsstring1 actually has 6 elementsIt is equivalent to

    char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };

    Can access individual characters

    string1[ 3 ] is character s

    Array name is address of array, so & not needed for scanf

    scanf( "%s", string2 );

    Reads characters until whitespace encounteredCan write beyond end of array, be careful

    *

  • *

    Passing Arrays to Functions

    Passing arraysTo pass an array argument to a function, specify the name of the array without any brackets

    int myArray[ 24 ];

    myFunction( myArray, 24 );

    Array size usually passed to function Arrays passed call-by-reference Name of array is address of first elementFunction knows where the array is storedModifies original memory locationsPassing array elements Passed by call-by-valuePass subscripted name (i.e., myArray[ 3 ]) to function

    *

  • *

    1/*

    2 Passing arrays and individual array elements to functions */

    3#include

    4#define SIZE 5

    5

    6void modifyArray( int [], int ); /* appears strange */

    7void modifyElement( int );

    8

    9int main()

    10{

    11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;

    12

    13 printf( "Effects of passing entire array call "

    14 "by reference:\n\nThe values of the "

    15 "original array are:\n" );

    16

    17 for ( i = 0; i

  • *

    Effects of passing entire array call by reference:

    The values of the original array are:

    0 1 2 3 4

    The values of the modified array are:

    0 2 4 6 8

    Effects of passing array element call by value:

    The value of a[3] is 6

    Value in modifyElement is 12

    The value of a[3] is 6

    33

    34void modifyArray( int b[], int size )

    35{

    36 int j;

    37

    38 for ( j = 0; j

  • /* Program to count the no of positive and negative numbers*/ #include< stdio.h > void main( ) { int a[50],n,count_neg=0,count_pos=0,I; printf(Enter the size of the array\n); scanf(%d,&n); printf(Enter the elements of the array\n); for(I=0;I < n;I++) scanf(%d,&a[I]); for(I=0;I < n;I++) { if(a[I] < 0) count_neg++; else count_pos++; } printf(There are %d negative numbers in the array\n,count_neg); printf(There are %d positive numbers in the array\n,count_pos); }

    *

  • *

    Multiple-Dimensional Arrays

    Multiple Dimensional arrays Tables with rows and columns (m by n array)Like matrices: specify row, then column

    a[ 0 ][ 0 ]

    a[ 1 ][ 0 ]

    a[ 2 ][ 0 ]

    a[ 0 ][ 1 ]

    a[ 1 ][ 1 ]

    a[ 2 ][ 1 ]

    a[ 0 ][ 2 ]

    a[ 1 ][ 2 ]

    a[ 2 ][ 2 ]

    a[ 0 ][ 3 ]

    a[ 1 ][ 3 ]

    a[ 2 ][ 3 ]

    Row 0

    Row 1

    Row 2

    Column 0

    Column 1

    Column 2

    Column 3

    Row subscript

    Array name

    Column subscript

    *

  • Initialization of multidimensional arrays:

    Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces

    Example:

    Initializes the elements of first row to zero and second row to 1.

    int table[2][3]={{0,0,0},{1,1,1}}

    By surrounding the elements of each row by braces.

    C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is:

    date_type array_name[s1][s2][s3]..[sn];

    Where s is the size of the ith dimension. Some examples are:

    int survey[3][5][12];
    float table[5][4][5][3];

    Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.

    *

  • example program to add two matrices & store the results in the 3rd matrix

    #include

    #include

    void main()

    {

    int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;

    clrscr();

    printf("enter the order of first matrix:");

    scanf("%d %d",&m,&n);

    printf("enter the order of the second matrix\n");

    scanf("%d %d",&p,&q);

    if(m==p && n==q)

    {

    printf("matrix can be added\n");

    printf("enter the elements of the matrix a");

    for(i=0;i < m;i++)

    {

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

    scanf("%d",&a[i][j]);

    }

    printf("enter the elements of the matrix b");

    for(i=0;i < p;i++)

    {

    for(j=0;j < q;j++)

    scanf("%d",&b[i][j]);

    }

    *

  • printf("the sum of the matrix a and b is");

    for(i=0;i < m;i++)

    {

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

    c[i][j]=a[i][j]+b[i][j];

    }

    for(i=0;i < m;i++)

    {

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

    printf("%d\t",c[i][j]);

    printf("\n");

    }

    }

    }

    *

  • Structure

    Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types.

    General format:


    struct tag_name
    {
    data type member1;
    data type member2;


    }

    Example:
    struct lib_books
    {
    char title[20];
    char author[15];
    int pages;
    float price;
    };

    *

  • the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure.

    We can declare structure variables using the tag name any where in the program. For example the statement,
    struct lib_books book1, book2, book3;

    declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this
    struct lib_books
    {
    char title[20];
    char author[15];
    int pages;
    float price;
    };

    struct lib_books, book1, book2, book3;

    Structure Contd

    *

  • We can also combine both template declaration and variables declaration in one statement, the declaration
    struct lib_books
    {
    char title[20];
    char author[15];
    int pages;
    float price;
    } book1,book2,book3;

    is valid.

    book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration.

    A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure.

    Structure Contd

    *

  • Giving values to members:

    The link between a member and a structure variable is established using the member operator . Which is known as dot operator or period operator.
    For example:

    Book1.price

    Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like
    scanf(%s,book1.file);
    scanf(%d,&book1.pages);

    book1.pages=250;
    book1.price=28.50;

    *

  • #include

    struct student

    {

    int id_no;

    char name[20];

    char address[20];

    int age;

    }newstudent;

    void main()

    {

    printf("Enter the student information");

    printf("Now Enter the student id_no");

    scanf("%d",&newstudent.id_no);

    printf("Enter the name of the student");

    scanf("%s",&newstudent.name);

    printf("Enter the address of the student");

    scanf("%s",&newstudent.address);

    printf("Enter the age of the student");

    scanf("%d",&newstudent.age);

    printf("Student information\n");

    printf("student id_number=%d\n",newstudent.id_no);

    printf("student name=%s\n",newstudent.name);

    printf("student Address=%s\n",newstudent.address);

    printf("Age of student=%d\n",newstudent.age);

    }

    EXAMPLE OF STRUCTURE

    *

  • Initializing structure:


    Example:

    Struct student newstudent
    { 12345, kapildev, Pes college, 19; };


    This initializes the id_no field to 12345,

    the name field to kapildev,

    the address field to pes college and

    the age field to 19.

    *

  • Functions and structures:

    We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we dont effect its corresponding argument.
    Passing structure to elements to functions:


    A structure may be passed into a function as individual member or a separate variable.
    A program example to display the contents of a structure passing the individual elements to a function is shown below.

    #include

    struct emp

    {

    int emp_id;

    char name[25];

    char department[10];

    float salary;

    };

    void display(int,char []);

    void main()

    {

    static struct emp emp1={125,"sampath","operator",7500.00};

    display(emp1.emp_id,emp1.name);

    }

    /* function to display structure variables*/

    void display(int e_no,char e_name[])

    {

    printf("%d %s",e_no,e_name);

    }

    *

  • Arrays of structure:

    It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example:


    structure information
    {
    int id_no;
    char name[20];
    char address[20];
    char combination[3];
    int age;
    }
    student[100];

    *

  • An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below.

    #include

    void main()

    {

    struct info

    {

    int id_no;

    char name[20];

    char address[20];

    int age;

    }std[100];

    int I,n;

    printf("Enter the number of students");

    scanf("%d",&n);

    printf(" Enter Id_no,name address combination age\m");

    for(I=0;I

  • Structure within a structure:

    A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures.
    struct date
    {
    int day;
    int month;
    int year;
    };
    struct student
    {
    int id_no;
    char name[20];
    char address[20];
    int age;
    struct date def;
    struct date doa;
    }oldstudent,newstudent;

    the sturucture student constains another structure date as its one of its members.

    *

  • Union

    Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows:

    union item
    {
    int m;
    float p;
    char c;
    }
    code;

    this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is

    code.m
    code.p
    code.c

    are all valid member variables.

    *

  • Pointers

    Pointer declaration:

    A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable.

    type *variable_name

    Example:

    int *ptr;
    float *ptr1;

    Address operator:

    Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:

    ptr=&num;

    This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.

    *

  • /* A program to illustrate pointer declaration*/
    #include
    void main()
    {
    int *ptr;
    int num;
    num=45;
    ptr=&num;
    printf (\n num is %d\n, num);
    printf (\n The num pointer is %d,ptr);
    }

    Output:

    num is 45

    The num pointer is 45

    *

  • /* Program to display the contents of the variable their address using pointer variable*/

    #include

    void main()

    {

    int num, *intptr;

    float x, *floptr;

    char ch, *cptr;

    num=123;

    x=12.34;

    ch='a';

    intptr=&num;

    cptr=&ch;

    floptr=&x;

    printf("Num %d stored at address %u\n",*intptr,intptr);

    printf("Value %f stored at address %u\n",*floptr,floptr);

    printf("Character %c stored at address %u\n",*cptr,cptr);

    }

    *

  • Pointer expressions & pointer arithmetic

    Like other variables pointer variables can be used in expressions.

    For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid.

    y = *p1 * *p2;
    sum = sum + *p1;
    z = 5* - *p2/p1;
    *p2 = *p2 + 10;

    we can also compare pointers by using relational operators the expressions such as

    p1 >p2 , p1==p2 and p1!=p2 are allowed.

    *

  • /*Program to illustrate the pointer expression and pointer arithmetic*/

    #include

    #include

    void main()

    {

    int *ptr1,*ptr2;

    int a,b,x,y,z;

    clrscr();

    a=30;b=6;

    ptr1=&a;

    ptr2=&b;

    x=*ptr1+ *ptr2-6;

    y=6* (- *ptr1) / *ptr2 + 30;

    printf("\nAddress of a %u",ptr1);

    printf("\nAddress of b %u",ptr2);

    printf("\na=%d, b=%d",a,b);

    printf("\nx=%d,y=%d",x,y);

    ptr1=ptr1 + 70;

    printf("\na=%d, b=%d",a,b);

    printf("\nAdress of a %u",ptr1);

    getch();

    }

    *

  • *

  • Pointers and function:

    The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups.
    1. Call by reference
    2. Call by value.

    Call by value:

    We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.

    *

  • #include

    void swap(int,int);

    void main()

    {

    int x,y;

    x=20;

    y=30;

    printf("\n Value of x and y before function call =%d %d",x,y);

    swap(x,y);

    printf("\n Value of x and y after function call =%d %d",x,y);

    }

    void swap(int p,int q)

    {

    int temp;

    temp=p;

    p=q;

    q=temp;

    }

    Output:

    Value of x and y before function call = 20 30

    Value of x and y after function call = 20 30

    Example of Call by Value

    *

  • Call by Reference

    When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

    /* example of call by reference*?

    #include

    void Swap(int *,int *);

    void main()

    {

    int x,y;

    x=20;

    y=30;

    printf("\n Value of x and y before function call =%d %d",x,y);

    Swap(&x,&y);

    printf("\n Value of x and y after function call =%d %d",x,y);

    }

    void Swap(int *p,int *q)

    {

    int temp;

    temp=*p;

    *p=*q;

    *q=temp;

    }

    *

  • *

  • Dynamic memory allocation:

    The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function.

    Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.

    FunctionTaskmallocAllocates memory requests size of bytes and returns a pointer to the Ist byte of allocated spacecallocAllocates space for an array of elements initializes them to zero and returns a pointer to the memoryfreeFrees previously allocated spacereallocModifies the size of previously allocated space.

    *

  • Allocating a block of memory

    A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

    ptr=(cast_type *)malloc(byte-size);

    ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.

    Example:

    x=(int *)malloc(100*sizeof(int));

    On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.

    *

  • Allocating multiple blocks of memory

    Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero.

    The general form of calloc is:

    ptr=(cast_type *) calloc(n,elem_size);

    The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

    *

  • Releasing the used space

    Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.

    free(ptr);

    ptr is a pointer that has been created by using malloc or calloc.

    *

  • To Alter the size of allocated memory

    The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :

    ptr=realloc(ptr,newsize);

    This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

    *

  • #include

    #include

    #define NULL 0

    void main()

    {

    char *buffer;

    /*Allocating memory*/

    if((buffer=(char *)malloc(10))==NULL)

    {

    printf("Malloc failed\n");

    exit(1);

    }

    strcpy(buffer,"Bangalore");

    printf("\nBuffer contains:%s\n",buffer);

    /*Reallocation*/

    if((buffer=(char *)realloc(buffer,15))==NULL)

    {

    printf("Reallocation failed\n");

    exit(1);

    }

    printf("\nBuffer size modified.\n");

    printf("\nBuffer still contains: %s\n",buffer);

    strcpy(buffer,"Mysore");

    printf("\nBuffer now contains:%s\n",buffer);

    /*freeing memory*/

    free(buffer);

    }

    *

  • Linked List

    A linked list is called so because each of items in the list is a part of a structure, which is linked to the structure containing the next item. This type of list is called a linked list since it can be considered as a list whose order is given by links from one item to the next.

    Structure

    Each item has a node consisting two fields one containing the variable and another consisting of address of the next item(i.e., pointer to the next item) in the list. A linked list is therefore a collection of structures ordered by logical links that are stored as the part of data.

    Consider the following example to illustrator the concept of linking. Suppose we define a structure as follows

    struct linked_list
    {
    float age;
    struct linked_list *next;
    }
    struct linked_list node1,node2;

    ItemItem

    *

  • Advantages of Linked List

    A linked list is a dynamic data structure and therefore the size of the linked list can grow or shrink in size during execution of the program. A linked list does not require any extra space therefore it does not waste extra memory. It provides flexibility in rearranging the items efficiently.

    The limitation of linked list is that it consumes extra space when compared to a array since each node must also contain the address of the next item in the list to search for a single item in a linked list is cumbersome and time consuming.

    *

  • #include

    #include

    #include

    /* structure containing a data part and link part */

    struct node

    {

    int data ;

    struct node *link ;

    };

    void append(struct node **,int );

    void display(struct node * );

    void main( )

    {

    struct node *p;

    p = NULL ;

    append ( &p, 14 ) ;

    append ( &p, 30 ) ;

    append ( &p, 25 ) ;

    append ( &p, 42 ) ;

    append ( &p, 17 ) ;

    display ( p ) ;

    }

    /* adds a node at the end of a linked list */

    void append ( struct node **q, int num )

    {

    struct node *temp, *r ;

    if (*q == NULL)

    {

    temp = malloc(sizeof(struct node)) ;

    temp -> data = num ;

    temp -> link = NULL ;

    *q = temp ;

    }

    else

    {

    temp = *q ;

    /* go to last node */

    while ( temp -> link != NULL )

    temp = temp -> link;

    /* add node at the end */

    r = malloc ( sizeof ( struct node ) ) ;

    r -> data = num ;

    r -> link = NULL ;

    temp -> link = r ;

    }

    }

    void display ( struct node *q )

    {

    printf ( "\n" ) ;

    /* traverse the entire linked list */

    while ( q != NULL )

    {

    printf (" %d ", q -> data ) ;

    q = q -> link ;

    }

    }

    Example of Linked List

    *