Introduction to C Language Day 2

Embed Size (px)

Citation preview

  • 8/8/2019 Introduction to C Language Day 2

    1/59

    Introduction to C LanguageIntroduction to C Language

    Day 2

    by Supreet Singh

  • 8/8/2019 Introduction to C Language Day 2

    2/59

    Arrays

    Arrays

  • 8/8/2019 Introduction to C Language Day 2

    3/59

    ArraysArrays

    An array is a series of variables, all being sametype and size

    Each variable in an array is called an array

    element All the elements are of same type, but may contain

    different values

    The entire array is contiguously stored in memory

    The position of each array element is known asarray index or subscript

    An array can either be one dimensional (1-D) ortwo dimensional (2-D) or Multi-dimensional

  • 8/8/2019 Introduction to C Language Day 2

    4/59

    Declaring a 1Declaring a 1--D ArrayD Array

    Syntax:

    data-type arrayname[size];

    Example:

    int aiEmployeeNumbers[6];float afSalary[6];

    The array index starts with zero

    The valid array indexes for the above declared array is 0 to 5

    When an array is declared inside a function without initializing it, the elementshave unknown (garbage) values and outside the function the elements have

    zero/default values

  • 8/8/2019 Introduction to C Language Day 2

    5/59

    Declaring and Initializing arrays (1 of 2)Declaring and Initializing arrays (1 of 2)

    Arrays can be initialized as they are declared

    Example:

    int aiEmployeeNumbers[] = {15090, 15091, 15092,

    15093,15094, 15095};

    The size in the above case is optional and it isautomatically computed

    In the above example size of the array is 6 and itoccupies 6 * 4 = 24 bytes (6 is the size of the array and4 is the number of bytes required to store one integeron Windows platform)

  • 8/8/2019 Introduction to C Language Day 2

    6/59

    Declaring and Initializing 1Declaring and Initializing 1--D arrays (2 ofD arrays (2 of

    2)2)

    When an array is partially initialized within afunction the remaining elements will begarbage values and outside any function the

    remaining elements will be zero valuesExample:

    int aiEmployeeNumbers[6] ={15090, 15091, 15092};

    In the above example, the array indexes from3 to 5 may contain zero or garbage values

  • 8/8/2019 Introduction to C Language Day 2

    7/59

    22--D ArraysD Arrays

    A 2-D array is used to store tabular data in terms of rows andcolumns

    A 2-D array should be declared by specifying the row size and thecolumn size

    To access the individual elements, the row and the column should besupplied

    The 2-D array is essentially a one dimensional array wherein eachelement itself is another array, hence an array of arrays

    As far storage is concerned, the row elements are in continuouslocations of memory hence called row major ordering in C language

    The table type visualization of rows and columns is therefore only forconvenience

  • 8/8/2019 Introduction to C Language Day 2

    8/59

    Declaring and using 2Declaring and using 2--D ArraysD Arrays

    A 2-D array can be declared by specifying the maximum size for rows andcolumns

    Syntax:data type arrayname [Row Size][Column Size];

    Example:

    int aiEmployeeInfo[3][2];The above declaration declares aiEmployeeInfo with 3 rows and 2 columns

    To access the individual elements row index (starts from zero) and thecorresponding column index (starts from zero) should be supplied

    Example:printf(%d,aiEmployeeInfo[0][1]);

    The above printf references the information at 0th row 1st column

  • 8/8/2019 Introduction to C Language Day 2

    9/59

    Initializing 2Initializing 2--D Arrays(1 of 2)D Arrays(1 of 2)

    A 2-D array can be initialized as given below:

    int aiEmployeeInfo[3][2]= {101,1,102,1,103,2};

    In the above declaration,101, 102 and 103 refers to employeeids and they are stored

    in [0][0], [1][0] and [2][0] positions1,1 and 2 refers to Job Codes and they are stored in [0][1],

    [1][1] and [2][1] positions

  • 8/8/2019 Introduction to C Language Day 2

    10/59

    Initializing 2Initializing 2--D Arrays (2 of 2)D Arrays (2 of 2)

    A 2-D array can be declared without specifying the row size ifit is initialized

    Example:

    int aiEmployeeInfo[][3]= {101,1,102,1,103,2};Since there are six initial values and the column size is 3, the

    number of

    rows is taken as 2

    If the column size is not supplied then there will be a

    compilation error

  • 8/8/2019 Introduction to C Language Day 2

    11/59

    Pointers

  • 8/8/2019 Introduction to C Language Day 2

    12/59

    Pointers(1 of 5)Pointers(1 of 5)

    A pointer is a special variable which stores theaddress of a memory location. It can be theaddress of a variable or directly the address of alocation in memory

    A variable is a name given to a set of memorylocations allocated to it

    For every variable there is an address, which is the

    starting address of its set of memory locations

    If a variable called p holds the address of anothervariable i then p is called as a pointer variableand p is said to point to i

  • 8/8/2019 Introduction to C Language Day 2

    13/59

    PointersPointers --Address of Operator(2 of 5)Address of Operator(2 of 5)

    Ampersand (&) is the address of operator .It is used to fetch the

    memory address of a variable

    * is called the indirection operator, dereferencing or value at address

    operator and is used with a pointer variable to fetch the value at a

    given memory location Both these operators are used with pointers

  • 8/8/2019 Introduction to C Language Day 2

    14/59

    PointersPointers -- Address of Operator(3 of 5)Address of Operator(3 of 5)

    To print the address of a variable, precede the variable with an

    ampersand (&)

    Example:

    int iNumber = 100;

    printf(The value is %d\n,iNumber);

    printf(The address is %u\n,&iNumber);

    printf(The address in hexa decimal is

    %x\n,&iNumber);

    Since an address is an unsigned

    integer, %u is used as a conversion

    specifier

    An address can be printed in hexa

    decimal form using %x as the conversion

    specifier

  • 8/8/2019 Introduction to C Language Day 2

    15/59

    Pointers(4 of 5)Pointers(4 of 5)

    To declare a pointer variable, use the following syntaxdata-type *pointerName;

    Example:

    1. int *piCount;This declaration tells the compiler that piCount will beused to store the address of an integer value in other words piCount points to an integer variable.

    2. float *pfBasic;

    This statement declares pfBasic as a pointer variablewhich can contain the address of a float variable.

    Note: The size of pointer variable on Windows platform is 4 bytes.

    However it may vary from one platform to another.

  • 8/8/2019 Introduction to C Language Day 2

    16/59

    Pointers(5 of 5)Pointers(5 of 5)

    Example:

    int iCount = 8;

    int *piCount;

    piCount = &iCount;

    printf(Value=%d,*piCount);

    iCount: an integer variable

    piCount: an integer pointer &: the address of operator

    * : the indirection operator

  • 8/8/2019 Introduction to C Language Day 2

    17/59

    Reading Contents of a variable usingReading Contents of a variable using

    PointersPointers

    To access the value at the address stored in the pointer, usethe following syntax *pointervariable

    Example:printf(%d, *piCount);

    y

    Here the*

    operator preceding piCount will fetch the value at theaddress stored in piCount

    Using == operator (Equal to) on pointers, will check whetherboth pointers being compared are pointing to the sameaddress or not

    Uninitialized pointers may point to any memory location

    Using * (indirection operator) on uninitialized pointers mayresult in program throwing a run time error

  • 8/8/2019 Introduction to C Language Day 2

    18/59

    NULL PointersNULL Pointers

    Using a pointer without initializing it to anyvalid address may result in data corruption oreven program crash

    To differentiate between initialized and uninitialized pointers, we usually set an uninitialized pointer to NULL

    Example:

    /* Initializing pointer to NULL */

    int *piCount = NULL;

  • 8/8/2019 Introduction to C Language Day 2

    19/59

    StringsStrings

  • 8/8/2019 Introduction to C Language Day 2

    20/59

    Strings (1 of 2)Strings (1 of 2)

    A string is a series of characters in a groupthat occupy contiguous memory

    Example:

    CDAC

    Information Technology

    A string should always be enclosed with indouble quotes ()

  • 8/8/2019 Introduction to C Language Day 2

    21/59

    Strings (2 of 2)Strings (2 of 2)

    In memory, a string ends with a nullcharacter\0

    Space should be allocated to store \0 aspart of the string

    A null character (\0) occupies 1 byte ofmemory

  • 8/8/2019 Introduction to C Language Day 2

    22/59

    Declaration of Strings (1 of 2)Declaration of Strings (1 of 2)

    Syntax:char variablename [Number_of_characters];

    Example:char acEmployeeName[20];

    Here 20 implies that the maximum number of characters can be 19and one position is reserved for \0

    Since a character occupies one byte, the above array occupies 20bytes (19 bytes for the employee name and one byte for \0)

  • 8/8/2019 Introduction to C Language Day 2

    23/59

    Declaration of Strings (2 of 2)Declaration of Strings (2 of 2)

    /* Declare String as a char pointer */

    char *pcName = Cdac;

    /* Declaring a string as a character array */char acName[ ] = Cdac;

    Think why \0 requires only one byte!!

  • 8/8/2019 Introduction to C Language Day 2

    24/59

    Printing Strings to Console (1 of 2)Printing Strings to Console (1 of 2)

    Using Character pointer:

    char *pcProg = C Fundamentals;printf(pcProg);

    printf(This is %s course,pcProg);

    Using CharacterArray:

    char acProg[] = C Fundamentals;printf(acProg);

    OR

    printf(%s, acProg );printf(This is %s course,acProg);

  • 8/8/2019 Introduction to C Language Day 2

    25/59

    Printing Strings to Console (2 of 2)Printing Strings to Console (2 of 2)

    Printing a string as part of a formattedstring

    int iCourseId = 27;char *pcProg = C Fundamentals;

    /* print the courseId (Int)and Course name(char*) */

    printf(The Id of this courseis %d and this course is %s

    \n,iCourseId, pcProg);

  • 8/8/2019 Introduction to C Language Day 2

    26/59

    strlen() Functionstrlen() Function

    strlen() function is used to count the number of characters in the string

    Counts all the characters excluding the null character \0

    Syntax:

    unsigned int strlen (char string[]);Here string[ ] can be a string constant or a character pointer or a character

    array and the function returns unsigned int

    Example:

    strlen(Programming Fundamentals);returns 24

    strlen(acItemCategory); returns the number of characters inthe

    character array acItemCategory

  • 8/8/2019 Introduction to C Language Day 2

    27/59

    Input of StringsInput of Strings scanf and gets functionsscanf and gets functions

    scanf(%s, acItemCategory);

    scanf(%s, &acItemCategory[0]);

    Both the input functions are valid. The first one passes the base

    address (Address of the first element) implicitly

    The second function passes the address of the first element explicitly

    gets(acItemCategory);

    gets(&acItemCategory[0]);

    This is an unformatted function to read strings

  • 8/8/2019 Introduction to C Language Day 2

    28/59

    String Handling functionsString Handling functions

    The following are the string functions that aresupported by C

    strlen() strcpy() strcat()strcmp() strcmpi() strncpy()

    strncat() strncmp()strnicmp()

    These functions are defined in string.h header file

    All these functions take either a character pointer or acharacter array as an argument

  • 8/8/2019 Introduction to C Language Day 2

    29/59

    strcpy() Functionstrcpy() Function

    strcpy() function is used to copy one string to another

    Syntax:

    strcpy (Dest_String , Source_String);

    y Here Dest_string should always be variable

    y Source_String can be a variable or a string constant

    y The previous contents of Dest_String, if any, will be over written

    Example:

    char acCourseName[40];

    strcpy(acCourseName , C Programming);

    The resultant string in acCourseName will be C Programming

  • 8/8/2019 Introduction to C Language Day 2

    30/59

    strcat() Functionstrcat() Function

    strcat() function is used to concatenate (Combine) two strings

    Syntaxstrcat( Dest_String_Variable , Source_String ) ;

    In this, the Destination should be a variable and Source_String can

    either be a string constant or a variable.The contents of Dest_String is concatenated with Source_Stringcontents and the resultant string is stored into Dest_String variable.

    Example:char acTraineeFpCourse [50] = The course is ;strcat(acTraineeFpCourse,Oracle 10G);

    The resultant string in acTraineeFPCourse will be The course isOracle 10G

  • 8/8/2019 Introduction to C Language Day 2

    31/59

    strcmp() Function (1 of 2)strcmp() Function (1 of 2)

    strcmp() function is used to compare twostrings

    strcmp() does a case sensitive (Upper caseand lower case alphabets are considered tobe different) comparison on strings

    Syntax:int strcmp( String1 , String2);Here both String1 and String2 can either be a variable or a string

    constant

  • 8/8/2019 Introduction to C Language Day 2

    32/59

    strcmp() Function (2 of 2)strcmp() Function (2 of 2)

    strcmp() function returns an integer value

    If strings are equal, it returns zero

    If the first string is alphabetically greater than thesecond string then, it returns a positive value

    If the first string is alphabetically less than the second

    string then, it returns a negative value

    Example:

    strcmp(My Work, My Job); returns apositive value

  • 8/8/2019 Introduction to C Language Day 2

    33/59

    strcmpi() Functionstrcmpi() Function

    strcmpi() function is same as strcmp()

    function but it is case insensitive

    Example:strcmpi(My WoRk , MY work); returns zero

  • 8/8/2019 Introduction to C Language Day 2

    34/59

    FunctionsFunctions

  • 8/8/2019 Introduction to C Language Day 2

    35/59

    FunctionsFunctions

    A function is a section of a program that performs a specific task

    Function groups a number of program statements into a unit and

    gives it a name. This unit can be reused wherever it is required in

    the program

    Functions employ the top down approachand hence becomes

    easier to develop and manage

    main()

    FunctionFunctionFunction

    callcallcall

    User defined function

  • 8/8/2019 Introduction to C Language Day 2

    36/59

    Advantages ofFunctionsAdvantages ofFunctions

    The functions can be developed by different people and canbe combined together as one application

    Solving a problem using different functions makesprogramming much simpler with fewer defects

    Easy to code,modify,debug and also to understand the code

    Functions support reusability ie. once a function is written itcan be called from any other module without having to rewrite

    the same. This saves time in rewriting the same code

  • 8/8/2019 Introduction to C Language Day 2

    37/59

    Passing values to functions and returningPassing values to functions and returning

    valuesvalues

    Functions are used to perform a specific task on a set of values

    Values can be passed to functions so that the function performs thetask on these values

    Values passed to the function are called arguments

    After the function performs the task, it may send back the results tothe calling function

    The value sent back by the function is called return value

    A function can return back only one value to the calling functionthrough a return statement

    Function may be called either from within main() or from withinanother function

  • 8/8/2019 Introduction to C Language Day 2

    38/59

    Elements of a FunctionElements of a Function

    Function Declaration orFunction Prototype :

    The function should be declared prior to its usage

    Function Definition :

    Implementing the function or writing the task of the function

    Consists of

    Function Header

    Function Body

    Function Invocation orFunction call:

    To utilize a functions service, the function have to be invoked

    (called)

  • 8/8/2019 Introduction to C Language Day 2

    39/59

    Declaring Function Prototypes (1 of 2)Declaring Function Prototypes (1 of 2)

    A function prototype is the information to the compilerregarding the user-defined function name, the datatype and the number of values to be passed to thefunction and the return data type from the function

    This is required because the user-defined function iswritten towards the end of the program and the maindoes not have any information regarding thesefunctions

    The function prototypes are generally written beforemain. A function prototype should end with asemicolon

  • 8/8/2019 Introduction to C Language Day 2

    40/59

    Declaring Function Prototypes (2 of 2)Declaring Function Prototypes (2 of 2)

    Function Prototypes declare ONLY the signature of the function beforeactually defining the function

    Here signature includes function name, return type, list of parameter datatypes and optional names of formal parameters

    Syntax:Return_data_type FunctionName (data_type arg1,

    data_type arg2,...,data_type argn );

    Example:

    int fnValidateDate(int iDay,int iMonth, int iYear);

    In the above example, iDay, iMonth and iYear are optional. Thesame can also be written as:

    int fnValidateDate(int,int, int);

  • 8/8/2019 Introduction to C Language Day 2

    41/59

    Writing UserWriting User--Defined FunctionsDefined Functions

    A function header and body looks like this:Return-data-type function-name(data-type argument-1,

    data-type argument-2,.){

    /* Local variable declarations *//* Write the body of the function here */

    Statement(s);return (expression);

    }

    The return data type can be any valid data type

    If a function does not return anything then the voidis the return type

    A function header does not end with a semicolon

    The return statement is optional. It is required only when a valuehas to be returned

  • 8/8/2019 Introduction to C Language Day 2

    42/59

    Writing UserWriting User--Defined FunctionsDefined Functions

    int fnAdd(int iNumber1, int iNumber2){

    /* Variable declaration*/

    int iSum;

    /* Find the sum */

    iSum = iNumber1 + iNumber2;

    /* Return the result */

    return (iSum);

    }

    Return data type Arguments

    (Parameters)

    Function

    header

    Function Body

    Can also be written as return iSu

  • 8/8/2019 Introduction to C Language Day 2

    43/59

    Returning valuesReturning values

    The result of the function can be given back to the calling functions

    return statement is used to return a value to the calling function

    Syntax:return (expression) ;

    Example:

    return(iNumber * iNumber);return 0;

    return (3);return;

    return (10 * iNumber);

  • 8/8/2019 Introduction to C Language Day 2

    44/59

    Calling UserCalling User--Defined Functions (1 of 2)Defined Functions (1 of 2)

    A function is called by giving its name and passing therequired arguments

    The constants can be sent as arguments to functions

    /* Function is called here */iResult = fnAdd(10, 15);

    The variables can also be sent as arguments tofunctions

    int iResult,iNumber1=10, iNumber2=20;

    /* Function is called here */

    iResult = fnAdd(iNumber1, iNumber2);

  • 8/8/2019 Introduction to C Language Day 2

    45/59

    Calling UserCalling User--Defined Functions (2 of 2)Defined Functions (2 of 2)

    Calling a function which does not returnany value

    /* Calling a function */

    fnDisplayPattern(15);

    Calling a function that do not take any

    arguments and do not return anything/* Calling a function */

    fnCompanyNameDisplay();

  • 8/8/2019 Introduction to C Language Day 2

    46/59

    Function TerminologiesFunction Terminologies

    void fnDisplay() ;

    int main(int argc, char **argv){

    fnDisplay();

    return 0;

    }

    void fnDisplay(){

    printf(Hello World);

    }

    Function Prototype

    Calling

    Function

    Function Call Statement

    Function

    Definition

    Called Function

  • 8/8/2019 Introduction to C Language Day 2

    47/59

    Formal and Actual ParametersFormal and Actual Parameters

    The variables declared in the functionheader are called as formal parameters

    The variables or constants that arepassed in the function call are called asactual parameters

    The formal parameter names and actualparameters names can be the same ordifferent

  • 8/8/2019 Introduction to C Language Day 2

    48/59

    FunctionsFunctions Example (1 of 2)Example (1 of 2)

    int fnAdd(int iNumber1, int iNumber2);

    int main(int argc, char **argv) {

    int iResult,iValue1=5, iValue2=10;

    /* Function is called here */

    iResult = fnAdd(iValue1, iValue2);

    printf(Sum of %d and %d is %d\n,iValue1,iValue2,iResult);

    return 0;

    }

    Function Prototype

    Actual Arguments

  • 8/8/2019 Introduction to C Language Day 2

    49/59

    FunctionsFunctions Example (2 of 2)Example (2 of 2)

    /* Function to add two integers */

    int fnAdd(int iNumber1, int iNumber2){

    /* Local variable declaration*/

    int iSum;

    iSum = iNumber1 + iNumber2; /* Find the sum */

    return (iSum); /* Return the result */

    }

    Formal Arguments

    Return value

  • 8/8/2019 Introduction to C Language Day 2

    50/59

    ParameterPassing TechniquesParameterPassing Techniques

    When a function is called and if the

    function accepts some parameters, then

    there are two ways by which the function

    can receive parameters

    Pass by value

    Pass by reference

  • 8/8/2019 Introduction to C Language Day 2

    51/59

    Pass by Value (1 of 3)Pass by Value (1 of 3)

    When parameters are passed from thecalled function to a calling function, thevalue of the actual argument is copied

    onto the formal argument

    Since the actual parameters and formal

    parameters are stored in different memorylocations, the changes in formalparameters do not alter the values ofactual parameters

  • 8/8/2019 Introduction to C Language Day 2

    52/59

    Pass by Value (2 of 3)Pass by Value (2 of 3)

    void fnUpdateValues(int iNumber1, int iNumber2);

    int main(int argc, char **argv) {int iValue1=100, iValue2=250;printf("\n\nBefore calling the function: ");

    printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);

    /* Call the function */

    fnUpdateValues(iValue1, iValue2);

    printf("After calling the function: ");

    printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);

    return 0;}void fnUpdateValues(int iNumber1, int iNumber2){

    /* Update the values */

    iNumber1 = iNumber1 + 15;

    iNumber2 = iNumber2 - 10;}

  • 8/8/2019 Introduction to C Language Day 2

    53/59

    Pass by Value (3 of 3)Pass by Value (3 of 3)

    main()

    100

    200

    fnUpdateValues()

    115

    240

    End of function fnUpdateValues

  • 8/8/2019 Introduction to C Language Day 2

    54/59

    Pass by Reference (1 of 4)Pass by Reference (1 of 4)

    Addresses of actual parameters arepassed

    The function should receive the addressesof the actual parameters through pointers

    The actual parameters and formalparameters if referencing the samememory location, then the changes thatare made become permanent

  • 8/8/2019 Introduction to C Language Day 2

    55/59

    Pass By Reference (2 of 4)Pass By Reference (2 of 4)

    void fnUpdateValues(int *piNumber1, int *piNumber2);

    int main(int argc, char **argv){

    int iValue1=100, iValue2=250;printf("\n\nBefore calling the function: ");

    printf("ivalue1=%diValue2=%d\n\n",iValue1,iValue2);

    /* Call the function and send the address of thevariables */

    fnUpdateValues(&iValue1, &iValue2);

    printf("After calling the function: ");

    printf("ivalue1=%diValue2=%d\n\n",iValue1,iValue2);return 0;

    }

  • 8/8/2019 Introduction to C Language Day 2

    56/59

    Pass By Reference (3 of 4)Pass By Reference (3 of 4)

    void fnUpdateValues(int

    *piNumber1, int *piNumber2){

    *piNumber1 = *piNumber1 + 15;

    *piNumber2 = *piNumber2 - 10;

    }

  • 8/8/2019 Introduction to C Language Day 2

    57/59

    Pass by Reference (4of 4)Pass by Reference (4of 4)

    amain()

    115

    240

    fnUpdateValues()

    Address of

    iValue1

    Address of

    iValue2

    End of function fnUpdateValues

  • 8/8/2019 Introduction to C Language Day 2

    58/59

    QUESTIONS?QUESTIONS?

  • 8/8/2019 Introduction to C Language Day 2

    59/59

    THANK YOU.THANK YOU.