C Programming Overview

Embed Size (px)

Citation preview

  • 8/12/2019 C Programming Overview

    1/41

    C Programming Overview

    Manas Mukul [email protected]

    9124999460

  • 8/12/2019 C Programming Overview

    2/41

    Compiling and Running a C program

    Preprocessor

    Compiler

    Assembler

    Linker

    Loader

  • 8/12/2019 C Programming Overview

    3/41

    Layout of the Program Memory

    Static memory

    Global VariablesStatic Variables

    Heap memory

    Dynamically

    allocated memory

    Stack Memory

    Auto variables

    Function

    parameter

    Program/ Text

    Program

    statements

  • 8/12/2019 C Programming Overview

    4/41

    First Simple Code in C

    #include

    int main()

    {/* my first program in C */

    printf("Hello, World! \n");

    return 0;}

    Preprocessor command

    Main functionentry point

    Comment in Cignored

    while compilation

    Built in Function with arguments

    Main functionreturn value

  • 8/12/2019 C Programming Overview

    5/41

    Tokens in C

    A C program consists of various tokens and atoken is either a keyword, an identifier, a

    constant, a string literal, or a symbol.

    printf("Hello, World! \n");

    printf

    (

    "Hello, World! \n"

    )

    ;

    5 tokens

  • 8/12/2019 C Programming Overview

    6/41

    CData Types

    Basic Data Types

    Integer and Float with different sizes

    Enumerated Data Types

    Arithmetic type with discrete integer values

    Void Data

    Indicates no Value

    Derived Data Types

    Pointer Type, Array Type, Structure Type and Unio

  • 8/12/2019 C Programming Overview

    7/41

    Basic Data Type

    Data Type Size in Bytes

    char 1

    short 2

    int 2 or 4

    long 4

    float 4

    double 8

    long double 10

    To find the size use the sizeof(type) operator

  • 8/12/2019 C Programming Overview

    8/41

    The void type

    The void type is used in three kinds of situation

    Function Returns as void Function arguments as void

    Pointers to void generic pointers

  • 8/12/2019 C Programming Overview

    9/41

    Enumerated Data Type

    Enumeration type allows programmer to define their own

    data type . Keyword enumis used to defined enumerated

    data type

    #include enum color{ green, yellow, pink, blue, red};

    int main()

    {

    enum color select;

    select=green;return 0;

    }

    By default the

    values starting from

    0 will be assigned

    to green, yellow,

    pink, blue, red

  • 8/12/2019 C Programming Overview

    10/41

    Variables in C

    A variable is a name given to a storage area that our programs can manipulate

    The name of the variable is decided by the user along with the type of data it can h

    Variablesdeclaration and definition can be done together

    int d = 3, f = 5; /* initializing d and f. */

    double pi = 3.14159; /* declares an approximation of pi. */

    char x = 'x'; /* the variable x has the value 'x'. */

    The scope or the time duration, a variable can exist is defined by the storage class

  • 8/12/2019 C Programming Overview

    11/41

    Programming Storage Class

    Automatic Storageclass

    Variables declared inside

    the function body are

    automatic by default.

    These variable are also

    known as local variables

    as they are local to the

    function and doesn't have

    meaning outside that

    function.

    autoExternal storage class

    Global variables declared inone file can be accessed in

    another file. Have a greater

    scope than global variables.

    extern

    Register Storage classThey are similar to the

    auto declared variables,

    however they can be

    accessed faster as they

    are stored in the register.

    register

    Static storage class

    Static variables exist for theentire duration of the

    program however they

    cannot be accessed outside

    the file.

    stat ic

  • 8/12/2019 C Programming Overview

    12/41

    Small QuizWhat will be the output?

    #include void Check();

    int main()

    {

    Check();

    Check();

    Check();}

    void Check()

    {

    int c=0; printf("%d\t",c);

    c+=5;

    }

    Output 1: 0 0

  • 8/12/2019 C Programming Overview

    13/41

    Constants and Literals

    Constants and Literals are the

    same.

    They are the fixed values that the

    program may not alter during its

    execution.

    Constants in C can be defined in two ways

    #define pre processor

    const keyword

    #include

    #define LENGTH 10

    int main()

    {

    constint WIDTH = 5;

    area = LENGTH * WIDTH;printf("value of area : %d",

    area);

    return 0;

    }

  • 8/12/2019 C Programming Overview

    14/41

    C Operators

    An operator is a symbol that tel ls the compi ler to

    perform speci f ic mathematical or logical

    manipulat ions

    The following operators are present in C:

    Arithmetic Operators [+,-,*,/,%,++,--]

    Relational Operators [ ==,!=,>,=,

  • 8/12/2019 C Programming Overview

    15/41

    Bitwise operators

    #include main()

    {

    int c = 0;

    unsigned int a = 60; /* 60 = 00111100 */

    unsigned int b = 13; /* 13 = 00001101 */

    c = a & b; /* 12 = 00001100 */

    c = a | b; /* 00111101 */

    c = a ^ b; /* 00110001 */

    c = ~a; /*11000011 */c = a > 2; /* 00001111 */

    }

    Binary AND Operator

    Binary OR Operator

    Binary XOR Operator

    Binary Is complement OperatoBinary Left Shift Operator

    Binary Right Shift Operator

  • 8/12/2019 C Programming Overview

    16/41

    Miscellaneous Operators

    sizeof() This operator returns the size of the variable

    & This operator returns the address of the

    variable

    * This operator returns the pointer of the variable

    ? : This operator returns the pointer of the variable

    If Condition is true? Then value X :OtherwisevalueY

  • 8/12/2019 C Programming Overview

    17/41

    What is a pointer?

    int x = 10;

    int *p;

    p = &x;

    pgets the address of xin memory.

    p

    x10

  • 8/12/2019 C Programming Overview

    18/41

    What is a pointer?

    int x = 10;

    int *p = NULL;

    p = &x;

    *p = 20;

    Declares a pointerto an integer

    & is addressoperator

    gets address of x

    * dereferenceoperator

    gets value atp

    Null pointer

  • 8/12/2019 C Programming Overview

    19/41

    What is a pointer?

  • 8/12/2019 C Programming Overview

    20/41

    Generic Pointers

    Pointer variable is declared as type void The pointer does not point to any data

    Can be used when you dont know what type of

    variable the pointer is going to point

    Once the type is known the void pointer need to becasted to that type

    void *ptr; *(int*) ptr;Generic pointer declaration Casting it to refer to an integer type

  • 8/12/2019 C Programming Overview

    21/41

    Pointer to a pointer

    A pointer to a pointer is a form of multipleindirection, or a chain of pointers.

    int **var;

  • 8/12/2019 C Programming Overview

    22/41

    Example code

    #include int main ()

    {

    int var;

    int *ptr;

    int **pptr;

    var = 3000;

    ptr = &var;

    pptr = &ptr;

    printf("Value of var = %d\n", var );

    printf("Value available at *ptr = %d\n", *ptr );printf("Value available at **pptr = %d\n", **pptr);

    return 0;

    }

    What will be the output??

  • 8/12/2019 C Programming Overview

    23/41

    Swapping two numbers (using temp)

    #include

    intmain()

    {

    intx,y,temp;

    printf(Enter x and y\n");

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

    temp =x;

    x =y;

    y=temp;

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

    return0;

    }

  • 8/12/2019 C Programming Overview

    24/41

    Swapping without a temp variable

    #includeintmain()

    {

    intx,y;

    printf(Enter x and y\n");scanf("%d%d",&x,&y);

    x =x+y;

    y =x-y;

    X =x-y;

    printf(After swapping\nx=%d\ny=%d\n",x,y);

    return0;

    }

  • 8/12/2019 C Programming Overview

    25/41

    Swapping using pointers

    #includeintmain()

    {

    intx,y,*a,*b,temp;

    printf(Enter x and y\n");

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

    a= &x; b=&y;

    temp = *b;

    *b = *a;

    *a = temp;printf(After swapping\nx=%d\ny=%d\n",x,y);

    return0;

    }

  • 8/12/2019 C Programming Overview

    26/41

    Swapping using bitwise XOR

    #includeintmain()

    {

    intx,y;

    printf(Enter x and y\n");scanf("%d%d",&x,&y);

    x =x^y;

    y =x^y;

    X =x^y;

    printf(After swapping\nx=%d\ny=%d\n",x,y);

    return0;

    }

  • 8/12/2019 C Programming Overview

    27/41

    Functions

    Function is a group of statements that togetherperform a task.

    Defining a Function

    Function Declarations

    Calling a Function

    /*fn returning the max between two nos */

    int max(int num1, int num2)

    {

    /* local variable declaration */int result;

    if (num1 > num2)

    result = num1;

    else

    result = num2;return result;

    }

    answer = max(a, b);

    N

  • 8/12/2019 C Programming Overview

    28/41

    You are building a ship game and arecurrently located at lat = 32 and lon = -64

    You need to go south east by latitude -1

    and lon +1

    You can write a function to do the above :

    go_south_east()

    N

    S

    W E

    longitude +1

    latitude

    -1

    void go_south_east(int lat, int lon){

    lat = lat - 1;

    lon = lon + 1;

    }

    Small Quiz

  • 8/12/2019 C Programming Overview

    29/41

    #include

    int main(){

    int latitude = 32;

    int longitude = -64;

    go_south_east(latitude, longitude);printf(" Now at: [%d, %d]\n", latitude, longitude);

    return 0;

    }

    void go_south_east(int lat, int lon)

    {lat = lat - 1;

    lon = lon + 1;

    }

    What should print now??

  • 8/12/2019 C Programming Overview

    30/41

    Calling a functionpassing arguments

    Two ways of passing arguments to afunction

    Pass by value

    Pass by reference

    The call by value method of passing arguments to a

    function copies the actual value of an argument into

    the formal parameter of the function.

  • 8/12/2019 C Programming Overview

    31/41

    Calling a functionby reference

    The call by reference method of passing arguments to a function copies the

    address of an argument

    Inside the function, the address is used to access the actual argument used in

    the call

    go_south_east(&latitude, &longitude);

    void go_south_east(int *lat, int *lon)

    {*lat = *lat - 1;

    *lon = *lon + 1;

    }

    &

    *

    * Alld

    iffe

    rent

  • 8/12/2019 C Programming Overview

    32/41

    C - Arrays

    Arraydata structure which can store multiple

    variables of the same type in contiguous memory

    locations

    double balance[5];

    double balance[5] = {10.0, 2.0, 3.4, 17.0, 50.0};

    double balance[] = {10.0, 2.0, 3.4, 17.0, 50.0};

  • 8/12/2019 C Programming Overview

    33/41

    Accessing Arrays

    double salary = balance[3];

    For loops are commonly used to access and initialize the array elements

    int main ()

    {

    int n[ 10 ];

    int i;

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

    {n[ i ] = i + 100;

    }

  • 8/12/2019 C Programming Overview

    34/41

    0 1 2 3

    4 5 6 7

    8 9 10 11

    Two dimension Arrays

    int val =a[2][3];

    int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10,

    11} };

    int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

    int c = a[2][3]

    What will be the value of c?

  • 8/12/2019 C Programming Overview

    35/41

    Pointer to an array

    An array name is a constant pointer to the first element of the array.

    double balance[50]; balanceis a pointer to &balance[0],

    double *p;

    double balance[10];

    p = balance;

    Hence you can do this

    *p and *balance can be used to print balance[0]

    *(p+1) and *(balance +1) can be used to print balance

  • 8/12/2019 C Programming Overview

    36/41

    Array of pointers

    Array of pointersis a array containing addresses

    int var[] = {10, 100, 200};

    int i, *ptr[3];

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

    {

    ptr[i] = &var[i];

    }

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

    {

    printf("Value of var[%d] = %d\n", i, *ptr[i]);

    }

  • 8/12/2019 C Programming Overview

    37/41

    Strings in C

    The string in C programming language is actually a one-dimensionalarray of characters which is terminated by a null character '\0'.

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

    char greeting[] = "Hello";

  • 8/12/2019 C Programming Overview

    38/41

    4 important string functions [string.h]

    strcpy(s1, s2); Copies string s2 into string s1.

    strcat(s1, s2); Concatenates string s2 onto the

    end of string s1.

    strlen(s1); Returns the length of string s1.

    strcmp(s1, s2); Returns 0 if s1 and s2 are the

    same; less than 0 if s1s2.

  • 8/12/2019 C Programming Overview

    39/41

    C Structures

    Arrays allow you to hold multiple data of the same

    kindWhat if you want to hold multiple data of different kinds

    cant do it in an array

    You need to use STRUCTURES or UNIONS !

    What is the difference?

  • 8/12/2019 C Programming Overview

    40/41

    Structure of a structure

    structBooks

    {

    int book_id;

    float price;

    };

    Outside main() Inside main()

    structBooks b1;

    b1. book_id = 101;

    b1. price = 122.50;

    structBooks *ptr;

    ptr = &b1;

    ptr -> book_id = 101;

    ptr -> price = 1225.50;

    int int float float float float

    2 bytes

    4 bytes

    sizeof(b1);

  • 8/12/2019 C Programming Overview

    41/41

    Unions

    Unions differ from structure only in memory organization

    unionBooks

    {

    int book_id;

    float price;

    };

    Outside main() Inside main()

    unionBooks b1;

    b1. book_id = 101;

    b1. price = 122.50;

    sizeof(b1);

    float float float float

    4 bytes