C Arrays Function

download C Arrays Function

of 65

Transcript of C Arrays Function

  • 7/31/2019 C Arrays Function

    1/65

  • 7/31/2019 C Arrays Function

    2/65

    An array is a collection of variables ofsimilardatatype.

    A specific element in an array is accessed by an index.

    Arrays may have from one to several dimensions.

    In C, all arrays consist of contiguous memorylocations.

    The lowest address corresponds to the first elementand the highest address to the last element.

    Integer array of 4 elements

    1000 1002 1004 1006

    ARRAYS

  • 7/31/2019 C Arrays Function

    3/65

    Single dimension Arrays The general form of declaring an array is

    [size];

    Eg:

    int marks[5];

    The values are accessed by the indexes.

    Eg:

    marks[0]=90;marks[1]=95;

    marks[2]=98;

    marks[3]=85;

    marks[4]=80;

  • 7/31/2019 C Arrays Function

    4/65

    Example/* Program using arrays */

    #include#include

    void main(){int arr[5],i; //declaring array variable of size 5clrscr();for(i=0;i

  • 7/31/2019 C Arrays Function

    5/65

    Memory mapping

    arr[0] arr[1] arr[2] arr[3] arr[4]

    1 2 3 4 5

  • 7/31/2019 C Arrays Function

    6/65

    Multi dimensional Array

    C supports multidimensional arrays.

    The exact limit, if any, is determined by the compiler.

    The general form of a multidimensional array declarationis

    [size1][size2][size3][sizen];

  • 7/31/2019 C Arrays Function

    7/65

    Two dimensional Array

    The simplest form of the multidimensional array is the

    two-dimensional array. The declaration syntax is

    [size][size];

    LeftIndex Right Index

  • 7/31/2019 C Arrays Function

    8/65

    Example/* Program for two dimensional array */

    #include#includevoid main()

    { int t, i, num[3][4];for(t=0; t

  • 7/31/2019 C Arrays Function

    9/65

    Memory mapping

    num[t][i]

    0 1 2 3

    0 1 2 3 4

    1 5 6 7 8

    2 9 10 11 12

  • 7/31/2019 C Arrays Function

    10/65

    Example/* Matrix Addition */#include

    #include

    void main()

    {

    int mat1[3][3];

    int mat2[3][3];

    int mat[3][3];

    int i,j,k,l;

    printf("\nGive the values for 1st Matrix: \n);for(i=0;i

  • 7/31/2019 C Arrays Function

    11/65

    printf("\nGive the values for 2nd Matrix:\n);

    for(i=0;i

  • 7/31/2019 C Arrays Function

    12/65

    Array Initialization C allows the initialization of arrays at the time of their

    declaration.

    Syntax [size1]. . .[sizeN]={value_list};

    Eg:int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Thevalue_list is a comma-separated list of values whose typeis compatible with data type.

  • 7/31/2019 C Arrays Function

    13/65

    Array InitializationWe can initialize the multi dimensional arrays also.

    Eg:int sqr[3][2] = {1,1,2,4,3,9};

    Another way

    int sqr[3][2] = {{1,1},{2,4},{3,9}};

    This is called Sub aggregate Grouping

  • 7/31/2019 C Arrays Function

    14/65

    Functions

  • 7/31/2019 C Arrays Function

    15/65

    Function

    Function is basic requirement of modularprogramming.

    The process of dividing a large program into small subprograms and manipulating them independently isknown as modular programming.

    A function is a named, independent, block ofstatements that perform well defined, specific taskand may return a value.

  • 7/31/2019 C Arrays Function

    16/65

    Example/* Program for simple function call */

    #include

    void main(){

    message(); //Function Call

    printf("\nCry, and you stop the monotony!");

    }

    message() //Function

    {

    printf("\nSmile,and the world smiles with you...");

    }

  • 7/31/2019 C Arrays Function

    17/65

    Types of Function Pre-defined functions User defined functions

    Pre-defined functions

    The functions, which has special type ofmeaning which isalreadydefined and stored, is called built-in functions orpre-defined functions.

    Eg:

    int a=4;x=pow(a,2);

    User defined functions

    Can be createdbytheuseror programmer for performing

    specific task.

  • 7/31/2019 C Arrays Function

    18/65

    Any C program contains at least one function.

    If a program contains only one function, it must be main( ). If a C program contains more than one function, then one (and

    only one) of these functions must be main( ), because programexecution always begins with main( ).

    There is no limit on the number of functions that might bepresent in a C program.

    Each function in a program is called in the sequence specified bythe function calls in main( ).

    After each function has done its thing, control returns to main().

    When main( ) runs out of function calls, the program ends.

  • 7/31/2019 C Arrays Function

    19/65

    Structure of Function(arg 1,arg 2,,arg n)

    {

    declaration part;

    statements;

    return;}

  • 7/31/2019 C Arrays Function

    20/65

    Exampleint sum(int x,int y){

    int result;result = x + y;return (result);

    }

  • 7/31/2019 C Arrays Function

    21/65

    Properties Every function has a uniquename. This name is used to

    call the function from main() function.

    A function can be calledfrom within anotherfunction.

    A function is independent and it can perform its taskwithout intervention from or interfering with other partsof the program.

    A function returns a value to the calling program. This isoptional and depends upon the task.

  • 7/31/2019 C Arrays Function

    22/65

    Example

    #include

    void main()

    {

    printf("\nI am in main");

    italy();

    printf("\nI am finally back in main");

    }

    italy(){

    printf("\nI am in italy");

    brazil();

    printf("\nI am back in italy");

    }

  • 7/31/2019 C Arrays Function

    23/65

    brazil()

    {

    printf("\nI am in brazil");

    argentina();}

    argentina()

    {

    printf("\nI am in argentina");

    }

  • 7/31/2019 C Arrays Function

    24/65

    Rules A function gets called when the function name is followed

    by a semicolon.main()

    {func();

    }

    A function is defined when function name is followed by apair of braces in which one or more statements may bepresent.

    func(){

    statement 1 ;statement 2 ;statement 3 ;

    }

  • 7/31/2019 C Arrays Function

    25/65

    Rules

    A function can be called any number of times.

    main()

    {display() ;

    display() ;

    }

    display()

    {

    printf("\n Learning C is very Easy");

    }

  • 7/31/2019 C Arrays Function

    26/65

    Rules

    The order in which the functions are defined in a programand the order in which they get called need not necessarilybe same.main()

    {

    display1() ;display2() ;}

    display2(){

    printf("\n Called Later ");}

    display1(){

    printf("\n Called First ");

    }

  • 7/31/2019 C Arrays Function

    27/65

    Rules

    A function can call itself. This is known as Recursion.

    int fact(int n)

    {

    if(n==0)

    return(1);

    return(n*fact(n-1));

    }Note: This function is known as RecursiveFunction.

  • 7/31/2019 C Arrays Function

    28/65

    Parts of the Function

    Function prototype declaration

    Definition of a function

    Function call

    Actual and formal arguments

    The return statement

  • 7/31/2019 C Arrays Function

    29/65

    Parts of the Function Function prototype:

    It helps the compiler to check the return and argumenttypes of the function.

    Function prototype declaration consists of Function return type

    Name

    Arguments list

    Ex:void show(void);

    int sum(int,int);

    float sum(float,int);

  • 7/31/2019 C Arrays Function

    30/65

    Parts of the Function

    Function Definition:

    The block of statement followed by functiondeclarator is called as function definition.

    The declarator and function prototypedeclaration should match each other.

    Function Call:A function is called by its name followed by

    arguments list enclosed in parenthesis andterminated by semi-colon.

  • 7/31/2019 C Arrays Function

    31/65

    Parts of the FunctionActual and formal arguments:

    The arguments declared in calling function arecalled actual arguments.

    The arguments declared in function declaratorare called formal arguments.

    The return statement:

    The return statement is used to return the value tocaller function.

    The return statement returns only one value at atime.

    Syntax : return (variable name);

  • 7/31/2019 C Arrays Function

    32/65

    void main()

    {

    int sum(int,int);

    int a=10,b=20,c;

    c=sum(a,b);

    }

    int sum(int x,int y)

    { return(x+y);

    }

    Function Prototype

    Function call

    Actual arguments

    Function declarator

    Function definition

    Return statement

    Formal arguments

    Parts of the Function

  • 7/31/2019 C Arrays Function

    33/65

    Types of Function

    A function may belong to any one of the followingcategories:

    1. Functions with no arguments and no return values.

    2. Functions with arguments and no return values.

    3. Functions with arguments and return values.

    4. Function with no arguments and return values.

  • 7/31/2019 C Arrays Function

    34/65

    Functions with no arguments and no return values This is the simplest function ,it does not receive any

    arguments from the called function and does notreturn any value from calling function.

    Types of Function

  • 7/31/2019 C Arrays Function

    35/65

    #include

    void main()

    {

    void show();

    show();

    }

    void show()

    {

    printf(Hi);

    }

    Example

  • 7/31/2019 C Arrays Function

    36/65

    Functions with arguments and no return values This function receives arguments from calling

    function and does not return value to the callingfunction.

    Types of Function

  • 7/31/2019 C Arrays Function

    37/65

    /* Example for with argument no returnvalue*/

    #include

    #include

    void main()

    {

    void line(char,int);

    line(*,20); //function call

    printf(\n Welcome to KGISL - iTech);

    line(&,20); //function call

    getch();

    }

    Example

  • 7/31/2019 C Arrays Function

    38/65

    void line(char ch,int n)

    {

    int i;

    for(i=0;i

  • 7/31/2019 C Arrays Function

    39/65

    #include

    #include

    void add(int x,int y)

    {

    int result;

    result = x+y;printf("Sum of %d and %d is %d.\n\n",x,y,result);

    }

    void main()

    {

    clrscr();add(17,95); //call 1

    add(59, 344); //call 2

    add(198,7895); //call 3

    getch();

    }

    Example

    There is no

    function prototype

  • 7/31/2019 C Arrays Function

    40/65

    Functions with arguments and return values This function receives arguments from calling

    function and returns the computed value back to thecalling function.

    Types of Function

  • 7/31/2019 C Arrays Function

    41/65

    #include

    #include

    int sum(int,int); //function prototype

    void main(){

    int i,j,k;

    clrscr();

    printf(Enter value of i and j:);scanf(%d%d,&i,&j);

    k=sum(i,j); //function call

    Example

  • 7/31/2019 C Arrays Function

    42/65

    printf(\n Sum is:%d,k);getch();

    }

    /* function definition for adding twonumbers */

    int sum(int a,int b){

    int c;c = a+b;return c;

    }

  • 7/31/2019 C Arrays Function

    43/65

    Functions with no arguments and return values

    Types of Function

  • 7/31/2019 C Arrays Function

    44/65

    Function Call

    There are two ways to call a function.

    1. Call byValue

    2. Call byReference

  • 7/31/2019 C Arrays Function

    45/65

    Example for Call by Value#include

    #include

    int main()

    {int x,y;

    clrscr();

    printf("Enter x and y value:");

    scanf("%d%d",&x,&y); //getting valuesprintf("\nBefore swapping:x=%d y=%d",x,y);

    swap(x,y); //Passing the values

    return 0;

  • 7/31/2019 C Arrays Function

    46/65

    int swap(int a,int b)

    {

    int c;

    c=a;a=b;

    b=c;

    printf("\n after swapping:a=%d b=%d",a,b);

    return 0;

    }

  • 7/31/2019 C Arrays Function

    47/65

    Example for Call by Reference

    #include#include

    int main()

    {

    int x,y;clrscr();

    printf("Enter x and y value:");

    scanf("%d%d",&x,&y);

    printf("\nBefore swapping:x=%d y=%d",x,y);

    swap(&x,&y); //Passing addresses

    return 0;

    }

  • 7/31/2019 C Arrays Function

    48/65

    int swap(int *a,int *b){

    int c;

    c=*a;*a=*b;

    *b=c;

    printf("\nAfter swapping:a=%d b=%d",*a,*b);

    return 0;}

  • 7/31/2019 C Arrays Function

    49/65

    Advantages of Function Support for modular programming.

    Reduction in program size.

    Code duplication is avoided.

    Code reusability is provided.

    Functions can be called repetitively.

    A set of functions can be used to form Libraries.

    Individual functions can be easily built,tested.

  • 7/31/2019 C Arrays Function

    50/65

    Pointers

  • 7/31/2019 C Arrays Function

    51/65

    Pointers Pointers provide the means by which functions can

    modify their calling arguments.

    Pointers support dynamic allocation.

    Pointers can improve the efficiency of certain routines.

  • 7/31/2019 C Arrays Function

    52/65

    What are pointers?

    Apointeris a variable that holds a memory address.

    This address is the location of another object (typicallyanother variable) in memory.

    Memory Address

    1000

    1001

    1002

    1003

    1004

    Variable in memory

    1003

    .

    .

    .Memory

  • 7/31/2019 C Arrays Function

    53/65

    Declaration of Pointer Syntax:

    *;

    The base type of the pointer defines what type ofvariables the pointer can point to.

  • 7/31/2019 C Arrays Function

    54/65

    Pointer Operators There are two special pointer operators: *and &. The &(Referencing Operator) is a unary operator that

    returns the memoryaddress of its operand.

    m=&count;* (De-referencing Operator) is the complement of&.

    It is a unary operator that returns thevalue located atthe address that follows.

    q=*m;

    count m q2000

    1002

    1002 2000

  • 7/31/2019 C Arrays Function

    55/65

    Example/* Program for pointers */

    #include#include

    void main(){int a,*p;clrscr();

    printf("Enter a:);

    scanf(%d,&a);p=&a;printf(\na: %d \np: %d \nvalue: %d,a,p,*p);getch();

    }

  • 7/31/2019 C Arrays Function

    56/65

    The void type of pointer is a special type of pointer.

    In C, void represents the absence of type.

    So void pointers are pointers that point to a valuethat has no type.

    Void Pointers

  • 7/31/2019 C Arrays Function

    57/65

    int a;

    int v1;

    void *ptr;

    a=100;

    ptr=&a;

    v1=*(int*)ptr; //defining the type

  • 7/31/2019 C Arrays Function

    58/65

    Example-1

    int a,v1;char b,v2;void *ptr;

    a=100;ptr=&a;v1=*(int*)ptr; //now it s pointing to integerprintf(" %d \n ",v1);

    b='S';ptr=&b;v2=*(char*)ptr; //now it s pointing to characterprintf(" %c \n ",v2);

  • 7/31/2019 C Arrays Function

    59/65

    Example-2

    #include#includevoid display(int x,void *y){

    int a;

    char b;if(x==1){

    a=*(int*)y;printf("Integer Value %d \n ",a);

    }if(x==2){

    b=*(char*)y;printf("Character Value %c \n ",b);

    }

    }

  • 7/31/2019 C Arrays Function

    60/65

    void main(){int s1;char s2;void *ptr1;

    clrscr();s1=300;ptr1=&s1;display(1,ptr1); //function call with int values2='J';

    ptr1=&s2;display(2,ptr1);//function call with char valuegetch();}

  • 7/31/2019 C Arrays Function

    61/65

    Pointer ExpressionAssignment

    int var,*p1,*p2;

    p1=&var;

    p2=p1;

    In this pointers p1 and p2pointsto the samevariablevar.

    Arithmetic

    int var,*p;

    p=&var;

    p++; // or p--;

    In this pointer moves to the next memory location

  • 7/31/2019 C Arrays Function

    62/65

    Pointer with Array Syntax:

    int *ptr;

    int sample[5];

    ptr=sample;

    It can also use & operator to specify the address of

    1st element.ptr=&sample;

    Note: Pointers can be arrayed like any other data type.

  • 7/31/2019 C Arrays Function

    63/65

    Example-1

    #includevoid main(){int *p,i=0;int x[5]={5,9,6,3,7};

    p=x; //initializing with base addressprintf(Element\tValue\tAddress\n\n);while(i

  • 7/31/2019 C Arrays Function

    64/65

    #include

    void main()

    {

    int a[4],v1,v2,*ptr;a[0]=100;

    a[1]=200;

    a[2]=300;

    a[3]=400;

    ptr=a;

    printf(" \n %d ",*ptr);

    ptr++;

    printf(" \n %d ",*ptr);

    v1=*(ptr+1);printf(" \n %d ",v1);

    ptr++;

    v2=*(ptr-1);

    printf(" \n %d ",v2);

    }

    Example-2

  • 7/31/2019 C Arrays Function

    65/65

    Multiple Indirection

    Multipleindirection or pointerstopointers is a pointerpoint to another pointer that points to the target value.

    Eg:

    float bal;

    float *balance,**newbalance;

    balance=&bal;

    newbalance=&balance; Multiple indirection can be carried on to whatever

    extent required.

    More than a pointer to a pointer is rarely needed.