***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Posts

    Friday, November 27, 2020

    Enumeration

    Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which make a program easy to read and maintain.

    The keyword “enum” is used to declare an enumeration.

    The following is the way to define the enum in C:

    enum  flag{integer_const1, integer_const2,.....integter_constN}; 

    In the above declaration, enum named as flag containing 'N' integer constants is defined. The default value of integer_const1 is 0, integer_const2 is 1, and so on.

    If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. 

    Example:

    enum fruits{mango, apple, banana, papaya}; 

    The default value of mango is 0, apple is 1, banana is 2, and papaya is 3.

    To change these default values, then :

    enum fruits{ mango=2, apple=1, banana=5, papaya=7}; 

    Variables of type enum can also be defined. They can be defined in two ways:

    enum  week{Mon, Tue, Wed};

    enum  week  day;

    // Or

    enum  week{Mon, Tue, Wed}day;

     

    An example program to demonstrate working of enum in C

    #include<stdio.h>

     enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

     void main()

    {

        enum  week   day;

        day = Wed;

        printf("%d",day);  

     

    Example 2:

    #include <stdio.h>

    enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday};

     void main()

    {

    printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,wednesday, thursday, friday, saturday);

    }

    Output:

    1  2  5  6  10  11  12

    Note: We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.

    Structure vs Union

    The difference between a structure and a union are: 


    Structure

    Union

    struct keyword is used to define a structure.

    union keyword is used to define a union.

    Every member within structure is assigned a unique memory location.

    In union, a memory location is shared by all the data members.

    It enables you to initialize several members at once.

    It enables you to initialize only the first member of union.

    The total size of the structure is the sum of the size of every data member.

    The total size of the union is the size of the largest data member.

    It is mainly used for storing various data types.

    It is mainly used for storing one of the many data types that are available.

    It occupies space for each and every member written in inner parameters.

    It occupies space for a member having the highest size written in inner parameters.

    Any member can be retrieved at a time.

    One member at a time can be retrieved in the union.

    Union

    Like structure, Union in c language is a user-defined data type that is used to store the different type of elements.

    At once, only one member of the union can occupy the memory. In other words, the size of the union in any instance is equal to the size of its largest element.

    Unions provide an efficient way of using the same memory location for multiple-purpose.

    Defining union

    The union keyword is used to define the union. Let's see the syntax to define union in c.

    union  union_name  

    { 

        data_type member1; 

        data_type member2; 

        . 

        . 

        data_type memeberN; 

    }; 

     

    The example to define union for an employee in c.

    union employee 

    {   int id; 

        char name[50]; 

        float salary; 

    };

     Allocation of memory to a structure and a union example:


    Declaring union variable

     A variable for the union has to be declared to access the member of the union easily.

    There are two ways to declare union variable:

     

    1. By union keyword within main() function
    2. By declaring a variable at the time of defining the union.

     First Method:

     union employee 

        int id; 

        char name[50]; 

        float salary; 

    };

    After defining structure write below code inside the main() function.

    union employee e1, e2; 

    The variables e1 and e2 can be used to access the values stored in the union.

    Second Method:

    union employee 

    {  

        int id; 

        char name[50]; 

        float salary; 

    }e1,e2; 

     

    If number of variables is not fixed, use the first method. It provides the flexibility to declare the union variable as many times as required

    Accessing members of the Union

    There are two ways to access union members:

    1. By . (member or dot operator)
    2. By -> (structure pointer operator)

    A pointer can be created to a union. If a pointer to union is created, members are accessed using arrow ( -> ) operator.

    Example:

    #include <stdio.h> 

    #include <string.h> 

    union employee   

    {   int id;   

        char name[50];   

    }e1;  //declaring e1 variable for union 

    int main( ) 

       //store first employee information 

       e1.id=101; 

       strcpy(e1.name, "Ashraf");//copying string into char array 

       //printing first employee information 

       printf( "employee 1 id : %d\n", e1.id); 

       printf( "employee 1 name : %s\n", e1.name); 

       return 0; 

    }


    Thursday, November 26, 2020

    Array of Structures in C

    An array of structures in C can be defined as the collection of multiple structures variables where each variable contains information about different entities.

    The array of structures in C is used to store information about multiple entities of different data types.

    The array of structures is also known as the collection of structures.


    In the above given example, a structure of employee is defined which contain three members (id , name, salary).

    In the above example emp[2] variable has been declared, which means there is a collection of two employee structures.

     

    Example:

    Example of an array of structures that stores information of 5 students and prints it.

    #include<stdio.h> 

    #include <string.h>   

    struct student{   

    int rollno;   

    char name[10];   

    };   

    void  main(){   

    int i;   

    struct student st[5];   

    printf("Enter Records of 5 students");   

    for(i=0;i<5;i++){   

    printf("\nEnter Rollno:");   

    scanf("%d",&st[i].rollno);   

    printf("\nEnter Name:");   

    scanf("%s",&st[i].name);   

    }   

    printf("\nStudent Information List:");   

    for(i=0;i<5;i++){   

    printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);   

    }       

    }    

    Structure

     A structure is a user defined data type in C. A structure creates a data type that can be used to group items of possibly different types into a single type.

    structure is user defined data type available in C that allows to combine data items of different kinds.

    A structure is a collection of heterogeneous (different) data items into a single type. Each element of a structure is called a member. 

    Defining a Structure

    struct keyword is used to define the structure.

    The syntax to define the structure in c :

    struct structure_name  

        data_type member1; 

        data_type member2; 

        . 

        . 

        data_type memeberN; 

    };

     

    Example:

     struct employee 

    {  

        int id; 

        char name[20]; 

        float salary; 

    }; 

     

    The following image shows the memory allocation of the structure employee that is defined in the above example.


    sizeof(employee) = 4+10+4 bytes = 18 bytes

    Declaring structure variable

    A variable for the structure has to be declared to access the member of the structure easily.

    There are two ways to declare structure variable:


    1. By struct keyword within main() function
    2. By declaring a variable at the time of defining the structure.

    First Method:

     struct employee 

        int id; 

        char name[50]; 

        float salary; 

    };

     After defining structure write below code inside the main() function.

     struct employee e1, e2; 

     The variables e1 and e2 can be used to access the values stored in the structure.

     Second Method:

     struct employee 

    {  

        int id; 

        char name[50]; 

        float salary; 

    }e1,e2; 

    If number of variables is not fixed, use the first method. It provides the flexibility to declare the structure variable as many times as required

    Accessing members of the structure

    There are two ways to access structure members:

    1. By . (member or dot operator)
    2. By -> (structure pointer operator)

    A pointer can be created to a structure. If a pointer to structure is created, members are accessed using arrow ( -> ) operator.

    The code to access the id member of e1 variable by . (dot) operator.

    e1.id

    Example 1:

    #include<stdio.h> 

    #include <string.h>   

    struct employee     

    {   int id;     

        char name[50];     

    }e1;  //declaring e1 variable for structure   

    void  main( )   

    {   

       //store first employee information   

       e1.id=101;   

       strcpy(e1.name, "Ashraf");//copying string into char array   

       //printing first employee information   

       printf( "employee1 id : %d\n", e1.id);   

       printf( "employee1 name : %s\n", e1.name);   

    }  

    Example 2:

    #include<stdio.h>

    struct Point

    {

       int x, y;

    };

    void  main()

    {

       struct Point p1 = {1, 2};

       // p2 is a pointer to structure p1

       struct Point *p2 = &p1;

       // Accessing structure members using structure pointer

       printf("%d %d", p2->x, p2->y);

    }



    DYNAMIC MEMORY ALLOCATION

    Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime.

    C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:

    1. malloc()
    2. calloc()
    3. free()
    4. realloc()

    1. malloc() method

    “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size.

    It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value.

    Syntax:

    ptr = (cast-type*) malloc(byte-size)

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

    Since the size of int is 2 bytes, this statement will allocate 200 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

    2. calloc() method

    “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’.

    Syntax:

    ptr = (cast-type*)calloc(n, element-size);

    ptr = (float*) calloc(25, sizeof(float));

    This statement allocates contiguous space in memory for 25 elements each with the size of the float.

    3. free() method

    “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own.

    Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

    Syntax:

    free(ptr);

    4. realloc() method

    “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.

    If the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

    re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value.

    Syntax:

    ptr = realloc(ptr, newSize);

    where ptr is reallocated with new size 'newSize'.

    Example 1:

    // Program to calculate the sum of n numbers entered by the user

     #include <stdio.h>

    #include <stdlib.h>

    int main()

    {

        int n, i, *ptr, sum = 0;

        printf("Enter number of elements: ");

        scanf("%d", &n);

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

        // if memory cannot be allocated

        if(ptr == NULL)                    

        {

            printf("Error! memory not allocated.");

            exit(0);

        }

        printf("Enter elements: ");

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

        {

            scanf("%d", ptr + i);

            sum += *(ptr + i);

        }

        printf("Sum = %d", sum);

        // deallocating the memory

        free(ptr);

        return 0;

    }

    Example 2:

    / Program to calculate the sum of n numbers entered by the user

    #include <stdio.h>

    #include <stdlib.h>

    int main()

    {

        int n, i, *ptr, sum = 0;

        printf("Enter number of elements: ");

        scanf("%d", &n);

        ptr = (int*) calloc(n, sizeof(int));

        if(ptr == NULL)

        {

            printf("Error! memory not allocated.");

            exit(0);

        }

         printf("Enter elements: ");

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

        {

            scanf("%d", ptr + i);

            sum += *(ptr + i);

        }

        printf("Sum = %d", sum);

        free(ptr);

        return 0;

    }

     

    Example 3: realloc()

    #include <stdio.h>

    #include <stdlib.h>

    int main()

    {

        int *ptr, i , n1, n2;

        printf("Enter size: ");

        scanf("%d", &n1);

        ptr = (int*) malloc(n1 * sizeof(int));

        printf("Addresses of previously allocated memory: ");

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

             printf("%u\n",ptr + i);

        printf("\nEnter the new size: ");

        scanf("%d", &n2);

        // rellocating the memory

        ptr = realloc(ptr, n2 * sizeof(int));

        printf("Addresses of newly allocated memory: ");

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

             printf("%u\n", ptr + i);

         free(ptr);

        return 0;

    }

    Top