Advanced C Programming | Sample
Programs

Home Advanced C Programming | Course Home Advanced C Programming | Sample Programs

Advanced C Programming – Sample Programs

Sample programs is the first step you take to transition from theory to practical. Often showcased in a classroom setting, these programs allow you to witness immediate execution. Complementing this, our mentors offer exercises involving real-time code modification during class. This fill-in-the-blanks approach not only eliminates coding apprehension but also propels you towards becoming a proficient coder. Practice C programming with examples, exercises, and programs for a hands-on learning experience.

Chapter 1 : Basic Refreshers

Brief:

A simple program exploring the basic C data types. C supports two basic
data-types hold integral and real objects as int and float (single precision). The char falls under
the integral category.

 

Source Code:


/*------------------------------------------------------------------------------------------------- 
*   Author         : Emertxe (https://emertxe.com) 
*   Date           : Wed 08 Mar 2016 16:00:04 IST
*   File           : c_t004_ch1_hello_world.c
*   Title          : First C Code
*   Description    : Every programmer would like to get the first code running on a system 
*                    which is written using specific programming language. The below example 
*                    print "hello world" on screen using C Programming Language
*----------------------------------------------------------------------------------------------*/
#include <stdio.h>
int main()
{
    printf("Hello Worldn");
    return 0;
} 

Example output:

Brief:

A simple program allowing the user enter a input from the keyboard and display it on screen.

 

Added:

Source Code:


    /*------------------------------------------------------------------------------------------------- 
    *   Author         : Emertxe (https://emertxe.com) 
    *   Date           : Wed 08 Mar 2016 16:00:04 IST
    *   File           : c_t009_ch1_reading_input.c
    *   Title          : Reading input from the user
    *   Description    : A simple program allowing the user enter a input from the keyboard and 
    *                    display it on screen
    *------------------------------------------------------------------------------------------------*/
    #include <stdio.h>
    int main()
    {
        int number;
        printf("Enter a number: ");
        scanf("%d", &number);
        printf("You entered: %dn", number);
        return 0;
    }
    

Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category.

Added:

Source Code:


/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t010_ch1_datatypes.c
 *   Title          : C basic datatypes
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float (single precision). 
 *                    The char falls under the integral category
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int account_number;
    float ammount;
    char currency;
    account_number = 1024;
    ammount = 100.5;
    currency = '$';
    printf("Mr. Xyz with account number %d owes me %f %cn", account_number, ammount, currency);
    return 0;
}

Example output:

Brief:

The character datatype is generally used to store printable symbol on screen in variable. This program demonstrates that char literals are stored as ascii values. You can note that, the char datatype can be used to store numbers too!! which when printed shows the corresponding ASCII symbol on screen

 

Source Code:

/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t011_ch1_char_datatype.c
 *   Title          : Character datatype handling
 *   Description    : The character datatype is generally used to store printable symbol on screen 
 *                    in variable. This program demonstrates that char literals are stored as ascii 
 *                    values. You can note that, the char datatype can be used to store numbers 
 *                    too!! which when printed shows the corresponding  ASCII symbol on screen.
 *------------------------------------------------------------------------------------------------*/
#include 
int main()
{
    char ch1 = '0';
    char ch2 = 'A';
    char ch3 = 65;
    printf("The character is %c with decimal equivalent %dn", ch1, ch1);
    printf("The character is %c with decimal equivalent %dn", ch2, ch2);
    printf("The character is %c with decimal equivalent %dn", ch3, ch3);
    return 0;
}

Example output:

Brief:

The character datatype is generally used to store printable symbol on screen in variable. This program demonstrates that char literals are stored as ascii values. You can note that, the char datatype can be used to store escape character too!! which when printed shows the corresponding ASCII symbol on screen.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t012_ch2_escape_characters.c
 *   Title          : Character datatype handling
 *   Description    : The character datatype is generally used to store printable symbol on screen 
 *                    in variable. This program demonstrates that char literals are stored as ascii 
 *                    values. You can note that, the char datatype can be used to store escape 
 *                    character too!! which when printed shows the corresponding ASCII symbol on 
 *                    the screen.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    char ch1 = '7'; // Octal 7
    char ch2 = 'x8'; // Hexadecimal 8
    char ch3 = 'xA'; // Hexadecimal A which is equivalent to n
    /* This line should print the values of ch1 and ch2 with a new line */
    printf("ch1 = %d, ch2 = %d%c", ch1, ch2, ch3);
    return 0;
}
Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category. Any variable defined with integral datatypes can be modified for its signedness and width properties. This example demonstrates the width modification

 

Source Code:

/*------------------------------------------------------------------------------------------------
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t013_ch1_type_modifiers.c
 *   Title          : C basic datatypes
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float (single precision). 
 *                    The char falls under the integral category. Any variable defined with integral 
 *                    datatypes can be modified for its signedness and width properties. This 
 *                    example demonstrates the width modification.
 *-----------------------------------------------------------------------------------------------*/
 
#include 
 
int main()
{
     short int count1;
     int long count2;
     short count3;

     /* Let's assume a 32 bit system */
     printf("count1 can now store only %u bytesn", sizeof(count1));
     printf("count2 can now store only %u bytesn", sizeof(count2));
     printf("count3 can now store only %u bytesn", sizeof(count3));
 
     return 0;
}
Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category. Any variable defined with integral datatypes can be modified for its signedness and width properties. This example demonstrates the sign modification.

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t014_ch1_type_modifiers.c
 *   Title          : C basic datatypes
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float(single precision). 
 *                    The char falls under the integral category.Any variable defined with integral 
 *                    datatypes can be modified for its signedness and width properties. This 
 *                    example demonstrates the sign modification.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    char num1;
    unsigned char num2;
    num1 = -1;
    num2 = -1;
    /* Instruct the printf to print the number in decimal for which default is signed */
    printf("num1 = %dn", num1);
    /* Instruct the printf to print the number in unsigned decimal */
    printf("num2 = %un", num2);
    /* The type conversion fundamental come into picture here */
    /* The smaller type get promoted to bigger when opertion happens between them */
    printf("num1 = %dn", num1 & 0xFF);
    printf("num2 = %dn", num2 & 0xFF);
    return 0;
}

Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category. Any variable defined with integral datatypes can be modified for its signedness and width properties. This example demonstrates the storage modification of variable.

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t015_ch1_type_modifiers.c
 *   Title          : C basic datatypes
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float (single precision). 
 *                    The char falls under the integral category. Any variable defined with integral 
 *                    datatypes can be modified for its signedness and width properties. This 
 *                    example demonstrates the storage modification of variable.
 *------------------------------------------------------------------------------------------------*/
#include 
int main()
{
    /* 
    * Request the compiler to provide a CPU register space if available
    * The allocation become auto on failure to get register space
    */ 
    register int i;
    for (i = 0; i < 10; i++)
    {
        puts("hello");
    }
    return 0;
}

Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category. Any variable defined with integral datatypes can be modified for its signedness and width properties. This example demonstrates the storage modification of variable

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t016_ch1_type_modifiers.c
 *   Title          : C basic datatypes
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float (single precision). 
 *                    The char falls under the integral category. Any variable defined with integral 
 *                    datatypes can be modified for its signedness and width properties. This 
 *                    example demonstrates the storage modification of variable.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    /* 
    * Request the compiler to provide a CPU register space if available
    * The allocation become auto on failure to get register space
    */ 
    register int number;
    printf("Enter a number: ");
    /* Cannot access the address of a variable specified with register keyword */
    scanf("%d", &number);
    printf("You entered: %d", number);
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates if condition.

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t017_ch1_if.c
 *   Title          : Flow control statement - if condtion
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates if 
 *                    condition.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    if (number < 5) { printf("number is less than 5n"); } /* The below syntax is to valid since it has only one statement under test condtion */ if (number > 5)
        printf("number is greater than 5n");
    /* Would would be using the below syntax if you have mutli statments under test condtion */
    if (number == 5)
    {
        printf("number is equal to 5n");
        printf("Done. So simple right!!n");
    }
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates if else condition.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t018_ch1_if_else.c
 *   Title          : Flow control statement - if condtion
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates if 
 *                    else condition.
 *-----------------------------------------------------------------------------------------------*/
 
#include 

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    if (number == 5)
    {
        printf("number is equal to 5n");
    }
    else
    {
        printf("number is not equal to 5n");
    }

    return 0;
}

Example output:

 

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates if else if condition.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t019_ch1_if_else_if.c
 *   Title          : Flow control statement - if condtion
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates if 
 *                    else if condition.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    if (number < 5) { printf("number is less than 5n"); } /* Any number of else if conditional check can be done */ else if (number > 5)
    {
        printf("number is greater than 5n");
    }
    /* Not manditory */
    else
    {
        printf("number is equal to 5n");
    }
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

 

Source Code:

/*-----------------------------------------------------------------------------------------------
* Author : Emertxe (https://emertxe.com)
* Date : Wed 08 Mar 2016 16:00:04 IST
* File : c_t020_ch1_switch.c
* Title : Flow control statement - switch statements
* Description : As we all know that a program generally execute in an sequence unless and
* until we have some condition to change the flow of execution. C Programming
* Language supports different flow conditions. This program demonstrates switch
* statements.
*-----------------------------------------------------------------------------------------------*/
#include 
    int main()
    {
    char user_input;
    printf("Enter an alphabet [Please enter lower case]: ");
    scanf("%c", &user_input);
    switch (user_input)
    {
    case 'a':
    printf("%c is an voweln", user_input);
    break;
    case 'e':
    printf("%c is an voweln", user_input);
    break;
    case 'i':
    printf("%c is an voweln", user_input);
    break;
    case 'o':
    printf("%c is an voweln", user_input);
    break;
    case 'u':
    printf("%c is an voweln", user_input);
    break;
    default:
    printf("%c is not a voweln", user_input);
    break;
    }
    printf("Please make sure you check the next examplen");
    return 0;
    }

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

 

Source Code:

/*-------------------------------------------------------------------------------------------------
* Author : Emertxe (https://emertxe.com)
* Date : Wed 08 Mar 2016 16:00:04 IST
* File : c_t022_ch1_switch.c
* Title : Flow control statement - switch statements
* Description : As we all know that a program generally execute in an sequence unless and
* until we have some condition to change the flow of execution. C Programming
* Language supports different flow conditions. This program demonstrates switch
* statements.
*------------------------------------------------------------------------------------------------*/
#include 
    int main()
    {
    char user_input;
    printf("Let me tell you what you typed [Try me]: ");
    scanf("%c", &user_input);
    switch (user_input)
    {
    /* You can provide a range as shown below */
    case 'a' ... 'z':
    printf("You entered a lower case alphabetn");
    break;
    case 'A' ... 'Z':
    printf("You entered an upper case alphabetn");
    break;
    case '0' ... '9':
    printf("You entered a numbern");
    break;
    default:
    printf("Oops :( you caught me!!n");
    break;
    }
    return 0;
    }

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

Source Code:


/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t023_ch1_switch.c
 *   Title          : Flow control statement - switch statements
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates switch 
 *                    statements.
 *------------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int number;
    printf("Please enter a number: ");
    scanf("%d", &number);
    switch (number)
    {
        /* The labels should not contain a variable (i.e a run time expression) */
        case number + 1:
            printf("You entered %fn", number);
            break;
        case number + 2:
            printf("You entered %fn", number);
            break;
        default:
            printf("Try again!!n");
            break;
    }
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

 

Source Code:


/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t024_ch1_switch.c
 *   Title          : Flow control statement - switch statements
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates switch 
 *                    statements.
 *------------------------------------------------------------------------------------------------*/

#include 

int main()
{
    float number;

    printf("Please enter a number: ");
    scanf("%f", &number);

    /* The switch expression should always be an integral expression */
    switch (number)
    {
        /* The labels should always evaluate to integral values */
        case 1.5:
            printf("You entered %fn", number);
            break;
        case 2.5:
            printf("You entered %fn", number);
            break;
        default:
            printf("Try again!!n");
            break;
    }

    return 0;
}
Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

Source Code:

/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t024_ch1_switch.c
 *   Title          : Flow control statement - switch statements
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates switch 
 *                    statements.
 *------------------------------------------------------------------------------------------------*/

#include 

int main()
{
    float number;

    printf("Please enter a number: ");
    scanf("%f", &number);

    /* The switch expression should always be an integral expression */
    switch (number)
    {
        /* The labels should always evaluate to integral values */
        case 1.5:
            printf("You entered %fn", number);
            break;
        case 2.5:
            printf("You entered %fn", number);
            break;
        default:
            printf("Try again!!n");
            break;
    }

    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

 

Source Code:


/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t025_ch1_switch.c
 *   Title          : Flow control statement - switch statements
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates switch 
 *                    statements.
 *------------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int number;

    printf("Please enter a number: ");
    scanf("%d", &number);

    switch (number)
    {
        /* The compiler evaluates this as 11 while compilation and find its as duplicate label */
        case 10 + 1:
            printf("You entered %fn", number);
            break;
        case 11:
            printf("You entered %fn", number);
            break;
        default:
            printf("Try again!!n");
            break;
    }

    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates switch statements.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t026_ch1_switch.c
 *   Title          : Flow control statement - switch statements
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates switch 
 *                    statements.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int number;

    printf("Please enter a number: ");
    scanf("%d", &number);

    switch (number)
    {
        /* The default lable can be put anywhere in the body */
        default:
            printf("Try again!!n");
            /* Make sure you have a break here, else it will lead to fall through */
            break;
        case 10 + 1:
            printf("You entered %fn", number);
            break;
        case 11:
            printf("You entered %fn", number);
            break;
    }

    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates while loop.

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t027_ch1_while.c
 *   Title          : Flow control statement - while loop
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates while 
 *                    loop.
 *-----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int user_input;
    int i = 0;
    printf("Enter an the length of the number series: ");
    scanf("%d", &user_input);
    if (user_input < 1)
    {
        printf("Invalid inputn");
        return 1;
    }
    printf("The series is: ");
    /* The condtion is evaluated before entering the loop */
    while (i < user_input)
    {
        printf("%d ", i++);
    }
    printf("n");
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates do while loop.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t028_ch1_while.c
 *   Title          : Flow control statement - do while loop
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates do 
 *                    while loop.
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int user_input;
    int i = 0;
    printf("Enter an the length of the number series: ");
    scanf("%d", &user_input);
    if (user_input < 1)
    {
        printf("Invalid inputn");
        return 1;
    }
    printf("The series is: ");
    /* The condtion is evaluated after entering the loop */
    do
    {
        printf("%d ", i++);
    } while (i < user_input);
    printf("n");
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates do while vs while loop.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t029_ch1_while.c
 *   Title          : Flow control statement - do while vs while loop
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    do while vs while loop
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    /* 
     * A simple and effective example to understand the difference between 
     * do while and while
     */ 
    do
    {
        printf("I should be seenn");
    } while (0);

    while (0)
    {
        printf("Nope, I should not be seenn");
    }

    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates for loop.

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t030_ch1_while.c
 *   Title          : Flow control statement - for loop
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    for loop.
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int user_input;
    int i = 0;
    printf("Enter an the length of the number series: ");
    scanf("%d", &user_input);
    if (user_input < 1)
    {
        printf("Invalid inputn");
        return 1;
    }
    printf("The series is: ");
    /* 
     * The initialization section is evaluated first and only once
     * The condtion is evaluated next before entering the loop
     * On true condition the loop body is executed and then
     * The post evaluation expression is evaluated followed by condition check
     */
    for (i = 0; i < user_input; i++)
    {
        printf("%d ", i++);
    }
    printf("n");
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates goto statement.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t031_ch1_goto.c
 *   Title          : Flow control statement - goto statement
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    goto statement
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int user_input;
    int i = 0;
    printf("Enter an the length of the number series: ");
    scanf("%d", &user_input);
    if (user_input < 1)
    {
        printf("Invalid inputn");
        return 1;
    }
    printf("The series is: ");
LOOP1:
    if (i != user_input)
    {
        printf("%d ", i++);
        goto LOOP1;
    }
    printf("n");
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates break statement.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t031_ch1_goto.c
 *   Title          : Flow control statement - goto statement
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    goto statement
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int user_input;
    int i = 0;
    printf("Enter an the length of the number series: ");
    scanf("%d", &user_input);
    if (user_input < 1)
    {
        printf("Invalid inputn");
        return 1;
    }
    printf("The series is: ");
LOOP1:
    if (i != user_input)
    {
        printf("%d ", i++);
        goto LOOP1;
    }
    printf("n");
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates break statement.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t033_ch1_break.c
 *   Title          : Flow control statement - break statement
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    break statement
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int i, number;
    printf("Enter a number: ");
    scanf("%d", &number);
    for (i = 0; i < 10; i++)
    {
        if (i == number)
        {
            printf("Number matchedn");
            /* 
             * Breaks the multi itretive loops (for, while and do while) 
             * under which it is stated 
             * One exception is the swtich statement
             */
            break;
        }
    }
    if (i == 10)
    {
        printf("Number not matchedn");
    }
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates continue statement.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t034_ch1_continue.c
 *   Title          : Flow control statement - continue statement
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions.This program demonstrates 
 *                    continue statement
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int i, number;
    int flag = 0;

    printf("Enter a number: ");
    scanf("%d", &number);

    for (i = 0; i < 10; i++)
    {
        if (i != number)
        {

            /* 
             * Continues the multi itretive loops (for, while and do while) 
             * under which it is stated 
             */
            continue;
        }
        printf("Number matchedn");
    }

    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates how NOT to use break and continue statements.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t035_ch1_invalid_break_continue.c
 *   Title          : Flow control statement - Invalid use of break & continue statement
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates how 
 *                    NOT to use break and continue statements.
 *---------------------------------------------------------------------------------------------*/
#include 
int main()
{
    char option;
    int num1 = 10, num2 = 20, sum;
    printf("Enter two numbers to be addedn");
    printf("Number1: ");
    scanf("%d", &num1);
    printf("Number2: ");
    scanf("%d", &num2);
    sum = num1 + num2;
    printf("The result of the expression is %dn", sum);
    printf("Do you want to Exit? [Y - Yes]: ");
    scanf("%c", &option);
    if (option != 'Y')
    {
        /* 
         * Invalid use of break
         * Can appear only inside swtich, while, do while and for loops
         */
        break;
    }
    else
    {
        /* 
         * Invalid use of continue
         * Can appear only inside while, do while and for loops
         */
        continue;
    }
    return 0;
}

Example output:

Brief:

As we all know that a program generally execute in an sequence unless and until we have some condition to change the flow of execution. C Programming Language supports different flow conditions. This program demonstrates nested loops.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe-group.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t036_ch1_nested_loops.c
 *   Title          : Flow control statement - Nested Loops
 *   Description    : As we all know that a program generally execute in an sequence unless and 
 *                    until we have some condition to change the flow of execution. C Programming 
 *                    Language supports different flow conditions. This program demonstrates 
 *                    nested loops
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int i, j;
    int inner_loop_length = 1;
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < inner_loop_length; j++)
        {
            printf("*");
        }
        printf("n");
        inner_loop_length++;
    }
    return 0;
}

Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates the behavior of post and pre increment operators.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t037_ch1_arith_oper_pre_post.c
 *   Title          : Operators - Arithmetic - Pre and Post
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre increment 
 *                    operators.
 *----------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int x = 0;
    int y;
    /* Snippet A */
    y = ++x;
    printf("x = %d, y = %dn", x, y);
    /* Snippet B */
    x = 0;
    y = x++;
    printf("x = %d, y = %dn", x, y);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates the behavior of post and pre increment operators.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t038_ch1_arith_oper_pre_post.c
 *   Title          : Operators - Arithmetic - Pre and Post
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int x = 0;
    /* The value gets incremented but not reflected to x */
    if (x++)
        puts("Yes :)");
    else
        puts("Huh :(");
    printf("x = %dn", x);
    /* The value gets decremented and reflected to x on the same expression */
    if (--x)
        puts("Yes :)");
    else
        puts("Huh :(");
    printf("x = %dn", x);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. When and expression gets evaluated, based on the objects we deal would lead to implicit type conversion. This example demonstrates implicit type promotion.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t039_ch1_type_conversions.c
 *   Title          : Type conversion - Implicit - Promotion
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/
#include 
int main()
{
    unsigned int count1 = 10;
    signed int count2 = -1;
    /* The smaller type get promoted to bigger, when opertion happens between them */
    if (count1 > count2)
    {
        printf("Yesn");
    }
    else
    {
        printf("Non");
    }
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. When and expression gets evaluated, based on the objects we deal would lead to implicit type conversion. This example demonstrates implicit type promotion.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t041_ch1_type_conversions.c
 *   Title          : Type conversion - Explicit - Demotion
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/ 
#include 
int main()
{
    int i;
    int array[5] = {1, 2, 3, 4, 5};
    /* We explicitly demote the unsigned to signed, hence it enters the loop */
    for (i = -1; i < (signed) (sizeof(array) / sizeof(int) - 1); i++)
    {
        printf("%dn", array[i + 1]);
    }
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:

– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. When and expression gets evaluated, based on the objects we deal would lead to implicit type conversion. This example demonstrates explicit type demotion.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t042_ch1_type_conversions.c
 *   Title          : Type conversion - Explicit - Promotion
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/  

#include 

int main()
{
    float celcius, farenheit;

    printf("Enter the farenheit value: ");
    scanf("%f", &farenheit);

    /* Explicit promotion of int to float */
    celcius = ((float) 5 / 9) * (farenheit - 32);

    printf("Farenheit %f is %f Celciusn", farenheit, celcius);

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. When and expression gets evaluated, based on the objects we deal would lead to implicit type conversion. This example demonstrates explicit type promotion.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t042_ch1_type_conversions.c
 *   Title          : Type conversion - Explicit - Promotion
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/  

#include 

int main()
{
    float celcius, farenheit;

    printf("Enter the farenheit value: ");
    scanf("%f", &farenheit);

    /* Explicit promotion of int to float */
    celcius = ((float) 5 / 9) * (farenheit - 32);

    printf("Farenheit %f is %f Celciusn", farenheit, celcius);

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. When and expression gets evaluated, based on the objects we deal would lead to implicit type conversion. This example demonstrates explicit type promotion.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t043_ch1_type_conversions.c
 *   Title          : Type conversion - Sign bit extension
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates the behaviour of post and pre 
 *                    increment operators.
 *---------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    signed char ch1 = -1;
    unsigned char ch2 = 255;
    printf("ch1(signed) = %dn", ch1); // Sign extension happens here
    printf("ch2 = %dn", ch2); // For unsigned numbers 0's are added
    printf("ch1(signed) = %Xn", ch1); // Sign extension happens here
    printf("ch2 = %Xn", ch2); // For unsigned numbers 0's are added
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates an assignment operator and its use with if statement to evaluate TRUE or FALSE.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t044_ch1_true_of_false.c
 *   Title          : Testing of the weight of a variable for TRUE or FALSE
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates an assignment operator and its use 
 *                    with if statement to evaluate TRUE or FALSE.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    int x = 10;

    /*
     * The value 0 is assigned to x here making its weight 0
     * So in C any variable which is non zero is TRUE
     * The below evaluation becomes false leading to else part
     */
    if (x = 0) 
    {
        printf("Hellon");
    }
    else
    {
        printf("Worldn");
    }

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates logical OR operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t045_ch1_logical_oper_or.c
 *   Title          : Operators - Logical - OR
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates logical OR operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int x = 0;
    /* 
     * Any one of the expression has to evaluate to true to enter the loop
     * If the first expression results in true the second won't be evaluted
     */
    if (x++ || x--)
    {
        printf("Yesn");
    }
    else
    {
        printf("Non");
    }
    printf("The value of x is %dn", x);
    return 0;
}

Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates logical AND operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t046_ch1_logical_oper_and.c
 *   Title          : Operators - Logical - AND
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates logical AND operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int x = 0;
    /* 
     * All the expressions has to evaluate to true to enter the loop
     * If the first expression results is false the second would not processed
     */
    if (x++ && x++)
    {
        printf("Yesn");
    }
    else
    {
        printf("Non");
    }
    printf("The value of x is %dn", x);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates logical NOT operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t047_ch1_logical_oper_not.c
 *   Title          : Operators - Logical - NOT
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates logical NOT operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int x = 5;
    /*
     * In C any variable which is non zero is TRUE
     * The below evaluation becomes false leading to else part 
     * since NOT of any non zero value will be always FALSE
     */
    if (!x)
    {
        printf("Hellon");
    }
    else
    {
        printf("Worldn");
    }
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates logical AND and OR operators and its associativity and precedence.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t048_ch1_logical_oper_and_or.c
 *   Title          : Operators - Logical - AND and OR
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates logical AND and OR operators and its
 *                    associativity and precedence.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a = 5, b = 1, c = 10;
    int res;
    /* 
     * The associativity and precedence come into picture here
     * If you check the table you would be seeing the AND has higher precedence.
     * But this doesn't decide the order of evaluation. The precedence is generally 
     * used to group the expression.
     * The below statement make sure that the AND would be done between b and c, but
     * the evaluation would start from left to right.
     * Hence only a would be incremented and is already true, will assign the result
     * to res and procced downwards without evaluating b and c
     */ 
    res = ++a || ++b && ++c;
    printf("a = %d, b = %d, c = %dn", a, b, c);
    printf("res = %dn", res);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates an operator precedence.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t049_ch1_oper_precedence.c
 *   Title          : Operators - Precedence
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates an operator precedence.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int p = 10, q = 20, r;
    /*
     * An intresting expresion which assigns the result of the logical operation
     * result in p and r even though they are assigned with 5!!. why??
     * Again the precedence of < is greater than ||, is greater than =. Hence the grouping
     * would be like (p = q = (5 || (q < 20))
     */ 
    if (p = r = 5 || q < 20)
    {
        printf("p = %d, q = %d, r = %dn", p, q, r);
    }
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates an assignment operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t050_ch1_assignemnt_oper.c
 *   Title          : Operators - Assignment
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates an assignment operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a = 1, c = 1, e = 1;
    float b = 1.5, d = 1.5, f = 1.5;
    /* 
     * The below expression starts from right to left
     * The type conversion fundametals to be kept in mind
     */ 
    a += b += c += d += e += f;
    printf("a = %d, b = %f, c = %d, d = %f, e = %d, f = %fn", a, b, c, d, e, f);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates greater and less than operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t051_ch1_relational_oper.c
 *   Title          : Operators - Relational - Less and Greater than
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates greater and less than operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a = 10, b = 5, c = 20;
    if ((a > b) && (b < c))
    {
        puts("Yes");
    }
    else
    {
        puts("No");
    }
    return 0;
}

Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates equal to operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t052_ch1_relational_oper.c
 *   Title          : Operators - Relational - Equal to
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates equal to operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    float val = 0.7;
    /* 
     * The result ends up if false, since the real constants are stored as double precision
     * but the variable val is float
     */
    if (val == 0.7)
    {
        puts("Equal");
    }
    else
    {
        puts("Not Equal");
    }
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. This example demonstrates not equal to operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t053_ch1_relational_oper.c
 *   Title          : Operators - Relational - Not equal to
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. This example demonstrates not equal to operator.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    float val = 0.7;

    /* 
     * The result ends up if false, since the real constants are stored as double precision
     * but its explicitly type casted as float which is equal to val, but the check is not
     * equal to
     */
    if (val != (float) 0.7)
    {
        puts("Not Equal");
    }
    else
    {
        puts("Equal");
    }

    return 0;
}


Example output:

 

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Bitwise operators most commonly used in embedded application development. This example demonstrates bitwise all bitwise operators.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t054_ch1_bitwise_oper.c
 *   Title          : Operators - Bitwise
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Bitwise operators most commonly used in embedded application
 *                    development. This example demonstrates bitwise all bitwise operators.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    /* An expression to clear a single bit at postion 0 */
    printf("%hhxn", 0xFF & 0xFE);
    /* An expression to set a single bit at postion 0 */
    printf("%hhxn", 0x00 | 0x01);
    /* An expression to toggle a single bit at postion 0 */
    printf("%hhxn", 0x01 ^ 0x01);
    /* An expression to left shift the value by one bit poistion */
    printf("%hhxn", 0xFF << 0x01); /* * An expression to right shift the value by one bit poistion * Note: The result would depend on the signed bit in case signed objects */ printf("%hhxn", 0xFF >> 0x01);
    /* An expression to 1's compliments the value */
    printf("%hhxn", ~0x00);
    printf("Please so see the next examples for simple appilcations of bitwise operatorn");
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Bitwise operators most commonly used in embedded application development. This example demonstrates usage of bitwise operators for clearing, setting, toggling and getting the bits from a object.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t055_ch1_bitwise_oper_bit_ops.c
 *   Title          : Operators - Bitwise
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Bitwise operators most commonly used in embedded application
 *                    development. This example demonstrates usage of bitwise operators for 
 *                    clearing, setting, toggling and getting the bits from a object.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    int data;
    int bit_mask;
    int bit_position;

    /*
     * Clear a bit a given position
     */ 
    printf("Enter a bit postion to be operted on 0XFF [Poition ranges from 0 to 7]: ");
    scanf("%d", &bit_position);

    if ((bit_position < 1) && (bit_position > 7))
    {
        printf("Bit position not yet supportedn");

        return 1;
    }

    /* Creation of a mask to clear at bit_position */
    data = 0xFF;
    bit_mask = ~(1 << bit_position);
    /* Clear the required bit */
    data = data & bit_mask;

    printf("Data [0XFF] after clearing the bit %d is %#hhXn", bit_position, data);

    /*
     * Set a bit a given position
     */ 
    printf("Enter a bit postion to be set in 0X00 [Poition ranges from 0 to 7]: ");
    scanf("%d", &bit_position);

    /* Creation of a mask to clear at bit_position */
    data = 0x00;
    bit_mask =  1 << bit_position;
    /* Clear the required bit */
    data = data | bit_mask;

    printf("Data [0X00] after setting the bit %d is %#hhXn", bit_position, data);

    /*
     * Toggle a bit a given position
     */ 
    printf("Enter a bit postion to be toggled in 0XAA [Poition ranges from 0 to 7]: ");
    scanf("%d", &bit_position);

    /* Creation of a mask to clear at bit_position */
    data = 0xAA;
    bit_mask =  1 << bit_position;
    /* Clear the required bit */
    data = data ^ bit_mask;

    printf("Data [0XAA] after toggling the bit %d is %#hhXn", bit_position, data);

    /*
     * Get a bit a given position
     */ 
    printf("Enter a bit postion to get from 0XAA [Poition ranges from 0 to 7]: ");
    scanf("%d", &bit_position);

    /* Creation of a mask to get a at bit_position */
    data = 0xAA;
    bit_mask =  1 << bit_position;

    /* Get the required bit */
    printf("The bit at position %d from Data [0XAA] is %dn", bit_position, !!(data & bit_mask));

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Bitwise operators most commonly used in embedded application development. This example demonstrates usage of the shift operators to swap nibbles of byte.

 

Source Code:


/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t056_ch1_bitwise_oper_bit_ops.c
 *   Title          : Operators - Bitwise
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Bitwise operators most commonly used in embedded application
 *                    development. This example demonstrates usage of the shift operators to swap
 *                    nibbles of byte.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    signed char num = 0xAB;

    /* Swap higher nibble with lower nibble */
    num = ((num >> 4) & 0x0F) | ((num << 4) & 0xF0);

    /* Mask 8 bits */
    printf("num = %Xn", num & 0xFF);

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Bitwise operators most commonly used in embedded application development. This example demonstrates usage of the shift operators and its behavior while shifting signed and unsigned numbers.

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t057_ch1_bitwise_oper_bit_ops.c
 *   Title          : Operators - Bitwise
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Bitwise operators most commonly used in embedded application
 *                    development. This example demonstrates usage of the shift operators and its
 *                    behaviour while shifting signed and unsigned numbers.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    signed int x = -1;
    unsigned int y = -1;

    /* The sign bit is 1 and would propagate while shifting */
    x = x >> 4;
    printf("Right shift of signed x by 4 = %Xn", x);

    x = x << 4; printf("Left shift of signed x by 4 = %Xn", x); /* The no sign bit, so 0 would propagate while shifting */ y = y >> 4;
    printf("Right shift of unsigned y by 4 = %Xn", y);

    y = y << 4;
    printf("Left shift of unsigned y by 4 = %Xn", y);

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value

Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. sizeof is a compile time operator. Very useful if you need to know the size of memory allocated for a defined object. This example shows the size of the different data types. Note this is implementation specific and would vary from architecture to architecture.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t058_ch1_sizeof_oper.c
 *   Title          : Operators - sizeof
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. sizeof is a compile time operator. Very useful if you need to know
 *                    the size of memory allocated for a defined object. This example shows the 
 *                    size of the different data types. Note this is implementation specific and 
 *                    would vary from architecture to architecture.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    /* 
     * sizeof is a compile time operator.
     * The return value depends on the compiler implementation and could vary
     * in different target architectures.
     * The below code was run on 32 bit gcc fo x86 architectures
     */
    printf("sizeof(char)tt: %u Bytesn", sizeof(char));
    printf("sizeof(short)tt: %u Bytesn", sizeof(short));
    printf("sizeof(int)tt: %u Bytesn", sizeof(int));
    printf("sizeof(long)tt: %u Bytesn", sizeof(long));
    printf("sizeof(long long)t: %u Bytesn", sizeof(long long));
    printf("sizeof(float)tt: %u Bytesn", sizeof(float));
    printf("sizeof(double)tt: %d Bytesn", sizeof(double));
    printf("sizeof(long double)t: %u Bytesn", sizeof(long double));
    printf("sizeof(pointer)tt: %u Bytesn", sizeof(short *));
    printf("sizeof(void)tt: %u Bytesn", sizeof(void));
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands

Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. sizeof is a compile time operator. Very useful if you need to know the size of memory allocated for a defined object. This example shows the size of the different data types. Note this is implementation specific and would vary from architecture to architecture.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t059_ch1_sizeof_oper.c
 *   Title          : Operators - sizeof
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. sizeof is a compile time operator. Very useful if you need to know
 *                    the size of memory allocated for a defined object. This example shows the 
 *                    size of the different data types. Note this is implementation specific and 
 *                    would vary from architecture to architecture.
 *-------------------------------------------------------------------------------------------*/   

#include 

int main()
{
    int num = 1;

    /* 
     * sizeof is a compile time operator.
     * The return value depends on the compiler implementation and could vary
     * in different target architectures.
     * The below code was run on 32 bit gcc fo x86 architectures
     * The parentheses are must if you have to find the size of datatype
     * size of returns a unsigned value
     */
    printf("%zu %zu %zun", sizeof(int), sizeof num, sizeof 1);

    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things: Added: – Operates on its operands

Added: – Returns a value Added: Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. sizeof is a compile time operator. Very useful if you need to know the size of memory allocated for a defined object. This example shows the size of the different data types. Note this is implementation specific and would vary from architecture to architecture.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t060_ch1_sizeof_oper.c
 *   Title          : Operators - sizeof
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. sizeof is a compile time operator. Very useful if you need to know
 *                    the size of memory allocated for a defined object. This example shows the 
 *                    size of the different data types. Note this is implementation specific and 
 *                    would vary from architecture to architecture.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int i = 0;
    /* 
     * sizeof is a compile time operator.
     * So the any expression which is an argument of will only be evaluated only at
     * compilation time. The code for such expression would not generated by compiler.
     */
    int j = sizeof(++i);
    printf("%d: %dn", i, j);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Comma depending on the context acts a operator and separator. In case of list of declarator, list of initializers and list of arguments its acts seperator. In rest of the cases it acts an operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t061_ch1_comma_oper.c
 *   Title          : Operators - Comma
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Comma depending on the context acts a operator and separator. In 
 *                    case of list of declarator, list of initializers and list of arguments its 
 *                    acts seperator. In rest of the cases it acts an operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int x;
    int y, z;
    /* The comma operator has the least precedence hence 5 would be assigned to x */
    x = 5, 10, 15;
    printf("%dn", x);
    /* 
     * The values are grouped with a parentheses, hence the parentheses would be evaluated first.
     * Now based on the associavity 15 would be assigned to x
     */ 
    x = (5, 10, 15);
    printf("%dn", x);
    /* 
     * The values are grouped with a parentheses, hence the parentheses would be evaluated first.
     * Now based on the associavity, y would be 100 and then z becomes 110 leading x to 110
     */ 
    x = (y = 100, z = y + 10);
    printf("x = %d, y = %d, z = %dn", x, y, z);
    return 0;
}

Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Comma depending on the context acts a operator and separator. In case of list of declarator, list of initializers and list of arguments its acts seperator. In rest of the cases it acts an operator.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t062_ch1_comma_oper.c
 *   Title          : Operators - Comma
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Comma depending on the context acts a operator and separator. In 
 *                    case of list of declarator, list of initializers and list of arguments its 
 *                    acts seperator. In rest of the cases it acts an operator.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int i = 0, j = 0;
    j = i++ ? i++ : ++i;
    printf("i = %d, j = %dn", i, j);
    j = i++ ? i++, ++j : ++j, i++;
    printf("i = %d, j = %dn", i, j);
    return 0;
}


Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Ternary operator to test a condition (hence called as conditional operator) and return expressions as true or false.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t063_ch1_ternary_oper_max.c
 *   Title          : Operators - Ternary
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Ternary operator to test a condition (hence called as conditional
 *                    operator) and return expressions as true or false
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a, b;
    int max;
    a = 100, b = 10;
    /* Test for a > b, on true it would return a else b */
    max = (a > b) ? a : b;
    printf("Max = %dn", max);
    a = 10, b = 100;
    (a > b) ? (max = a) : (max = b);
    printf("Max = %dn", max);
    a = 10, b = 10;
    (a > b) ? printf("Max = %dn", a): printf("Max = %dn", b);
    a = 1, b = 200;
    printf("Largest = %dn", (a > b) ? a : b);
    return 0;
}

Example output:

Brief:

Symbols that instructs the compiler to perform specific arithmetic or logical operation on operands All C operators do 2 things:
– Operates on its operands
– Returns a value
Operators play a very crucial role in controlling the system behavior in general. There are different types of Operators available in C Programming Language. Ternary operator to test a condition (hence called as conditional operator) and return expressions as true or false.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t064_ch1_ternary_oper_abs_val.c
 *   Title          : Operators - Ternary
 *   Description    : Symbols that instructs the compiler to perform specific arithmetic or 
 *                    logical operation on operands. All C operators do 2 things
 *                     - Operates on its operands
 *                     - Returns a value
 *                    Operators play a very crucial role in controlling the system behaviour in 
 *                    general. There are different types of Operators available in C Programming 
 *                    Language. Ternary operator to test a condition (hence called as conditional
 *                    operator) and return expressions as true or false
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int x = -10;
    unsigned int abs_val;
    abs_val = (x > 0) ? x : -x;
    printf("Absolute val = %un", abs_val);
    return 0;
}


Example output:

Brief:

A simple program exploring the basic C data types. C supports two basic datatypes hold integral and real objects as int and float (single precision). The char falls under the integral category. Any variable can be qualified for non mutability, hence cannot be changed.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t065_ch_qualifier_const.c
 *   Title          : C basic datatypes - Const Qualifier
 *   Description    : A simple program exploring the basic C data types. C supports two basic 
 *                    datatypes hold integral and real objects as int and float (single 
 *                    precision). The char falls under the integral category. Any variable 
 *                    can be qualified for non mutability, hence cannot be changed.
 *-------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    const int num1;
    /* Not allowed to change */
    num1 = 10;
    if (num1 == 10)
    {
        printf("Yesn");
    }
    /* Only way to assign a value to const variable */
    const int num2 = 10;
    /* Not allowed to change */
    if (num2++ == 10)
    {
        printf("Yesn");
    }
    return 0;
}


Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example show how to define, store and print an array.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t066_ch1_array.c
 *   Title          : C User Defiened Datatype - Arrays
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example show how 
 *                    to define, store and print an array.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a[5];
    int i;
    /* Store values in array */
    for (i = 0; i < 5; i++)
    {
        a[i] = i + 1;
    }
    /* Print array */
    for (i = 0; i < 5; i++)
    {
        printf("The element at index %d is %dn", i, a[i]);
    }
}


Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example show how to get the input from the user and store in a defined array.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t067_ch1_array.c
 *   Title          : C User Defiened Datatype - Arrays - Reading from user
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example show how 
 *                    to get the input from the user and store in a defined array.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a[5];
    int i;
    printf("Enter 5 numbers: ");
    for (i = 0; i < 5; i++)
    {
        /* Read and store values entered by the user in array at index i */
        scanf("%d", &a[i]);
    }
    /* Print scaned array elements */
    for (i = 0; i < 5; i++)
    {
        printf("The element at index %d is %dn", i, a[i]);
    }
}


Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example show illeagle access of the array elements (out of bound).

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t068_ch1_array_boundary.c
 *   Title          : C User Defiened Datatype - Arrays - Out of bound
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example show 
 *                    illeagle access of the array elements (out of bound).
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    /* 
     * Lets define 3 array variables x, y, z where each can store 2 elements
     * Assuming the memory allocated for each array is contigous
     */ 
    int x[2] = {1, 2};
    int y[2];
    int z[2] = {3, 4};
    int i;
    printf("Enter the elements for y[]n");
    for (i = 0; i < 3; i++)
    {
        scanf("%d", &y[i]);
        /* 
         * Note that the array y is defined to store only 2 elements, but the loop run
         * from 0 to 2 which is 3 elements!
         * So the adjacent of y is array z, so expecting z[0] gets changed to the last
         * user input
         */ 
    }
    /* Based on the above assumption we are now modifing the 1st element of the x i.e. x[1] */
    y[-1] = 10;
    printf("Values of x[] are:n");
    for (i = 0; i < 2; i++)
    {
        printf("%d ", x[i]);
    }
    printf("n");
    printf("Values of z[] are:n");
    for (i = 0; i < 2; i++)
    {
        printf("%d ", z[i]);
    }
    printf("n");
    printf("Please make sure to check the next examplen");
    return 0;
}

Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example show illeagle access of the array elements (out of bound) which could lead to segmentation fault.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t069_ch1_array_boundary.c
 *   Title          : C User Defiened Datatype - Arrays - Out of bound
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example show 
 *                    illeagle access of the array elements (out of bound) which could lead to 
 *                    segmentation fault.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a[5], i;
    /* 
     * The array is defined for just 5 elements.
     * Moreover we are trying to access 50 elements from 5000 to 5050
     * which could certinly lead to a segmentation fault
     */ 
    for (i = 5000; i <= 5050; i++)
    {
        printf("%dn", a[i]);
    }
    return 0;
}

Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example shows array initialization while definition and how address is allocated for each element of an array.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t070_ch1_array_element_address.c
 *   Title          : C User Defiened Datatype - Arrays - Element addresses
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example shows 
 *                    array initialization while definition and how address is allocated for 
 *                    each element of an array.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    /* On a 32 bit system size of int would be 4 bytes width */
    int arr1[3] = {1, 2, 3};
    /* On a 32 bit system size of short would be 2 bytes width */
    short arr2[3] = {1, 2, 3};
    /* On a 32 bit system size of char would be 1 bytes width */
    char arr3[3] = {'A', 'B', 'C'};
    int i;
    for (i = 0; i < 3; i++)
    {
        printf("Element %d at arr1[%d] is at %pn", i, i, &arr1[i]);
    }
    for (i = 0; i < 3; i++)
    {
        printf("Element %d at arr2[%d] is at %pn", i, i, &arr2[i]);
    }
    for (i = 0; i < 3; i++)
    {
        printf("Element %d at arr3[%d] is at %pn", i, i, &arr3[i]);
    }
    return 0;
}

Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example shows that the array cannot be copied by direct assignment.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t071_ch1_array_copy.c
 *   Title          : C User Defiened Datatype - Arrays - Copy
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example shows 
 *                    that the array cannot be copied by direct assignment.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a[5] = {1, 2, 3, 4, 5};
    int b[5];
    int i;
    /* 
     * Will a get copied to b!!?
     */
    b = a;
    /* 
     * No, not possible. The array name represents a base address of an array which is
     * a constant, so since we cannot modify a constant object the copiler will issue an
     * error.
     */ 
    /* Print array b */
    for (i = 0; i < 5; i++)
    {
        printf("%d ", b[i]);
    }
}


Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example shows how to copy an array.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t072_ch1_array_copy.c
 *   Title          : C User Defiened Datatype - Arrays - Copy
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example shows how 
 *                    to copy an array.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    int a[5] = {1, 2, 3, 4, 5};
    int b[5];
    int i;
    /* Copy a to b, element by element */
    for (i = 0; i < 5; i++)
    {
        b[i] = a[i];
    }
    /* Print array b */
    for (i = 0; i < 5; i++)
    {
        printf("%d ", b[i]);
    }
    printf("n");
    return 0;
}


Example output:

Brief:

An array is a collection of similar data type Elements occupy consecutive memory locations (addresses) First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. This example shows how to initialize an array.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t073_ch1_array_copy.c
 *   Title          : C User Defiened Datatype - Arrays - Initialization
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the 
 *                    last element with highest address. Elements are indexed from 0 to 
 *                    SIZE – 1. for example say we have an array of 5 elements(say array[5]) 
 *                    will be indexed from 0 to 4. Accessing out of range array elements would 
 *                    be “illegal access”, i.e for example do not access elements array[-1] and 
 *                    array[SIZE]. Array size can't be altered at run time.This example shows 
 *                    how to copy an array.
 *--------------------------------------------------------------------------------------------*/   
#include 
int main()
{
    /* Perfectly fine */
    int a[5] = {1, 2, 3, 4, 5};
    /* Perfectly fine, elements 2, 3 and 4 will be uninitilized */
    int b[5] = {6, 7};
    /* Perfectly fine, all elements will be uninitilized */
    int c[5];
    /* No, atleast gcc doesn't allow this, will lead to compiler error*/
    int d[];
    int size = 5;
    /* No not allowed, a variable size array cannot be initialized */
    int e[size] = {1, 2, 3, 4, 5};
    return 0;
}


Example output:

Chapter 2 : Functions Part 1

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This code shows how to write a function using C.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t074_ch2_function_basics.c
 *   Title          : Functions Basics - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Re usability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *					          This code shows how to write a function using C
 *-----------------------------------------------------------------------------------------*/

#include 

/* Function definition to accept 2 numbers from the user and display the sum of them */
void add()
{
	int num1, num2;
	int sum;

	printf("Enter two numbers: ");
	scanf("%d%d", &num1, &num2);

	sum = num1 + num2;

	printf("The sum is %dn", sum);
}

int main()
{
	/* Function call for addition */
	add();

    return 0;
}


Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This code shows how to write a function using C accepting arguments.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t075_ch2_function_args.c
 *   Title          : Functions Basics - Arguments
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This code shows how to write a function using C accepting arguments.
 *-----------------------------------------------------------------------------------------*/

#include 

/* 
 * Function definition to accept 2 numbers from the caller and display the sum of them
 * Whatever we write in the parentheses is / are called as formal argument(s)
 */
void add(int num1, int num2)
{
	int sum;

	sum = num1 + num2;

	printf("The sum is %dn", sum);
}

int main()
{
	int num1, num2;

	printf("Enter two numbers: ");
	scanf("%d%d", &num1, &num2);

	/* 
	 * Function call to accept 2 numbers from the user and display the sum of them
	 * Whatever we write in the parentheses is / are called as actual argument(s)
	 */
	add(num1, num2);

    return 0;
}


Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This code shows how to write a function using C accepting arguments and returning a value to the caller.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t076_ch2_function_args_and_return.c
 *   Title          : Functions Basics - Arguments and Return
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This code shows how to write a function using C accepting arguments and 
 *                    returning a value to the caller.
 *------------------------------------------------------------------------------------------*/  

#include 

/* 
 * Function definition to accept 2 numbers from the caller and display the sum of them
 * Whatever we write in the parentheses is / are called as formal argument(s)
 * The return data type of the function is integer. Make sure the returned objects datatype
 * matches the return datatype
 */
int add(int num1, int num2)
{
	int sum;

	sum = num1 + num2;

	/* Return the computed value to the caller */
	return sum;
}

int main()
{
	int num1, num2;
	int sum;

	printf("Enter two numbers: ");
	scanf("%d%d", &num1, &num2);

	/* 
	 * Function call to accept 2 numbers from the user and display the sum of them
	 * Whatever we write in the parentheses is / are called as actual argument(s)
	 */
	sum = add(num1, num2);

	printf("The sum is %dn", sum);

    return 0;
}


Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This code shows how to write a function using C accepting arguments and retuning a value to the caller. The caller can ignore the return value if required.

 

Source Code:

/*--------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t077_ch2_function_ignore_return.c
 *   Title          : Functions Basics - Ignoring the return value
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This code shows how to write a function using C accepting arguments and 
 *                    retuning a value to the caller. The caller can ignore the return value 
 *                    if required.
 *------------------------------------------------------------------------------------------*/  

#include 

/* 
 * Function definition to accept 2 numbers from the caller and display the sum of them
 * Whatever we write in the parentheses is / are called as formal argument(s)
 * The return data type of the function is integer. Make sure the returned objects datatype
 * matches the return datatype
 */
int add(int num1, int num2)
{
	int sum;

	sum = num1 + num2;

	/* Return the computed value to the caller */
	return sum;
}

int main()
{
	int num1, num2;
	int sum = 0;

	printf("Enter two numbers: ");
	scanf("%d%d", &num1, &num2);

	/* 
	 * Add funtion is called and its return value is ignored.
	 */
	add(num1, num2);

	printf("The sum is %dn", sum);

    return 0;
}

Example output:

Chapter 3 : Pointers Part 1

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows how to define and use a pointer.

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t078_ch3_pointers.c
 *   Title          : Pointer Basics - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    shows how to define and use a pointer
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 5;
    /* ptr is a pointer which will be pointing to an integer */
    int *ptr;

    /* 
    * As mentioned above the pointer should hold an address of an memory.
    * Now since this code is going to run in OS, we cannot store any random address
    * in it. So we have to define an variable and let the OS to allocate a memory for it.
    * An address of an variable is obtained by the & operator (called as referencing
    * operator)
    * Storing the address of x in ptr (So made it to point to x now)
    */
    ptr = &x; 

    /* Print the address of x */
    printf("&x = %pn", &x);
    /* 
    * Print the value of ptr. Yes you read it right. The address of x is stored
    * as value in ptr
    * And obviously ptr too, would have its own address which can be requested with &
    * as shown below in line 45
    */
    printf("ptr = %pn", ptr);

    /* Print the address of ptr */
    printf("&ptr = %pn", &ptr);

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows how to define and use a pointer and how to access (dereference) a value pointed by a pointer.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t079_ch3_pointers.c
 *   Title          : Pointer Basics - Example 2
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    shows how to define and use a pointer and how to access (dereference) a 
 *                    value pointed by a pointer.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 5;
    /* ptr is a pointer which will be pointing to an integer */
    int *ptr;

    /* 
    * As mentioned above the pointer should hold an address of an memory.
    * Now since this code is going to run in OS, we cannot store any random address
    * in it. So we have to define an variable and let the OS to allocate a memory for it.
    * An address of an variable is obtained by the & operator (called as referencing operator)
    * Storing the address of x in ptr (So made it to point to x now)
    */
    ptr = &x; 

    /* Print the value of x */
    printf("x = %dn", x);

    /*
    * Now to print the value at address held by the pointer, we need to use the
    * Dereferencing operator * ( Please don't get confused with * of comment ;) )
    */
    printf("Value at address pointed by ptr = %dn", *ptr);

    return 0;
}

Example output:

 

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows how to define and use a pointer and how to access (dereference) a value pointed by a pointer.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t080_ch3_pointers.c
 *   Title          : Pointer Basics - Example 3
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    shows how to define and use a pointer and how to access (dereference) a 
 *                    value pointed by a pointer.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 5;
    /* ptr is a pointer which will be pointing to an integer */
    int *ptr;

    /* 
    * As mentioned above, the pointer should hold an address of an memory.
    * Now since this code is going to run in OS, we cannot store any random address
    * in it. So we have to define an variable and let the OS to allocate a memory for it.
    * An address of an variable is obtained by the & operator (called as referencing operator)
    * Storing the address of x in ptr (So made it to point to x now)
    */
    ptr = &x; 

    /* Print the value of x using direct and indirect addressing */
    printf("x = %dn", x);
    printf("Value at address pointed by ptr = %dn", *ptr);

    /* Modify the value at address pointed by ptr */
	  *ptr = 20;

    /* The value of x will be changed to 20 */
    printf("x = %dn", x);

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows that the pointer is a variable which stores an integer value (i.e the address).

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t081_ch3_pointer_is_an_int.c
 *   Title          : Pointer Basics - Pointer is an integer
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    shows that the pointer is a variable which stores an integer value 
 *                    (i.e the address).
 *-------------------------------------------------------------------------------------------*/
#include 
int main()
{
    int num;
    int *ptr;
    /* Store a value in a integer variable */
    num = 5;
    /* Store a value in a pointer variable */
    ptr = 5;
    /*
    * There is no difference in both the above statements, They just hold integer numbers!.
    * On this sense pointers always integral values (Address can never be real number, at least not
    * in computers ;) )
    * But most important point is that, the width of the address could be bigger that it might not fit
    * in a variable of type int!!
    * Width of the address depends on the addressing capability of the system.
    */
    printf("num = %dn", num);
    printf("ptr = %dn", ptr);
    /* Check for exception (Size might differ) */
    printf("sizeof int = %un", sizeof(int));
    printf("sizeof long = %un", sizeof(long));
    printf("sizeof pointer = %un", sizeof(int *));
    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows why the types attached to pointer when they always hold integral values as seen in the previous example.

 

Source Code:

/*--------------------------------------------------------------------------------------------
 *   Author         : Emertxe (https://www.emertxe.com)
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t082_ch3_pointer_types.c
 *   Title          : Pointer Basics - Why types to Pointers?
 *   Description    : The C basic data types allows us to access a limited and fixed number of
 *                    the memory bytes. In order to increase the flexibility to access a range
 *                    of memory bytes C supports pointers. Any variable defined as a pointer
 *                    will hold an address of memory location. Have to be careful with dealing
 *                    the address ranges, else would lead to illegal memory access. This example
 *                    shows why the types attached to pointer when they always hold integral
 *                    values as seen in the previous example.
 *-------------------------------------------------------------------------------------------*/
#include 
int main()
{
    double d = 2.5;
    char ch = 'A';
    int *iptr;
    char *cptr;
    double *dptr;
    printf("Sizeof *iptr = %un", sizeof(*iptr));
    printf("Sizeof *cptr = %un", sizeof(*cptr));
    printf("Sizeof *dptr = %un", sizeof(*dptr));
    /* Store address of char ch */
    cptr = &ch;
    /* Store address of double d  */
    dptr = &d;
    /* De-reference char pointer (fetches a char - 1 byte) */
    printf("*cptr = %cn", *cptr);
    /* De-reference double pointer (fetches a double - 8 bytes) */
    printf("*dptr = %fn", *dptr);
    /*
    * From the above statements we can conclude the types to pointers are
    * required to access the value pointed by the pointer, without which
    * it would not know how many bytes to read or write from / to the location
    * it is pointing to.
    */
	return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows all the pointers size remains the same as address bus size.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t083_ch3_pointer_size.c
 *   Title          : Pointer Basics - Why types to Pointers?
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    shows all the pointers size remains the same as address bus size.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
	char *cptr;
	int *iptr;

	if (sizeof(cptr) == sizeof(iptr))
	{
		printf("Size of all pointers are equaln");
	}
	else
	{
		printf("No they are not equaln");
	}

	if (sizeof(char *) == sizeof(long long *))
	{
		printf("Size of all pointers are equaln");
	}
	else
	{
		printf("No they are not equaln");
	}

	return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example shows what happens if cross access different pointers types.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t084_ch3_pointer_types.c
 *   Title          : Pointer Basics - Cross accessing different pointer types
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example
 *                    shows what happens if cross access different pointers types.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int num = 0x12345678;
    int *ptr = #
    char *cptr = (char *)#

    int int_val;
    char char_val;

    int_val = *ptr;
    char_val = *cptr;

    printf("*ptr = %x, int_val = %xn", *ptr, int_val);
    printf("*cptr = %x, char_val = %xn", *cptr, char_val);

    *cptr = 0x55;
    printf("*cptr = %x, char_val = %xn", *cptr & 0xFF, char_val);
    printf("*ptr = %x, int_val = %xn", *ptr, int_val);

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates the different interpretation of an array by the compiler.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t201_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Stringification - Example 1
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be converted into a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define WARN_IF(EXP)								
do													
{													
	x--;											
	if (EXP)										
	{												
		fprintf(stderr, "Warning: " #EXP "n");		
	}												
} while (x)

int main()
{
	int x = 5;

	WARN_IF (x == 0);

	return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates arithmetic operations on pointers.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t202_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Stringification - Example 2
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be converted into a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define PRINT(expr) printf(#expr " is %dn", expr)

int main()
{
    int x, y = 5, z = 10, a = 50, b = 12, c = 100;

    PRINT(x = y + c * (a / z) % y);

	return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates arithmetic operations on pointers.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t203_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Concatination
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be used to concatinated.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define CAT(x) (x##_val)

int main()
{
	int int_val = 4;
	float float_val = 2.54;

	printf("int val = %dn", CAT(int));
	printf("float val = %fn", CAT(float));

	return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates arithmetic operations on pointers.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t088_ch3_array_interpretations.c
 *   Title          : Pointer Basics - Array Arithmetic - Example 3
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    demonstrates arithmetic operations on pointers.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int a[5] = {10, 20, 30, 40, 50};
    int *ptr;
    int i;

    /* 
     * This is the second interpretation by the compiler as a pointer to the first element
     * of an array
     * a is a pointer to the first element
     */
    ptr = a;

    for (i = 0; i < 5; i++)
    {
        /* 
         * The pointer is incremented every time the loop is run accessing each element of
         * an array its pointing to.
         * Note: The post increment happens first and the dereferencing next. Still the
         * pointer variable will be holding the older value which get dereferenced
         */
        printf("%d ", *ptr++);
    }
    printf("n");

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates the major difference between pointers and arrays on we handle it.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t089_ch3_pointers_vs_array.c
 *   Title          : Pointer Basics - Pointer vs Arrays Example 1 - Part 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    demonstrates the major difference between pointers and arrays on we handle 
 *                    it.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int a[5] = {10, 20, 30, 40, 50};
    int *ptr;
    int i;

    /* 
     * This is the second interpretation by the compiler as a pointer to the first element
     * of an array
     * a is a pointer to the first element
     */
    ptr = a;

    for (i = 0; i < 5; i++)
    {
        /* Allowed. As explained in the previous example */
        printf("%d ", *ptr++);
    }
    printf("n");

    for (i = 0; i < 5; i++)
    {
        /* Not allowed. The array name represents a constant pointer */
        printf("%d ", *a++);
    }
    printf("n");

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. This example demonstrates the major difference between pointers and arrays on we handle it.

 

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t090_ch3_pointers_vs_array.c
 *   Title          : Pointer Basics - Pointer vs Arrays Example 1 - Part 2
 *   Description    : The C basic data types allows us to access a limited and fixed number of 
 *                    the memory bytes. In order to increase the flexibility to access a range 
 *                    of memory bytes C supports pointers. Any variable defined as a pointer 
 *                    will hold an address of memory location. Have to be careful with dealing 
 *                    the address ranges, else would lead to illegal memory access. This example 
 *                    demonstrates the major difference between pointers and arrays on we handle 
 *                    it.
 *-------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int a[5] = {10, 20, 30, 40, 50};
    int *ptr;
    int i;

    /* 
     * This is the second interpretation by the compiler as a pointer to the first element
     * of an array
     * a is a pointer to the first element
     */
    ptr = a;

    for (i = 0; i < 5; i++)
    {
        /* Allowed. As explained in the previous example */
        printf("%d ", *ptr++);
    }
    printf("n");

    for (i = 0; i < 5; i++)
    {
        /* Allowed. Here we are indexing the elements from the base address */
        printf("%d ", *(a + i));
    }
    printf("n");

    return 0;
}

Example output:

 

Chapter 4 : Functions - Part 2

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.
There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful. This example show a simple usage of pass by reference.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t091_ch2_function_pass_by_ref.c
 *   Title          : Functions Basics - Pass by References - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful This 
 *                    example show a simple usage of pass by reference
 *---------------------------------------------------------------------------------------------*/ 

#include 

void modify(int *ptr)
{
    /* Changing the value of x with help of pointer */
    *ptr = 10;
}

int main()
{
    int x = 5;

    printf("x = %dn", x);

    /* The reference (address) of the x is sent to the modify function */
    modify(&x);

    printf("x = %dn", x);

    return 0;
}

Example output:

 

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful. This example show the most common discussed example “Swap” 2 variables.

 

Source Code:

/*---------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t092_ch2_function_pass_by_ref.c
 *   Title          : Functions Basics - Pass by References - Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. This 
 *                    example show the most common discussed example "Swap" 2 variables.
 *---------------------------------------------------------------------------------------------*/ 
 
#include 

void swap(int *ptr1, int *ptr2)
{
    int temp;

    temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;
}

int main()
{
    int a = 5, b = 10;

    printf("a = %d, b = %dn", a, b);

    /* Send the references of a and b to swap function */
    swap(&a, &b);

    printf("a = %d, b = %dn", a, b);

    return 0;
}

Example output:

 

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This code program illustrates the method of returning more than one value using pass by reference. C language does not support returning multiple values using the return keyword.
The solution is to pass the address of result variables by reference from the calling function. In this example, sum and prod are passed by reference from main() function..

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t093_ch2_function_pass_by_ref.c
 *   Title          : Functions Basics - Pass by References - Example 3
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. This code 
 *                    program illustrates the method of returning more than one value using pass 
 *                    by reference. C language does not support returning multiple values using the
 *                    return keyword.
 *                    The solution is to pass the address of result variables by reference from the 
 *                    calling function. In this example, sum and prod are passed by reference from 
 *                    main() function.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

void sum_prod(int x, int y, int *sum_ptr, int *prod_ptr)
{
    /* 
     * The operation happens on x and y and the result is stored in the address
     * referenced (pointed) by pointer sum_ptr (pointing to address of sum)
     */
    *sum_ptr = x + y;
    /* 
     * The operation happens on x and y and the result is stored in the address
     * referenced (pointed) by pointer prod_ptr (pointing to address of prod)
     */
    *prod_ptr = x * y;
}

int main()
{
    int a = 2, b = 5, sum, prod;

    /* The values of a and b are sent along with the references of sum and product */
    sum_prod(a, b, &sum, &prod);

    printf("sum = %d, prod = %dn", sum, prod);

    return 0;
}

Example output:

 

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This program illustrates the method of passing a block of data with the help of arrays a function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t094_ch2_fuction_pass_array.c
 *   Title          : Functions Basics - Pass by References - Passing arrays - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. 
 *                    This program illustrates the method of passing a block of data with the 
 *                    help of arrays a function.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/*
 * Accept the base address of the array in a variable ptr.
 * This is the second interpretation of an array. The compiler see this as a pointer to 
 * the first element of an big variable 'a'.
 * Hence the writing any number as size inside the square bracket makes no sense. But
 * the square brackets are required for the compiler not to interpret ptr as normal
 * integer variable
 */
void print_array(int ptr[])
{
    int i;

    /* 
     * The next issue is we will not be able to know the size of the array being passed to 
     * the function because of the same reason stated above. Hence we end up in writing a 
     * hard coded value as loop terminator.
     * This is not preferred for modular programming approach, so its better send the size
     * along with the base address of an array. Shown in next example
     */
    for (i = 0; i < 5; i++)
    {
    	printf("%d ", ptr[i]);
    }
    puts("");
}

int main()
{
    int a[5] = {1, 2, 3, 4, 5};

    /* Pass the base address of the array */
    print_array(a);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This program illustrates the method of passing a block of data with the help of arrays a function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t095_ch2_fuction_pass_array.c
 *   Title          : Functions Basics - Pass by References - Passing arrays - Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. 
 *                    This program illustrates the method of passing a block of data with the 
 *                    help of arrays a function.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/* 
 * As mentioned in the previous example, The base address of the array is stored in 
 * a pointer. Hence we can use the pointer notation to accept an array in a function
 */
void print_array(int *ptr, int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        /* Accessing a pointer like an array */
        printf("%d ", ptr[i]);
    }
    puts("");
}

int main()
{
    int a[5] = {1, 2, 3, 4, 5};
    int b[3] = {1, 2, 3};

    /* Pass the base address of arrays with their sizes */
    print_array(a, 5);
    print_array(b, 3);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This program illustrates the method of passing a block of data with the help of arrays a function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t096_ch2_fuction_pass_array.c
 *   Title          : Functions Basics - Pass by References - Passing arrays - Example 3
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. 
 *                    This program illustrates the method of passing a block of data with the 
 *                    help of arrays a function.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/* 
 * You should be able to understand this example based on explanation given on the 
 * previous examples
 */

void print_array(int *arr, int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }
    puts("");
}

void square_array(int a[], int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        *(a + i) = (*(a + i)) + (*(a + i));
    }
}

int main()
{
    int a[5] = {1, 2, 3, 4, 5};

    square_array(a, 5);
    print_array(a, 5);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This code program illustrates the method of returning more than one value using pass by reference. So on that context we can pass the array from main get it filled from the function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t097_ch2_fuction_return_array.c
 *   Title          : Functions Basics - Pass by References - Returning Arrays - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. 
 *                    This code program illustrates the method of returning more than one value 
 *                    using pass by reference. So on that context we can pass the array from 
 *                    main get it filled from the fuction.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

void print_array(int *arr, int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }
    puts("");
}

void get_user_input(int *a, int n)
{
    int i;

    printf("Enter %d integers: ", n);

    for (i = 0; i < n; i++)
    {
        scanf("%d", a + i);
    }
}

int main()
{
    int a[5];

    get_user_input(a, sizeof(a) / sizeof(a[0]));
    print_array(a, 5);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

There could be instance were we need to deal with a huge amount of data, return multiple values from functions, have common pool of data across different functions etc., then Pass by reference is very helpful.
This code program illustrates the method of returning more than one value using pass by reference. So can define an array in a function and return its address to the caller.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t098_ch2_fuction_return_array.c
 *   Title          : Functions Basics - Pass by References - Returning Arrays - Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    There could be instance were we need to deal with a huge amount of data, 
 *                    return multiple values from functions, have common pool of data across 
 *                    different functions etc., then Pass by reference is very helpful. 
 *                    This code program illustrates the method of returning more than one value 
 *                    using pass by reference. So can define an array in a function and return 
 *                    its address to the caller.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

void print_array(int *arr, int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }
    puts("");
}

int *get_user_input(int size)
{
    /* 
     * Note the definition below. The memory allocation for the array 'a' would be
     * automatic, which would get get destroyed when the function return becoming illegal
     * to access. By adding static storage modifier will help us get a memory which will
     * be available through out the program. Will see more on this in later examples
     */
    static int a[size];
    int i;

    for (i = 0; i < size; i++)
    {
        scanf("%d", a + i);
    }
}

int main()
{
    int *ptr;

    /* A function to get user inputs for 5 integer space */
    ptr = get_user_input(5);
    print_array(ptr, 5);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This program illustrates the use of the function prototype and the default behavior.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t099_ch2_funtion_prototype.c
 *   Title          : Functions Basics - Function Prototypes - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the use of the function prototype and the default 
 *                    behaviour
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/*
 * The compiler expect how a function is defined, like its no of arguments, the type
 * of the arguments and a function return type.
 * Now fortunately the compiler see the definition of 'display' function before it is 
 * called. So when any function calls it, the compiler has clear idea about its definition.
 * What if this function is defined in some other file or any function calls it before
 * the compiler knows about its definition?. Please look into the next example.
 */
void display(void)
{
    int count = 0;

    printf("count = %dn", ++count);
}

int main()
{
    display();

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This program illustrates the use of the function prototype and the default behavior.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t100_ch2_funtion_prototype.c
 *   Title          : Functions Basics - Function Prototypes - Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the use of the function prototype and the default 
 *                    behaviour
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int main()
{
    /*
     * The 'display' function is called before the compiler can know about its
     * definition
     */
    display();

    return 0;
}

/*
 * The code would work fine though you get compiler warning.
 * But note that, this will never be the same in all the cases.
 * The compiler would lead to an error it finds a major mismatch than its assumption
 * Please see the next example.
 */
void display(void)
{
    int count = 0;

    printf("count = %dn", ++count);
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This program illustrates the use of the function prototype and the default behavior.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t101_ch2_funtion_prototype.c
 *   Title          : Functions Basics - Function Prototypes - Example 3
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the use of the function prototype and the default 
 *                    behaviour
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int main()
{
    int num1 = 5, num2 = 10;
    double res;

    res = average(num1, num2);

    printf("average = %fn", res);
}

/*
 * This will lead to a compiler error. How to solve this??
 * Function Prototype - Please look into next example
 */
double average(int x, int y)
{
    double avg;

    avg = (x + y) / 2.0;

    return avg;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more. This program illustrates the use of the function prototype and the default behavior.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t102_ch2_funtion_prototype.c
 *   Title          : Functions Basics - Function Prototypes - Example 4
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group 
 *                    of instructions written to do a specific functionality (hence called as
 *                    function). Using functions we can achieve many advantages like Reusability,
 *                    Divide and conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the use of the function prototype and the default 
 *                    behaviour
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/* 
 * Function prototype
 * With the below line the compilers is aware about the exception of the 'average' function
 * when called before definition.
 * These are also called as declarations
 */
double average(int x, int y);
/*
 * Note: The variable names are not important in prototypes, but its types are. 
 * The above prototype could be written as 
 */
double average(int, int);
/*
 * Ya ya, I know :), the declarations can be made any number of times
 */

int main()
{
    int num1 = 5, num2 = 10;
    double res;

    res = average(num1, num2);

    printf("average = %fn", res);
}

double average(int x, int y)
{
    double avg;

    avg = (x + y) / 2.0;

    return avg;
}

Example output:

 

Chapter 5 : Storage Classes Part 1

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.
Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use local variables (also known as auto (automatic)).

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t103_ch4_storage_class_local.c
 *   Title          : Storage Classes - Local Variables - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use local variables (also known as
 *                    auto (automatic))
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int main()
{
    /* A local variable belonging to function 'main', visible to complete function */
    int x = 10;

    if(x > 5)
    { 
        /* 
         * y is a local variable belonging to this if block.
         * Only visbile to this block
         */
        int y = 1000;

        printf("y = %dn", y);
    }

    /* 
     * Compiler will issue an error, since it is not able to find 'y' in the current 
     * (function) block
     */
    printf("y = %dn", y);

    return 0;
}

Example output:

 

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use local variables (also known as auto (automatic)) name space issue.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t104_ch4_storage_class_local.c
 *   Title          : Storage Classes - Local Variables - Example 2
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use local variables (also known as
 *                    auto (automatic)) name space issue
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int main()
{
    /* A local variable belonging to function 'main', visible to complete function */
    int x = 10;

    if(x > 5)
    { 
        /* 
         * x is a local variable belonging to this if block.
         * Only visbile to this block
         * Note that there are 2 variables named 'x'. This is allowed if don't share the
         * same block
         */
        int x = 20;

        printf("x = %dn", x);
    }

    printf("x = %dn", x);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use local variables (also known as auto (automatic)) name space issue.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t105_ch4_storage_class_local.c
 *   Title          : Storage Classes - Local Variables - Example 3
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use local variables (also known as
 *                    auto (automatic)) name space issue
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int main()
{
    /* A local variable belonging to function 'main', visible to complete function */
    int x = 10;
    /* Again a variable with the same name */
    int x = 20;
    /* This is not allowed, which leads to name space issue */

    printf("x = %dn", x);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use local variables (also known as auto (automatic)). Usage of same names in different functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t106_ch4_storage_class_local.c
 *   Title          : Storage Classes - Local Variables - Example 4
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use local variables (also known as
 *                    auto (automatic)). Usage of same names in different functions.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/* A local variable (Parameter) belonging to function 'print', visible to complete function */
void print(int x)
{
    printf("%dn", x)
}

int main()
{
    /* A local variable belonging to function 'main', visible to complete function */
    int x = 10;

    print(x);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use local variables (also known as auto (automatic)). Usage of same names in different functions. Name space issue stack frame, between local variables and parameter list.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t107_ch4_storage_class_local.c
 *   Title          : Storage Classes - Local Variables - Example 5
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use local variables (also known as
 *                    auto (automatic)). Usage of same names in different functions. Name space 
 *                    issue stack frame, between local variables and parameter list.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

/* A local variable (Parameter) belonging to function 'print', visible to complete function */
void print(int x)
{
    /* Again a local variable with the same name not allowed */
    int x;

    printf("%dn", x)
}

int main()
{
    /* A local variable belonging to function 'main', visible to complete function */
    int x = 10;

    print(x);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use static storage modifier on variables. The static modified variables gets the memory allocated a data segments. These variables have the life through out the program cycle.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t108_ch4_storage_class_static.c
 *   Title          : Storage Classes - Static - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use static storage modifier on variables.
 *                    The static modified variables gets the memory allocated a data segments. 
 *                    These variables have the life through out the program cycle.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

void book_ticket(int recently_booked)
{
    static int total_tickets;

    total_tickets = total_tickets + recently_booked;

    printf("Total tickets booked: %dn", total_tickets);

}

int main()
{
    /* Say by booking agent */
    book_ticket(5);
    /* Say by online */
    book_ticket(50);
    /* Say by counter */
    book_ticket(30);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the use static storage modifier on variables. The static modified variables gets the memory allocated a data segments. These variables have the life through out the program cycle.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t109_ch4_storage_class_static.c
 *   Title          : Storage Classes - Static - Example 2
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use static storage modifier on variables.
 *                    The static modified variables gets the memory allocated a data segments. 
 *                    These variables have the life through out the program cycle.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

void foo(int num)
{
    /* 
     * Not possible. Only constant values can be assigned to static vars.
     * Memory is allocated at compile time in data segment
     */
    static int x = num;

    printf("%dn", x);

}

int main()
{
    foo(5);

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below:

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer.

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward.
This program demonstrates the we should not return address of local variables address.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thursday 23 Mar 2016 16:00:04 IST
 *   File           : c_t110_ch4_storage_class_local_return.c
 *   Title          : Storage Classes - Local Variables - Example 3
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment 
 *                    to lower memory requirements. This segment is usually marked read-only 
 *                    so a program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the 
 *                    programmer.
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be 
 *                    added (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library 
 *                    also gets dynamic memory for its own personal workspace from the heap 
 *                    as well. As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use static storage modifier on variables.
 *                    The static modified variables gets the memory allocated a data segments. 
 *                    These variables have the life through out the program cycle.
 *-----------------------------------------------------------------------------------------------*/ 
 
#include 

int * foo(void)
{
    int a = 10;

    /* Local variables address should not be returned */
    return &a;
}

int main()
{
    int *ptr;

    ptr = foo();

    printf("Do not return local variable's address!!n");

    /* Expects to print 10. But!! */
    printf("*ptr = %dn", *ptr);

    return 0;
}

Example output:

 

Chapter 6 : Functions - Part 3

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.
This program illustrates the implicit linking of the standard functions by the compiler.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wednesday 05 April 2017 16:00:04 IST
 *   File           : c_t111_ch2_functions_linking.c
 *   Title          : Functions Basics - Function Linking - Implicit
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like Re usability, Divide and 
 *                    conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the implicit linking of the standardfunctions by 
 *                    the compiler.
 *-----------------------------------------------------------------------------------------------*/ 
 
int main()
{
    /*
     * 'printf' is a standard built-in library function.
     * If you note, we have not included the function prototype for this, so we might expect 
     * warning by the compiler!. In order to avoid it we have to add a header file which has
     * the declaration of 'printf', and this is nothing but "stdio.h"
     * Interestingly you would observe that the compiler would compile the code and it would 
     * run without even including the header file!.
     * Why? Well the answer is simple, when the compiler see a function call before it sees
     * the definition, it implicitly assumes then to be in libc library and if it finds it
     * proceeds with the compilation, else we will get an error while linking
     */
    printf("hellon");

    /* Please do see the next example for explicit linking */

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.
This program illustrates the need of explicit linking of the standard functions by the compiler.

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wednesday 05 April 2017 16:00:04 IST
 *   File           : c_t111_ch2_functions_linking.c
 *   Title          : Functions Basics - Function Linking - Implicit
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like Re usability, Divide and 
 *                    conquer, Modularity, Testability, Abstraction and many more.
 *                    This program illustrates the implicit linking of the standardfunctions by 
 *                    the compiler.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
/* Header file containing the declaration for sqrt function */
#include 

int main()
{
    double res;
    double val = 10;

    /* 
     * Will compiler do the same thing as mentioned in the previous example
     * Well yes, but the sqrt function is not part of the libc library, and hence
     * we need to explicitly link the libm library while compiling
     * See the sample output section
     */
    res = sqrt(val);

    printf("%fn", res);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

A function calling itself to perform given task is called as Recursion. A concept which could be used to solve a problem elegantly. Many complex operation can be easily implemented with it. But as we all know that, every thing as an advantage and disadvantage. In order to have recursion we need good amount of memory and take more time to preform the task because of context switching.

This program illustrates the how to implement a simple recursive function for a generating a factorial of a given number.

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wednesday 05 April 2017 16:00:04 IST
 *   File           : c_t113_ch2_function_recursion.c
 *   Title          : Functions Basics - Recursion
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    A function calling itself to perform given task is called as Recursion. 
 *                    A concept which could be used to solve a with it. But as we all know that, 
 *                    every thing as an advantage and disadvantage. In order to have recursion we 
 *                    need good amount of memory and take more time to preform the task because of 
 *                    context switching.
 *                    This program illustrates the how to implement a simple recursive function for 
 *                    a generating a factorial of a given number
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int factorial(int n)
{
    /* 
     * Base condition:
     * Every recursive solution should have a finite limit. When a function is called
     * a stack frame is created and grows till it reaches the depth (a function call within
     * a function). The last frame which is created would get destroyed first in a LIFO manner.
     * If the depth of the function call doesn't end within amount of allocated stack, it would 
     * lead to segment violation (sometimes called as stack overflow). So the decided limit 
     * up to which a stack can grow is called base condition
     */
    if (n == 0)
    {
        return 1;
    }
    else
    {
        /* 
         * Recursive condition:
         * A condition which call the function (self) again is called as recursive condition
         */
        return n * factorial(n - 1);
    }
}

Example output:

 

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like
Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

A function calling itself to perform given task is called as Recursion. A concept which could be used to solve a problem elegantly. Many complex operation can be easily implemented with it. But as we all know that, every thing as an advantage and disadvantage. In order to have recursion we need good amount of memory and take more time to preform the task because of context switching.

This program illustrates the how to function recursion would lead to stack overflow.

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wednesday 05 April 2017 16:00:04 IST
 *   File           : c_t113_ch2_function_recursion.c
 *   Title          : Functions Basics - Recursion
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    A function calling itself to perform given task is called as Recursion. 
 *                    A concept which could be used to solve a with it. But as we all know that, 
 *                    every thing as an advantage and disadvantage. In order to have recursion we 
 *                    need good amount of memory and take more time to preform the task because of 
 *                    context switching.
 *                    This program illustrates the how to function recursion would lead to stack 
 *                    overflow.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int test(int n)
{
    /*
     * The base condition missing!!
     */

    /* 
     * Recursive condition:
     * A condition which call the function (self) again is called as recursive condition
     * Since the base condition is missing, this would keep on calling (say infinite,
     * theoretically) leading to stack overflow
     */
    return n + test(n - 1);
}

int main()
{
    int res;

    res = test(3);

    printf("res = %dn", res);

    return 0;
}

Example output:

Chapter 7 : Standard IO

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory

 

This program shows the usage of getchar and putchar functions.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t115_ch4_stdio_unformatted.c
 *   Title          : Standard I/O - Unformatted I/0
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows the usage of getchar and putchar functions
 *-----------------------------------------------------------------------------------------------*/ 

#include 
/* For character classification routines */
#include 

int main()
{
	int ch;

    /* 
     * Just loop this End of File (EOF) is encountered
     * getchar reads a character from the input stream (stdin)
     * Note: Need to hit Ctrl-D for EOF
     */
	for ( ; (ch = getchar()) != EOF; )
	{
	    /* 
	     * Put the received character from the input stream (stdin) to output
	     * stream (stdout)
	     * toupper is a function to convert lower case to upper case letters
	     */
		putchar(toupper(ch));
	}

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory

 

This program shows the usage of getchar and putchar functions.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t116_ch4_stdio_unformatted.c
 *   Title          : Standard I/O - Unformatted I/0
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows the usage of getchar and putchar functions
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    char buffer[10];
	
    /* 
     * Reads characters from the input stream (stdin)
     * Not recommend to use, since it would try to write the input buffer
     * to the 'buffer' without checking the size leading to stack smashing.
     * Use fgets instead.
     */
    gets(buffer);
    /* 
     * Puts the user string on the standard output (stdout) on encountering
     * new line ('n')
     */
    puts(buffer);

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory

 

This program shows the difference between gets and fgets.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t117_ch4_stdio_unformatted.c
 *   Title          : Standard I/O - Unformatted I/0
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows the difference between gets and fgets.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    char buffer[10];

    /* 
     * Reads characters from the input stream (stdin) upto specified 
     * count
     * fgets is safer, as  you can specify the size of array.
     * If user enters more characters in stdin, they are ignored.
     * Only size - 1 characters are read. 1 byte is reserved for 
     */
    fgets(buffer, 10, stdin);
    puts(buffer);

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows different type specifiers to format the output.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t118_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - type specifiers
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different type specifiers to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("%cn", 'A');
	printf("%d %in", 10, 10);
	printf("%on", 8);
	printf("%x %X %xn", 0xABCD, 0xABCD, 10);
	printf("%u %dn", 255, (char) 255);
	printf("%f %Fn", 2.0, 2.0);
	printf("%e %En", 1.2, 1.2);
	printf("%a %An", 123.4, 123.4);
	printf("%g %Gn", 1.21, 1.0);
	printf("%sn", "Hello");

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory

 

This program shows different width specifiers to format the output.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t119_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - width specifiers
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different width specifiers to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("%3d %3dn", 1, 1);
	printf("%3d %3dn", 10, 10);
	printf("%3d %3dn", 100, 100);

	printf("%10sn", "Hello");
	printf("%20sn", "Hello");

	printf("%*dn", 1, 1);
	printf("%*dn", 2, 1);
	printf("%*dn", 3, 1);

	printf("%*sn", 5, "Hello");
	printf("%*sn", 6, "Hello");
	printf("%*sn", 7, "Hello");

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows different length specifiers to format the output.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t120_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - length specifiers
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different length specifiers to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("%hXn", 0xFFFFFFFF);
	printf("%lXn", 0xFFFFFFFFl);
	printf("%llXn", 0xFFFFFFFFFFFFFFFF);

	printf("%Lfn", 1.23456789L);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows different flag specifiers to format the output.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t121_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - flag specifiers
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different flag specifiers to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("%-3d %-3dn", 1, 1);
	printf("%-3d %-3dn", 10, 10);
	printf("%-3d %-3dn", 100, 100);

	printf("%03dn", 1);

	printf("% 3dn", 111);
	printf("% 3dn", -111);

	printf("%#x %#X %#xn", 0xABCD, 0xABCD, 10);
	printf("%#on", 8);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows different precision specifiers to format the output.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t122_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - precision specifiers
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different precision specifiers to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("%3.1dn", 1);
	printf("%3.2dn", 1);
	printf("%3.3dn", 1);

	printf("%0.3fn", 1.0);
	printf("%5.3fn", 122.0);
	printf("%0.10fn", 1.0);

	printf("%12.10sn", "Hello World");

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstartes the return value of printf and how it is important to find its failure.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t123_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - escape sequence
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows different escape sequences to format the output.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("Hello");
	printf(" ");
	printf("World");
	printf("n");

	printf("Hello Worldn");

	printf("HellorWorldn");

	printf("HellobWorldn");

	printf("HellotWorldn");

	printf("Hello vWorldn");

	printf("f");

	printf("The path in Linux is A/B/Cn");
	printf("The path in Windows is ABCn");

	printf("Its 100%% correctn");

	printf("HelloeWorldn");

	printf(""Hello World"n");

	printf("127157162154144 11014515415415712");

	return 0;
}
Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory. This program demonstartes the return value of printf and how it is important to find its failure

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t123_ch4_stdio_formatted_printf.c
 *   Title          : Standard I/O - Formatted I/0 - printf - escape sequence
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstartes the return value of printf and how it is important
 *                    to find its failure.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int ret;

    ret = printf("hellon");
    (ret != -1) ? printf("Printed %d charsn", ret) : puts("puts: Failed to print");

    /* Close stdout */
    close(1);

    ret = printf("worldn");
    (ret != -1) ? fprintf(stderr, "fprintf: Printed %d charsn", ret) : fprintf(stderr, "fprintf: Failed to printn");

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows how to scan different data types from user

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t125_ch4_stdio_formatted_scanf.c
 *   Title          : Standard I/O - Formatted I/0 - scanf
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows how to scan different data types from user.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int num1;
	char ch;
	float num2;
	char string1[100];

	printf("Please enter in the following order to get expected outputn");
	printf("An integernA single characternA float numbernA non space stringn");

	scanf("%d %c %f %s", &num1 , &ch, &num2, string1);
	printf("%d %c %f %sn", num1, ch, num2, string1);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows how to scan different data types from user, if required we can ignore some type of data entered by the user with flag.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t126_ch4_stdio_formatted_scanf.c
 *   Title          : Standard I/O - Formatted I/0 - scanf - Ignore user input
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows how to scan different data types from user, if required we 
 *                    can ignore some type of data entered by the user with * flag
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int hours;
	int mins;
	int secs;

	printf("Please enter Time as HH:MM:SSn");

	scanf("%d%*c%d%*c%d", &hours, &mins, &secs);
	printf("%d:%d:%dn", hours, mins, secs);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory This program demonstrates the return value of printf and how it is important to find its failure.

 

This program shows what scanf return in case of successful scan and invalid scan.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t127_ch4_stdio_formatted_scanf.c
 *   Title          : Standard I/O - Formatted I/0 - scanf - return value
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows what scanf return in case of sucessful scan and
 *                    invalid scan.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int hours = 12;
	int mins = 55;
	int secs = 15;
	int ret;

	printf("Please enter Time as HH:MM:SSn");

	ret = scanf("%d%*c%d%*c%d", &hours, &mins, &secs);

	if (ret != 3)
	{
		printf("Scaned %d elementsn", ret);
		printf("%d:%d:%dn", hours, mins, secs);
		printf("Invalid Inputs. Please try againn");

		return 1;
	}

	printf("Scaned %d elementsn", ret);
	printf("%d:%d:%dn", hours, mins, secs);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows how to scan have a issue if called in a loop because of input buffer.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t128_ch4_stdio_formatted_scanf.c
 *   Title          : Standard I/O - Formatted I/0 - scanf - Buffering issues
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows how to scan have a issue if called in a loop because of 
 *                    input buffer.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    char ch;

	while (ch != 'q')
	{
		printf("Enter a char: ");
		scanf("%c", &ch);

		printf("nYou entered %cn", ch);
	}

    return 0;
}
Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows how to scan have a issue if called in a loop because of input buffer.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t129_ch4_stdio_formatted_scanf.c
 *   Title          : Standard I/O - Formatted I/0 - scanf - Buffering issues
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows how to scan have a issue if called in a loop because of 
 *                    input buffer.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int x;
    char ch;

    printf("Enter a number: ");
    scanf("%d", &x);

    printf("Enter a char: ");
    scanf("%c", &ch);

    printf("You entered %d and %cn", x, ch);

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows usage of sptintf – printf as string in a buffer.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t130_ch4_stdio_formatted_sprintf.c
 *   Title          : Standard I/O - Formatted I/0 - sprintf
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows usage of sptintf - printf as string in a buffer
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int ret;
	int num1 = 123;
	char ch = 'A';
	float num2 = 12.345;
	char string1[] = "sprintf() Test";
	char string2[100];
	
	ret = sprintf(string2, "%d %c %f %s", num1 , ch, num2, string1);
	
	printf("This string "%s" is printed by sprintf() and it printed %d charsn", string2, ret);


	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows usage of sscanf – scan from a string.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t131_ch4_stdio_formatted_sscanf.c
 *   Title          : Standard I/O - Formatted I/0 - sscanf - Example 1
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows usage of sscanf - scan from a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int age;
	char array_1[10];
	char array_2[10];

	/* Note the below line carefully */
	sscanf("I am 30 years old", "%s %s %d ", array_1, array_2, &age);
	printf("%sn", array_1);
	printf("%sn", array_2);
	printf("Ok you are %d oldn", age);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows usage of sscanf – scan from a string.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t132_ch4_stdio_formatted_sscanf.c
 *   Title          : Standard I/O - Formatted I/0 - sscanf - Example 2
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows usage of sscanf - scan from a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int age;
	
	/* Note the below line carefully */
	sscanf("I am 30 years old", "%*s%*s%d%*s", &age);
	printf("Ok you are %d oldn", age);

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t133_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Output - Clear on program exit
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("hello");

    /* The output buffer gets cleared on program termination */
    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t134_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Output - Clear with 'n'
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    while (1)
    {
        /* The buffer gets cleared on encountering a n */
		printf("hellon");
		sleep(1);
    }
    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the fcodeormatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t135_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Output - Clear while a read operation
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	int num;

	while (1)
	{
		printf("Enter a number: ");
		/* 
		 * Note that the above line doesn't have n, still it got
		 * printed before a read is called
		 */
		scanf("%d", &num);
		printf("You entered %d", num);
	}

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t136_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Output - Clear with fflush call
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    while (1)
    {
		printf("hello");
		/* Clears the buffer */
		fflush(stdout);
		sleep(1);
    }

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t137_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Output - clear while buffer overflow
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
	char *str = "1";

	while (1)
	{
	    /* 
	     * The printf will on screen will appear only when the output buffer is filles
	     * Assume the buffer size is 8 bytes, the output would appear on screen every 
	     * 8 seconds
	     */
		printf("%s", str);
		sleep(1);
	}

	return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t138_ch4_stdio_output_buffer.c
 *   Title          : Standard I/O - Buffering - Error
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    int flag = 0;

    while (1)
    {
		fputs("hello on stdout", stdout);
		/* Comes on the screen immediately */
		fputs("hello on stderr", stderr);

		sleep(1);
    }

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t139_ch4_stdio_input_buffer.c
 *   Title          : Standard I/O - Buffering - Input - Clears on encountering 'n'
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 
#include 

int main()
{
    char ch = '0';

    printf("The loop will continue to print all characters entered before 'Y' and Enter Key!!!n");
    printf("Please try itn");

    while (ch != 'Y')
    {
        scanf("%c", &ch);
        printf("%c ", ch);
    }

    printf("Now, That was due to buffered inputn");

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t140_ch4_stdio_input_buffer.c
 *   Title          : Standard I/O - Buffering - Input - Clear with __fpurge
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 
#include 

int main()
{
    char ch = '0';

    printf("The loop will print only the first character, until 'Y' and Enter Key is pressed!!!n");
    printf("Please try itn");

    while (ch != 'Y')
    {

        scanf("%c", &ch);

        /* Not Standard and not portable */
        __fpurge(stdin);

        printf("%cn", ch);
    }

    printf("Now, That was due to buffer clearing after reading one charactern");

    return 0;
}

Example output:

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program demonstrates when output buffer get cleared.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t141_ch4_stdio_input_buffer.c
 *   Title          : Standard I/O - Buffering - Input - Read upto n
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program demonstrates when output buffer get cleared.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 
#include 

int main()
{
    char ch  = '0';

    printf("The loop will print only the first character, until 'Y' and Enter Key is pressed!!!n");
    printf("Please try itn");

    while (ch != 'Y')
    {
      scanf("%c", &ch);

      while (getchar() != 'n');

      printf("%cn", ch);
    }

    printf("Now, This was due to buffer clearing after reading one charactern");

    return 0;
}

Example output:

 

Brief:

Most of the system application interact with the users. The output presentations sometimes matter. The standard i/o functions gives us the facilities required. There are 2 types of functions available to handle the data, they are unformatted and formatted functions. The unformatted function are use to handle raw data where there are no data conversions required before access. While the formatted function as the name specifies does the required data conversions before storing or reading from memory.

 

This program shows how regular expression can be used with printf.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t142_ch4_stdio_formatted_printf_regex.c
 *   Title          : Standard I/O - Formatted I/0 - printf - Regular Expressions
 *   Description    : Most of the system application interact with the users. The output 
 *                    presentations sometimes matter. The standard i/o functions gives us the 
 *                    facilities required.There are 2 types of functions available to handle the 
 *                    data, they are unformatted and formatted functions. The unformatted function 
 *                    are use to handle raw data where there are no data conversions required 
 *                    before access. While the formated function as the name specifies does the 
 *                    required data conversions before storing or reading from memory. 
 *                    This program shows how regular expression can be used with printf.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    char name[30];
    char temp[30];
    unsigned int id;
    int status;

    printf("Enter name: ");
    status = scanf("%[a-zA-Z]", name);

    /* Will be 1 if the user input starts with alphabet */
    if (status == 1)
    {
    	printf("Name: %sn", name);
    }
    else
    {
    	printf("%sn", "You entered invalid name");
    	return 1;
    }

    /* Ignore all upto n */
    while (getchar() != 'n');

    printf("Enter an ID: ");
    status = scanf("%[0-9]", temp);

    if (status == 1)
    {
        /* Convert string to integer */
    	id = atoi(temp);
    	printf("ID: %dn", id);
    }
    else
    {
    	printf("%sn", "You entered invalid ID");
    	return 1;
    }

    return 0;
}

Example output:

Chapter 8 : Strings

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show some different ways of initializing the strings.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t143_ch5_strings_inits.c
 *   Title          : Strings - Initializations
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show some different ways of initializing the strings
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int i;

    /* A character array */
	char char_array[11] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};

    for (i = 0; i < sizeof(char_array); i++)
    {
        printf("%c", char_array[i]);
    }
    printf("n");

    /* Sequence of characters which ends with a '' is called as string */
	char string1[12] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', ''};

    printf("%sn", string1);

    /* 
     * Sequence of characters which ends with a '' is called as string 
     * Compiler implicitly assumes the size to be the no of initialized 
     * elements
     */
	char string2[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', ''};

    printf("%sn", string2);

    /* 
     * As mentioned in description, characters enclosed with "" are considered as
     * string and has an implicit ''
     */
	char string3[] = "Hello World";

    printf("%sn", string3);

    /* 
     * A string pointed by a pointer 'string4'
     */
	char *string4 = "Hello World";

    printf("%sn", string4);

    return 0;
}

Example output:

 

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the behavior of compiler in allocating the memory to a string based on different methods.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t144_ch5_strings_mem_alloc.c
 *   Title          : Strings - Memory Allocations
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the behaviour of compiler in allocating the memory to a 
 *                    string based on different methods.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int i;

    /* A string defined as an array. This would go to stack */
	char string1[12] = "Hello World";
    /* 
     * A string defined with pointer. The allocation of this method
     * would depend on the compiler. This could go to an read only section or a
     * stack, a will be pointed by a pointer
     */
	char *string2 = "Hello World";

    printf("%sn", string1);
    printf("%sn", string2);

    printf("The address of string1 is %pn", &string1);
    printf("The address of first element in string1 is %pn", &string1[0]);

    /* Note the output in this case */
    printf("The address of string2 is %pn", &string2);
    printf("The address of first element in string2 is %pn", &string2[0]);

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the size occupied by the string in memory.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t145_ch5_strings_size.c
 *   Title          : Strings - Size
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the size occupied by the string in memory.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    /* A string defined as an array. This would go to stack */
	char string1[12] = "Hello World";
	char *string2 = "Hello World";

    /* 
     * First array interpretation
     */
    printf("%zun", sizeof(string1));
    /* 
     * Note the output in this case
     * You get the size of the pointer not the string pointed by it!
     */
    printf("%zun", sizeof(string2));

    /* 
     * Size of the string can be obtained using 'strlen' function
     * Note: The 'strlen' function ignores the null
     */
    printf("%dn", strlen(string1));
    printf("%dn", strlen(string2));

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.
Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example illustrates sting juxtaposing.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t146_ch5_strings_juxtaposing.c
 *   Title          : Strings - Juxtaposing
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example illustrates sting juxtaposing
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    if (sizeof("Hello" "World") == sizeof("Hello") + sizeof("World"))
    {
        printf("WoWn");
    }
    else
    {
        printf("HuHn");
    }

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible manipulations.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t147_ch5_strings_manipulations.c
 *   Title          : Strings - Manipulation
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible manipulations
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    /* A string defined as an array. This would go to stack */
	char string1[12] = "Hello World";
	char *string2 = "Hello World";

    /*
     * As mentioned in the previous examples, this would got to stack, hence we
     * can modify the content
     */
    string1[4] = ' ';
    printf("%sn", string1);
    /*
     * This could go to a read only section (at least in GCC), hence we cannot
     * change its content
     * This will lead to a run time failure
     */
    string2[4] = ' ';
    printf("%sn", string2);

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible manipulations.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t148_ch5_strings_mem_share.c
 *   Title          : Strings - Memory Sharing
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible manipulations
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    /*
     * As mentioned in the previous example could go to a read only section 
     * (at least in GCC) we cannot modify ist contents, the compiler acts smart 
     * providing the same address to both the pointers.
     */
	char *string1 = "Hello World";
	char *string2 = "Hello World";

    if (string1 == string2)
    {
        printf("Yea, they share the same locationn");
    }

    /*
     * Here the pointers don't share the same location
     */
	char *string3 = "Hello World";
	char *string4 = "Hello Worlds";

    if (string3 != string4)
    {
        printf("Nope, Hmm!! why??, Thinkn");
    }

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t149_ch5_string_scan.c - Example 1
 *   Title          : Strings - Read from user
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    char str[10];

    printf("Enter a string: ");
    /* 
     * Scanf doesn't know the size of the defined array.
     * Hence buffer overflow can happen, if user enters
     * more than array size characters. Same applies for
     * gets() function. Hence you get a message gets() is dangerous.
     */
    scanf("%s", str);

    printf("You entered %sn", str);

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t150_ch5_string_scan.c
 *   Title          : Strings - Read from user - Example 2
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

void get_string(char *str, int size)
{
    int i;

    for (i = 0; i < (size - 1); i++)
    {
        scanf("%c", &str[i]);

        if (isspace(str[i]))
        {
            break;
        }

    }
    /* String terminator */
    str[i] = '';
}

int main()
{
    char str[10];

    printf("Enter a string: ");
    get_string(str, sizeof(str)); 

    printf("You entered %sn", str);

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t151_ch5_string_scan.c
 *   Title          : Strings - Read from user - Example 3
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

void get_string(char *str, int size)
{
    fgets(str, size, stdin);

    if (str[strlen(str) - 1] == 'n')
    {
        str[strlen(str) - 1] = '';
    }
}

int main()
{
    char str[10];

    printf("Enter a string: ");
    get_string(str, sizeof(str)); 

    printf("You entered %sn", str);

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t152_ch5_string_scan.c
 *   Title          : Strings - Read from user - Example 4
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    /* Uninitialized pointer */
    char *str;

    printf("Enter a string: ");
    /* 
     * Trying to scan the data at a location pointed by a uninitialized pointer
     * Note: Illegal and could case run time error!!
     */
    scanf("%s", str);
    printf("string is %sn", str);

    /* Please do see the next example */

    return 0;
}

Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “. This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t153_ch5_string_scan.c
 *   Title          : Strings - Read from user - Example 5
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

void get_string(char *str, int size)
{
    fgets(str, size, stdin);

    if (str[strlen(str) - 1] == 'n')
    {
        str[strlen(str) - 1] = '';
    }
}

int main()
{
    char arr[10];
    char *str;

    str = arr;

    printf("Enter a string: ");
    get_string(str, sizeof(arr)); 
    printf("string is %sn", arr);

    return 0;
}
Example output:

Brief:

Computers are designed to interact with humans, and we come to know on what’s happening by the messages printed on screen. A message is a group of words, words are group of characters. So a message is typically stored as a string.

Strings: Contiguous sequence of characters. Stores printable ASCII characters and its extensions. End of the string is marked with a special character, the null character ‘\0’. ‘\0’ is implicit in strings enclosed with ” “.
This example show the possible way to read a string from the user.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Friday 07 April 2017 16:00:04 IST
 *   File           : c_t154_ch5_string_functions.c
 *   Title          : Strings - Some example user defined functions
 *   Description    : Computers are designed to interact with humans, and we come to know on whats 
 *                    happening by the messages printed on screen. A message is a group of words, 
 *                    words are group of characters. So a message is typically stored as a string.
 *                    Strings:
 *                    Contiguous sequence of characters. 
 *                    Stores printable ASCII characters and its extensions
 *                    End of the string is marked with a special character, the null character ''
 *                    '' is implicit in strings enclosed with " "
 *
 *                    This example show the possible way to read a string from the user
 *-----------------------------------------------------------------------------------------------*/ 

#include 

size_t str_len(const char *str)
{
	int length = 0;

	while (*str != '')
	{
		length++;
		str++;
	}

	return length;
}

char *str_rev(char *str)
{
	int length;
	int i;
	char ch;

	length = str_len(str) - 1;

	i = 0;
	while (length > i)
	{
		ch = str[i];
		str[i] = str[length]; 
		str[length] = ch; 
		i++;
		length--;
	}

	return str;
}

int str_palin_check(char *str)
{
	int length;
	int i;
	char ch;

	length = str_len(str) - 1;

	for (i = 0; i < (length + 1) / 2; i++) { ch = *(str + length - i); if (ch == *(str + i)) { continue; } else { return 1; } } return 0; } int str_cmp(const char *str1, const char *str2) { int ret; for ( ; *str1 != ''; ) { if (*str1 == *str2) { str1++; str2++; continue; } break; } ret = *str1 - *str2; if (ret > 0)
	{
		ret = 1;
	}
	else if (ret < 0) { ret = -1; } return ret; } int str_to_upper(char *str) { int convertion_count = 0; while (*str != '') { if ((*str >= 'a') && (*str <= 'z')) { *str = *str - 32; convertion_count++; } str++; } return convertion_count; } int str_to_lower(char *str) { int convertion_count = 0; while (*str != '') { if ((*str >= 'A') && (*str <= 'Z'))
		{
			*str = *str + 32;
			convertion_count++;
		}

		str++;
	}

	return convertion_count;
}

char *str_cpy(char *dest, const char *src)
{
	int i = 0;

	while (*src != '')
	{
		*(dest + i++) = *src++;
	}
	*(dest + i) ='';

	return dest;
}

int main()
{
    int ret;
    char buffer[10];

    ret = str_len("Hello");
    printf("The length of the string is %dn", ret);

    str_cpy(buffer, "Hello");
    printf("The buffer contains: %sn", buffer);

    !str_cmp("Hello", "Hello") ? printf("Truen") : printf("Falsen");
    !str_cmp("Hell", "Hello") ? printf("Truen") : printf("Falsen");

    str_to_upper(buffer);
    printf("The buffer contains: %sn", buffer);

    str_rev(buffer);
    printf("The buffer contains: %sn", buffer);

    !str_palin_check("Hello") ? printf("Truen") : printf("Falsen");
    !str_palin_check("madam") ? printf("Truen") : printf("Falsen");

    return 0;
}

Example output:

 

Chapter 9 : Storage classes Part 2

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use register modifier on variables.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t155_ch4_storage_class_register.c
 *   Title          : Storage Classes - Register - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use register modifier on variables
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    /* Request the loader to get a register space if available, else defaults to int */
	register int iter_1;
	
	for (iter_1 = 0; iter_1 < 5000000; ++iter_1)
	{
		printf("r%d", iter_1);
	}
	printf("n");

	return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions
Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use register modifier on variables.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t156_ch4_storage_class_register.c
 *   Title          : Storage Classes - Register - Example 2
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use register modifier on variables
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	register int num;
	
	/* An address of a register variable cannot be accessed */
	scanf("%d", &num);
	printf("%dn", num);

	return 0;
}

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions
Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use register modifier on variables.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (http://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t157_ch4_storage_class_register.c
 *   Title          : Storage Classes - Register - Example 3
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use register modifier on variables
 *-----------------------------------------------------------------------------------------------*/ 

#include <stdio.h>

int main()
{
	register int i = 10;
	/* An address of a register variable cannot be accessed */
	int *j = &i;

	printf("*j %dn", *j);

	return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use global variable.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t158_ch4_storage_class_global.c
 *   Title          : Storage Classes - Global Variables - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use global variable
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/*
 * A global variable which has the visibility all the functions in this file
 * and to all the files if required
 * Global variable are extern by default can be accessed by other file using
 * extern keyword
 */
int count;

void print_count(void)
{
    printf("The count is: %dn", count);
}

void counter(void)
{
	count++;
}

int main()
{
	while (1)
	{
		counter();
		print_count();
		sleep(1);
	}

	return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute

The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use global variable.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t159_ch4_storage_class_global.c
 *   Title          : Storage Classes - Global Variables - Example 2
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use global variable
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/*
 * A global variable which has the visibility all the functions in this file
 * and to all the files if required
 * Global variable are extern by default can be accessed by other file using
 * extern keyword
 */
int count;

void print_count(void)
{
    /*
     * A variable with a same name in a local space will over shadow the 
     * global variable (means they are different though the name are same)
     * This is an automatic variable now
     */
    int count = 0;

    /* The count value will be always zero */
    printf("The count is: %dn", count);
}

void counter(void)
{
	count++;
}

int main()
{
	while (1)
	{
		counter();
		print_count();
		sleep(1);
	}

	return 0;
}
Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute
The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use static global variable across multiple files.

 

Handler Function:

#include 

/* A variable for timing one second */
int one_second;

/* Called by the kernel after the set time is elapsed */
void alarm_handler(int not_used)
{
    /* Gets reset in c_t159_ch4_storage_class_global.c */
	one_second = 1;

    printf("One Second Overn");
}

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t160_ch4_storage_class_global.c
 *   Title          : Storage Classes - Static Global Variables - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use ststic global variable across multiple files
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/* 
 * A variable with same name defined in in c_t160_ch4_handler.c which gets set
 * for a set time. We have a alarm call set for 1 second hence the name.
 * The one_second defined in this file is modified as a static global variable
 * which can be seen only by the functions defined in this file
 */
static int one_second;
extern void alarm_handler(int not_used);

int main()
{
    int five_seconds = 0;

    /*
     * A handler for alarm
     * To know more about these type of functions you can look into you Linux Internal link
     */
    signal(SIGALRM, alarm_handler);

    /* Set the alarm trigger for one second */
    alarm(1);

    /* Let the loop terminate after 5 seconds */
    while (five_seconds != 5)
    {
        /* 
         * This variable doesn't get set at all since no one modifies it in this file
         * The alarm will not be triggered again. This leads to infinite loop
         */
        if (one_second)
        {
            /* This code will be never reached */
            alarm(1);

            /* This code will be never reached */
            one_second = 0;
            five_seconds++;
        }
    }

    printf("Five Seconds Overn");

    return 0;
}

Example output:

Brief:

An program after loading into memory would occupy different space based on the requirement. They are as mentioned below

Text Segment: The text segment contains the actual code to be executed. It’s usually sharable, so multiple instances of a program can share the text segment to lower memory requirements. This segment is usually marked read-only so a program can’t modify its own instructions

Initialized Data Segment: This segment contains global variables which are initialized by the programmer

Uninitialized Data Segment: Also named “BSS” (block started by symbol) which was an operator
used by an old assembler. This segment contains uninitialized global variables. All variables in this segment are initialized to 0 or NULL (for pointers) before the program begins to execute

The Stack: The stack is a collection of stack frames. When a new frame needs to be added (as a result of a newly called function), the stack grows downward
The Heap: Most dynamic memory, whether requested via C’s malloc(). The C library also gets dynamic memory for its own personal workspace from the heap as well. As more memory is requested “on the fly”, the heap grows upward

This program demonstrates the use static global variable across multiple files.

 

Handler Function:

#include 

/* A variable for timing one second */
int one_second;

/* Called by the kernel after the set time is elapsed */
static void alarm_handler(int not_used)
{
    /* Gets reset in c_t159_ch4_storage_class_global.c */
	one_second = 1;

    printf("One Second Overn");
}

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_t161_ch4_storage_class_static_function.c
 *   Title          : Storage Classes - Static Functions - Example 1
 *   Description    : An program after loading into memory would occupy different space based on 
 *                    the requirement. They are as mentioned below.
 *                    Text Segment: 
 *                    The text segment contains the actual code to be executed. It's usually 
 *                    sharable, so multiple instances of a program can share the text segment to 
 *                    lower memory requirements. This segment is usually marked read-only so a 
 *                    program can't modify its own instructions.
 *                    Initialized Data Segment:
 *                    This segment contains global variables which are initialized by the programmer
 *                    Uninitialized Data Segment:
 *                    Also named “BSS" (block started by symbol) which was an operator used by 
 *                    an old assembler. This segment contains uninitialized global variables. 
 *                    All variables in this segment are initialized to 0 or NULL (for pointers) 
 *                    before the program begins to execute
 *                    The Stack:
 *                    The stack is a collection of stack frames. When a new frame needs to be added 
 *                    (as a result of a newly called function), the stack grows downward
 *                    The Heap: 
 *                    Most dynamic memory, whether requested via C's malloc(). The C library also 
 *                    gets dynamic memory for its own personal workspace from the heap as well. 
 *                    As more memory is requested "on the fly", the heap grows upward
 *                    
 *                    This program demonstrates the use static storage modifier in function 
 *                    definitions
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/* 
 * A variable defined in in c_t161_ch4_handler.c
 * for a set time. We have a alarm call set for 1 second hence the name.
 */
extern int one_second;

/* 
 * Though the prototype declares it extern, the definition of this function
 * is made static allowing the scope of 'alarm_handler' function to only
 * c_t161_ch4_handler.c
 * So when the compiler try to link, it would not see the definition of this
 * function
 */
extern void alarm_handler(int not_used);

int main()
{
    int five_seconds = 0;

    /*
     * A handler for alarm
     * To know more about these type of functions you can look into you Linux Internal link
     */
    /* Will lead to compiler error */
    signal(SIGALRM, alarm_handler);

    /* Set the alarm trigger for one second */
    alarm(1);

    /* Let the loop terminate after 5 seconds */
    while (five_seconds != 5)
    {
        /* 
         * Gets set in the 'alarm_handler' written in c_t161_ch4_handler.c
         */
        if (one_second)
        {
            /* Set the alarm trigger for one second */
            alarm(1);

            /* Reset for next count */
            one_second = 0;
            five_seconds++;
        }
    }

    printf("Five Seconds Overn");

    return 0;
}

Example output:

 

Chapter 10 : Pointers Part 2

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows use of NULL pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_161_ch5_pointer_null.c
 *   Title          : NUll Pointers - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows use of NULL pointers
 *----------------------------------------------------------------------------------------------*/

#include 
#include 
#include 

int main()
{
    /* 
     * Note here we have not assigned a valid address to the pointer yet.
     * This is sometimes referred as wild pointers
     */
    int *iptr;

    /* Accessing the uninitialized pointer could have undefined behavior */
    *iptr = 50;
    /* You might get 50 on screen */
    printf("%dn", *iptr);

    /* 
     * If you still don't have any valid address to be stored in a pointer, better
     * initialized that pointer to a value which would give a predicted value all
     * the time if accessed unknowingly
     * This can be achieved by initializing a pointer to NULL (OS dependent reserved value)
     * when accessed gives you guaranteed segmentation violation error
     */
    iptr = NULL;

    /* Will lead to segmentation fault */
    *iptr = 50;
    printf("%dn", *iptr);

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows use of void pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_162_ch5_void_pointers.c
 *   Title          : Void Pointers - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows use of void pointers
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 0x31323334;
    /*
    * The advantage of the void pointer is that we can make to point to any memory location where
    * we don't bother what is stored at the location
    */
    void *vptr = &x;

    /* 
    * As mention above the void pointer will be pointing a memory location containing just data.
    * Now while accessing the data the compiler expects us to tell how much we need
    * This has to be done by type casting the void pointer
    */
    printf("%cn", *(char *)(vptr + 0));
    printf("%cn", *(char *)(vptr + 1));
    printf("%cn", *(char *)(vptr + 2));
    printf("%cn", *(char *)(vptr + 3));

    printf("%hxn", *(short *)(vptr + 2));

    printf("%xn", *(int *)(vptr + 0));

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to use malloc.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_163_ch5_pointers_malloc.c
 *   Title          : Dynamic Memory Allocation - malloc - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use malloc
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    int *ptr;
    int i;

    /* Request 5 blocks of memory of size integer */
    ptr = (int *) malloc(5 * sizeof(int));

    if (ptr == NULL)
    {
          fprintf(stderr, "malloc: Memory not allocatedn");

          return 1;
    }

    ptr[0] = 25;
    ptr[1] = 50;
    ptr[2] = 75;
    ptr[3] = 100;
    ptr[4] = 125;

	for (i = 0; i < 5; i++)
	{
		printf("%dn", i[ptr]);
	}

    /* Make sure you free the allocated memory to avoid memory leak */
    free(ptr);
    
    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to use calloc.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_164_ch5_pointers_calloc.c
 *   Title          : Dynamic Memory Allocation - calloc - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use calloc
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    int *ptr;
    int i;

    /* Request 10 blocks of memory of size integer initialized with 0 */
    ptr = (int *) calloc(10, sizeof(int));

    if (ptr == NULL)
    {
          fprintf(stderr, "calloc: Memory not allocatedn");

          return 1;
    }

    *(ptr + 0) = 25;
    *(ptr + 1) = 50;
    *(ptr + 2) = 75;
    *(ptr + 3) = 100;
    *(ptr + 4) = 125;
  
    /* 
     * Not that the loop runs for 10 times, but we have assigned only 5 values
     * which will be initialized to 0
     */
	for (i = 0; i < 5; i++)
	{
		printf("%dn", i[ptr]);
	}

    /* Make sure you free the allocated memory to avoid memory leak */
    free(ptr);
    
    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access. Dynamic memory allocation helps us to get the memory from the heap at run time. The allocated memory can be extended or shrinked.

This example shows how to use realloc.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_165_ch5_pointers_realloc.c
 *   Title          : Dynamic Memory Allocation - realloc - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use realloc
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    int *ptr;
    int *new_ptr;

    /* Allocate 5000 * 4 (32 bit system) bytes of memory */
    ptr = (int *) malloc(5000 * sizeof(int));

    if (ptr == NULL)
    {
          fprintf(stderr, "calloc: Memory not allocatedn");

          return 1;
    }

    /* 
     * Just reallocate big chunk of memory
     * If the kernel doesn't find enough space in existing block then it would 
     * give a new memory block if possible else would fail
     */
    new_ptr = realloc(ptr, 0x80000000);

    if (new_ptr == NULL)
    {
       fprintf(stderr, "malloc: Memory not allocatedn");
    }
    else
    {
      ptr = new_ptr;
    }

    printf("Pointing to region starting from %pn", ptr);

    /* Make sure you free the allocated memory to avoid memory leak */
    free(ptr);
    
    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to use const pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_166_ch5_pointers_const.c
 *   Title          : Const Pointers- Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use const pointers
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 100;
    /* *ptr is constant */
    const int *ptr = &x;

    /* This is allowed */
    ptr++;

    /* Is not OK */
    *ptr = 5;

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to use const pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_167_ch5_pointers_const.c
 *   Title          : Const Pointers- Example 2
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use const pointers
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 100;
    /* *ptr is constant */
    int * const ptr = &x;

    /* This is not allowed */
    ptr++;

    /* This is allowed */
    *ptr = 5;

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to use const pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_168_ch5_pointers_const.c
 *   Title          : Const Pointers- Example 3
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to use const pointers
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int x = 100;
    /* Both pointer and the value it is pointing are constants */
    const int * const ptr = &x;

    /* This is not allowed */
    ptr++;

    /* This is not allowed */
    *ptr = 5;

    return 0;
}

Example output:

Chapter 11 : Pointers Part 3

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to define multilevel pointers.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_161_ch5_pointer_multi.c
 *   Title          : Multilevel Pointers - Example 1
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to define multilevel pointers
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
	int num = 10;
	/* ptr1 points to num */
	int *ptr1 = #
	/* ptr2 points to ptr1 */
	int **ptr2 = &ptr1;
	/* ptr3 points to ptr2 */
	int ***ptr3 = &ptr2;

	printf("%pn", ptr3);
	printf("%pn", *ptr3);
	printf("%pn", **ptr3);
	printf("%dn", ***ptr3);

	return 0;
}

Example output:

 

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to define multilevel pointers and passing to a function.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_170_ch5_pointer_multi.c
 *   Title          : Multilevel Pointers - Example 2
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to define multilevel pointers
 *----------------------------------------------------------------------------------------------*/

#include 

void foo(int **pptr)
{
    **pptr = 50;
}

int main()
{
    int x = 10;
    int *ptr = &x;

    foo(&ptr);

    printf("x = %dn", x);

    return 0;
}

Example output:

Brief:

The C basic data types allows us to access a limited and fixed number of the memory bytes. In order to increase the flexibility to access a range of memory bytes C supports pointers. Any variable defined as a pointer will hold an address of memory location. Have to be careful with dealing the address ranges, else would lead to illegal memory access.

This example shows how to define multilevel pointers and passing to a function and allocation of memory in it.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Wed 12 April 2017 16:00:04 IST
 *   File           : c_171_ch5_pointer_multi.c
 *   Title          : Multilevel Pointers - Example 3
 *   Description    : The C basic data types allows us to access a limited and fixed number of the 
 *                    memory bytes. In order to increase the flexibility to access a range of 
 *                    memory bytes C supports pointers.
 *                    Any variable defined as a pointer will hold an address of memory location. 
 *                    Have to be careful with dealing the address ranges, else would lead to 
 *                    illegal memory access.
 *                    This example shows how to define multilevel pointers and passing to a function 
 *                    and allocation of memory in it.
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

void alloc_mem(int **pptr, int nmemb)
{
    *pptr = (int *)malloc(nmemb * sizeof(int));
}

int main()
{
    int *ptr = NULL;

    alloc_mem(&ptr, 5);

    if (ptr == NULL)
    {
        exit(1);
    }

    printf("Allocated memoryn");

    if (ptr != NULL)
    {
        free(ptr);
        ptr = NULL;
    }

    return 0;
}

Example output:

 

Chapter 12 : 2D - Arrays

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to define a 2D array.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t172_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to define a 2D array.
 *---------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int matrix[3][4];
    int max_rows = 3, max_cols = 4;
    int row, col, count = 1;

    for (row = 0; row < max_rows; row++)
    {
        for (col = 0; col < max_cols; col++)
        {
            matrix[row][col] = count;
            count++;
        }
    }

    printf("Printing the 2D Arrayn");

    for (row = 0; row < max_rows; row++)
    {
        /* Prints a single row at a time */
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", matrix[row][col]);
        }
        /* To format the output. For next row */
        printf("n");
    }

    return 0;
}

Example output:

 

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to define a 2D array at definition.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t173_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Initialization
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to define a 2D array at definition.
 *---------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    int max_rows = 3, max_cols = 4;
    int row, col, count = 1;

    printf("Printing the 2D Arrayn");

    for (row = 0; row < max_rows; row++)
    {
        /* Prints a single row at a time */
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", matrix[row][col]);
        }
        /* To format the output. For next row */
        printf("n");
    }

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to read a 2D array.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t174_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Read for user
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to read a 2D array.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int matrix[3][4];
    int max_rows = 3, max_cols = 4;
    int row, col, count = 1;

    printf("Enter the valuesn");

    for (row = 0; row < max_rows; row++)
    {
        for (col = 0; col < max_cols; col++)
        {
            scanf("%d", &matrix[row][col]);
        }
    }

    printf("Printing the 2D Arrayn");

    for (row = 0; row < max_rows; row++)
    {
        /* Prints a single row at a time */
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", matrix[row][col]);
        }
        /* To format the output. For next row */
        printf("n");
    }

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how 2D arrays are stored in memory.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t175_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Address
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how 2D arrays are stored in memory.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int a[3][4];

    /* All addresses are same, but types are different */
    /* Base addr of 2D array */
    printf("a = %lun", a);
    /* Address of whole 2D array */
    printf("&a = %lun", &a);
    /* Address of 1st row */
    printf("&a[0] = %lun", &a[0]);
    /* Address of 1st integer element */
    printf("&a[0][0] = %lun", &a[0][0]);

    puts("--------------------------------");
    /* a[1] indicates 2nd row. */
    printf("a[1] = %lun", a[1]);
    /* Same as above */
    printf("*(a + 1) = %lun", *(a + 1));

    puts("--------------------------------");

    /* Base addr of 2D array */
    printf("a = %lun", a);
    /* 2nd row address */
    printf("a + 1 = %lun", a + 1);
    /* 2nd 2D array (&a + 1 * sizeof (a)) */
    printf("&a + 1 = %lun", &a + 1);
    /* 2nd row addr */
    printf("&a[0] + 1 = %lun", &a[0] + 1);
    /* 2nd element addr */
    printf("&a[0][0] + 1 = %lun", &a[0][0] + 1);

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to access a 2D array with pointer notation.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t176_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Access like pointer
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to access a 2D array with pointer notation.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int arr[3][4] = {
                     {1,  2,  3,  4},
                     {5,  6,  7,  8},
                     {9, 10, 11, 12}
                    };

    /* Print the array size */
    printf("sizeof(arr) = %un", sizeof(arr));

    /* Should print the row size */
    printf("sizeof(arr[0]) = %un", sizeof(arr[0]));
    printf("sizeof(*arr) = %un", sizeof(*arr));

    /* Should print the col size */
    printf("sizeof(arr[0][0]) = %un", sizeof(arr[0][0]));
    printf("sizeof(**arr) = %un", sizeof(**arr));

    printf("arr[0][0] = %dn", arr[0][0]);
    printf("**arr = %dn", **arr);

    printf("arr[2][1] = %dn", arr[2][1]);
    printf("*(*(arr + 2) + 1) = %dn", *(*(arr + 2) + 1));

    return 0;
}

Example output:

 

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to access a 2D array with pointer notation.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t177_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Array of pointers
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to access a 2D array with pointer notation.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int matrix[3][4];
    int max_rows = 3, max_cols = 4, row, col, count = 1;
    /* Array of 3 pointers to integer */
    int *ptr[3];

    for (row = 0; row < max_rows; row++)
    {
        for (col = 0; col < max_cols; col++)
        {
            matrix[row][col] = count++;
        }
    }

    /* The addres of 1st row of matrix in 1st element of array pointing to integer */
    ptr[0] = matrix[0];
    /* The addres of 2nd row of matrix in 2nd element of array pointing to integer */
    ptr[1] = matrix[1];
    /* The addres of 3rd row of matrix in 3rd element of array pointing to integer */
    ptr[2] = matrix[2];

    printf("Printing the 2D Arrayn");

    for (row = 0; row < max_rows; row++)
    {
        /* Prints a single row at a time */
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", ptr[row][col]);
            /* 
             * Can be accessed like
             * printf("%4d", *(ptr[row] + col));
             */
            /* 
             * Can be accessed like
             * printf("%4d", *(*(ptr + row) + col));
             */
        }
        /* To format the output. For next row */
        printf("n");
    }

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to access a 2D array with pointer notation.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t178_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Pointer to a array - Example 1
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to access a 2D array with pointer notation.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int a[5] = {1, 2, 3, 4, 5};
    int (*ptr)[5];
    int *ptr2 = a;
    int i = 0;

    /* Store the address of whole array */
    ptr = &a;

    printf("sizeof(ptr) = %un", sizeof(ptr));
    /* *ptr gets the entire array */
    printf("sizeof(*ptr) = %un", sizeof(*ptr));
    /* *ptr2 gets the 1st element */
    printf("sizeof(*ptr2) = %un", sizeof(*ptr2));

    /* Pointer arithmetic on ptr */
    printf("ptr = %pn", ptr);
    printf("ptr + 1 = %pn", ptr + 1);

    /* (*ptr) - Gets the entire 1D array */
    /* (*ptr)[0] - Gets 1st element from array */
    printf("(*ptr)[0]%dn", (*ptr)[0]);

    for (i = 0; i < 5; i++)
    {
        /* ith element from array */
        printf("%dn", (*ptr)[i]);
    } 
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to access a 2D array with pointer notation.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t179_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Pointer to a array - Example 2
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to access a 2D array with pointer notation.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    int arr[3][4] = {
                     {1,  2,  3,  4},
                     {5,  6,  7,  8},
                     {9, 10, 11, 12}
                    };
    /* ptr a pointer to an array of integers */
    int (*ptr)[4];
    int i = 0, j = 0;;

    /* Store the base address of array a (Analogy a => &a[0]) */
    ptr = arr;

    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 4; j++)
        {
            printf("%3d", ptr[i][j]); 
        }
        puts("");
    }

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows an example of array of strings.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t180_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Array of strings
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows an example of array of strings.
 *----------------------------------------------------------------------------------------------*/

#include 

int main()
{
    /* Array of 3 char pointers */
	char *s[3];

	s[0] = "Array";
	s[1] = "of";
	s[2] = "Strings";
	
	printf("%s %s %sn", s[0], s[1], s[2]);

	return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to pass a 2D array to a function.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t181_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Passing to functions - Example 1
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to pass a 2D array to a function.
 *----------------------------------------------------------------------------------------------*/

#include 

void print_2d_array(int max_rows, int max_cols, int arr[max_rows][max_cols])
{
    int row, col;

    for (row = 0; row < max_rows; row++)
    {
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", arr[row][col]);
        }
        printf("n");
    }
}

int main()
{
    int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    int max_rows = 3, max_cols = 4;

    printf("Printing the 2D Arrayn");
    print_2d_array(max_rows, max_cols, matrix);

    return 0;
}

Example output:

 

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to pass a 2D array to a function.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t182_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Passing to functions - Example 2
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to pass a 2D array to a function.
 *----------------------------------------------------------------------------------------------*/

#include 

/* Passed as pointer to an array */
void print_2D_array(int (*ptr)[4], int max_rows)
{
    int row, col;
    int max_cols = 4;

    printf("Printing the 2D Arrayn");

    for (row = 0; row < max_rows; row++)
    {
        for (col = 0; col < max_cols; col++)
        {
            printf("%4d", ptr[row][col]);
        }
        printf("n");
    }
}

int main()
{
    int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
    int max_rows = 3, max_cols = 4;

    print_2D_array(matrix, max_rows);

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to pass a 2D array to a function.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t183_ch5_arrays_2d.c
 *   Title          : Arrays - 2 Dimensions - Passing to functions - Example 3
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to pass a 2D array to a function.
 *----------------------------------------------------------------------------------------------*/

#include 

#define MAX_ROWS 2
#define MAX_COLS 3

/* Passing a 2D array as a 1D array */
void print_2d_array(int *ptr, int rows, int cols)
{
    int i, j;

    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            printf("%5d", *(ptr + (i * cols) + j));
        }
        puts("");
    }
}

int main()
{
    int arr[MAX_ROWS][MAX_COLS] = {{1, 2, 3}, {4, 5, 6}};

    /* Passing a 2D array as a 1D array */
    print_2d_array((int *)arr, MAX_ROWS, MAX_COLS);

    return 0;
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to create an array where the row cannot be altered.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t184_ch5_arrays_row_static.c
 *   Title          : Arrays - 2 Dimensions Creation - Row Static
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to create an array where the row cannot be altered
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    int *ra[5];
    int i, j, n_rows = 5, n_cols = 3, k = 1;

    /* Allocate each row dynamically. ie., Array of integers */
    for (i = 0; i < n_rows; i++)
    {
        ra[i] = (int *) malloc(n_cols * sizeof(int));
    }

    /* Access the 2D array */
    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            ra[i][j] = k++;
        }
    }

    /* Print array */
    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            printf("%4d", ra[i][j]);
        }
        printf("n");
    }

    /* Free cols */
    for (i = 0; i < n_rows; i++)
    {
        if (ra[i] != NULL)
        {
            free(ra[i]);
            ra[i] = NULL;
        }
    }
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to create an array where the column cannot be altered.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t185_ch5_arrays_row_static.c
 *   Title          : Arrays - 2 Dimensions Creation - Column Static
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to create an array where the column cannot be altered
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    /* Pointer to an array of 3 ints (Columns fixed) */
    int (*ra)[3];
    int i, j, n_rows = 5, n_cols = 3, k = 1;

    /* Allocate whole array dynamically */
    ra = (int (*)[3]) malloc(n_cols * n_rows * sizeof(int));

    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            ra[i][j] = k++;
        }
    }

    /* Print array */
    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            printf("%4d", ra[i][j]);
        }
        printf("n");
    }

    /* Free cols */
    if (ra != NULL)
    {
        free(ra);
        ra = NULL;
    }
}

Example output:

Brief:

An array is a collection of similar data type. Elements occupy consecutive memory locations (addresses). First element with lowest address and the last element with highest address. Elements are indexed from 0 to SIZE – 1. for example say we have an array of 5 elements(say array[5]) will be indexed from 0 to 4. Accessing out of range array elements would be “illegal access”, i.e for example do not access elements array[-1] and array[SIZE]. Array size can’t be altered at run time. Sometimes we have a situation where we have to deal with big pool of memory and need easy access we can go with multi dimensional arrays. Point to be noted is, that a multi dimensional array will be placed and can be accessed linearly.

 

This example shows how to create an array where the row and column cannot be altered.

 

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 13 Mar 2017 16:00:04 IST
 *   File           : c_t186_ch5_arrays_row_static.c
 *   Title          : Arrays - 2 Dimensions Creation - Both row and cloumn dynamic
 *   Description    : An array is a collection of similar data type. Elements occupy consecutive 
 *                    memory locations (addresses). First element with lowest address and the last 
 *                    element with highest address. Elements are indexed from 0 to SIZE – 1. 
 *                    for example say we have an array of 5 elements(say array[5]) will be indexed 
 *                    from 0 to 4. Accessing out of range array elements would be “illegal access”,
 *                    i.e for example do not access elements array[-1] and array[SIZE]. 
 *                    Array size can't be altered at run time.
 *
 *                    Sometimes we have a situation where we have to deal with big pool of memory 
 *                    and need easy access we can go with multi dimensional arrays. Point to be 
 *                    noted is, that a multi dimensional array will be placed and can be accessed 
 *                    linearly.
 *
 *                    This example shows how to create an array where the row and column cannot 
 *                    be altered
 *----------------------------------------------------------------------------------------------*/

#include 
#include 

int main()
{
    int **ra;
    int i, j, n_rows = 5, n_cols = 3, k = 1;

    /* Allocate rows (array of pointers) dynamically */
    ra = (int **) malloc(n_rows * sizeof(int *));

    /* Allocate cols (1D int array) dynamically, for each row */
    for (i = 0; i < n_rows; i++)
    {
        ra[i] = (int *) malloc(n_cols * sizeof(int));
    }

    /* Access the 2D array */
    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            ra[i][j] = k++;
        }
    }

    /* Print array */
    for (i = 0; i < n_rows; i++)
    {
        for (j = 0; j < n_cols; j++)
        {
            printf("%4d", ra[i][j]);
        }
        printf("n");
    }

    /* Free cols */
    for (i = 0; i < n_rows; i++)
    {
        if (ra[i] != NULL)
        {
            free(ra[i]);
            ra[i] = NULL;
        }
    }

    /* Free rows */
    if (ra != NULL)
    {
        free(ra);
        ra = NULL;
    }

    return 0;
}

Example output:

Chapter13 : Functions - Part 4

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This program illustrates how to use the command line argument.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t187_ch5_functions_cmd_line.c
 *   Title          : Functions - Command Line Arguments - Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This program illustrates how to use the command line argument
 *-----------------------------------------------------------------------------------------------*/ 

#include 

/* 
 * argc (argument count)  - Contains number of arguments including program name
 * argv (argument vector) - Contains the actual arguments.
 * argv[0] is the program name
 */

int main(int argc, char *argv[])
{
    int i;

    printf("No of args = %dn", argc);

    puts("List of arguments");

    for (i = 0; i < argc; i++)
    {
        printf("%d: %sn", i, argv[i]);
    }

    return 0;
}
 

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This program illustrates how to use the command line argument.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t188_ch5_functions_cmd_line.c
 *   Title          : Functions - Command Line Arguments - Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This program illustrates how to use the command line argument
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

static void usage(char *program)
{
    printf("Usage:n");
    printf("%s   ..... n", program);

    exit(1);
}

int main(int argc, char *argv[])
{
    int i, sum = 0;

    if (argc == 1)
    {
        usage(argv[0]);
    }

    for (i = 1; i < argc; i++)
    {
        sum += atoi(argv[i]);
    }

    printf("average = %fn", (double) sum / (argc - 1));

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This program illustrates how to use the function pointers.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t189_ch5_function_pointers.c
 *   Title          : Functions Pointers -  Example 1
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This program illustrates how to use the function pointers
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

int main()
{
    int res;
    int (*fptr)(int, int);

    /* Assign add functions address */
    fptr = &add;

    /* Invoke add function */
    res = (*fptr)(5, 10);
    printf("res = %dn", res);

    /* Assign sub function address */
    fptr = sub;
    /* Call sub func. Notice that u need not derefence fptr */
    res = fptr(5, 10);

    printf("res = %dn", res);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.


’atexit’ is used to register a function to be called at normal process termination.
my_exit will get called before the program terminates.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t190_ch5_function_pointers.c
 *   Title          : Functions Pointers -  Example 2
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    'atexit' is used to register a function to be called at normal process 
 *                    termination. my_exit will get called before the program terminates.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

void my_exit(void)
{
    printf("Exiting programn");
}

int main()
{
    /* Registering my_exit function */
    atexit(my_exit);

    exit(1);

    puts("Before Exit");
    
    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This example shows how to pass function pointer as an argument to function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t191_ch5_function_pointers.c
 *   Title          : Functions Pointers -  Example 3
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This example shows how to pass function pointer as an argument to function.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int addition(int a, int b)
{
    return a + b; 
}

int subtraction(int a, int b)
{
    return a - b;
}

int operation (int x, int y, int (*functocall)(int,int))
{
    int g;

    g = functocall(x,y);

    return g;
}

int main ()
{
    int m,n;
    int (*minus)(int, int) = subtraction;

    m = operation (7, 5, addition);
    n = operation (20, 5, minus);

    printf("%d %dn", m, n);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This example shows usage of function pointer using qsort builtin function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t192_ch5_function_pointers.c
 *   Title          : Functions Pointers -  Example 4
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This example shows usage of function pointer using qsort builtin function.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int sort_ascending(const void *a, const void *b)
{
    return *(int *)a > *(int *)b;
}

int sort_descending(const void *a, const void *b)
{
    return *(int *)a < *(int *)b;
}

int sort_string(const void *a, const void *b)
{
    return strcmp(*(char **)a, *(char **)b);
}

void print_int_array(int *arr, unsigned int size)
{
    int i = 0;

    for (i = 0; i < size; i++)
    {
        printf("%dn", arr[i]);
    }
}

void print_str_array(char **arr, unsigned int size)
{
    int i = 0;

    for (i = 0; i < size; i++)
    {
        printf("%sn", arr[i]);
    }
}

int main(void)
{
    int array1[5] = { 9, 2, 6, 1, 7 };
    char *str_array1[] = {"hello", "apple", "zebra", "india", "cricket" };
    size_t strings_len = sizeof(str_array1) / sizeof(char *);
    int size = 5;
    int i = 0;

    qsort(array1, size, sizeof(int), sort_ascending);
    printf("Ascendingn");
    print_int_array(array1, size);

    qsort(array1, size, sizeof(int), sort_descending);
    printf("Descendingn");
    print_int_array(array1, size);

    i = strings_len + 1;

    qsort(str_array1, strings_len, sizeof(char *), sort_string);
    printf("nString sortn");
    print_str_array(str_array1, strings_len);

    return 0;
}

Example output:

Brief:

We generally encounter a situation where we end up writing the same code again and again leading up to a question, can we avoid this some how?, Yes, the answer is functions. Technically a function be called as group of instructions written to do a specific functionality (hence called as function). Using functions we can achieve many advantages like Re usability, Divide and conquer, Modularity, Testability, Abstraction and many more.

 

This example shows how to use Variable argument function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t193_ch5_function_var_arg.c
 *   Title          : Functions - Variable Arguments
 *   Description    : We generally encounter a situation where we end up writing the same code 
 *                    again and again leading up to a question, can we avoid this some how?, 
 *                    Yes, the answer is functions. Technically a function be called as group of 
 *                    instructions written to do a specific functionality (hence called as
 *                    function).
 *                    Using functions we can achieve many advantages like  Re usability, Divide 
 *                    and conquer, Modularity, Testability, Abstraction and many more.
 *
 *                    This example shows how to use Variable argument fuction.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

double calc_mean(int no_of_args, ...)
{
    va_list ap;
    double temp, sum = 0;
    int i;

    va_start(ap, no_of_args);

    for (i = 0; i < no_of_args; i++)
    {
        /* Fetch the next argument (of double type) */
        temp = va_arg(ap, double);
        sum += temp;
    }
    
    va_end(ap);

    return (sum / no_of_args);
}

int main()
{
    double res; 

    res = calc_mean(3, 3.0, 4.0, 5.0);
    printf("avg = %lfn", res);

    res = calc_mean(2, 1.0, 2.0);
    printf("avg = %lfn", res);

    return 0;
}

Example output:

Chapter 14 : Preprocessing

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to include a header file and its search path.

 

char *test(void);

Preprocessor header:

char *test(void)
{
    static char *str = "Hello";

    return str;
}

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t194_ch6_preprocessor_header_1.c
 *   Title          : Preprocessors - Search Path
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to include a header file and its search path.
 *-----------------------------------------------------------------------------------------------*/ 

/* Any header file we put in angular brackets will be searched in standard path */
#include 
/* Any header file we put in "" will be searched in current directory or the given path */
#include "c_t194_ch6_preprocessor_header_2.h"

int main()
{
	puts(test());

	return 0;
}

Example output:

 

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to include a header file and its search path.

 

Preprocessor header File 1:

#ifndef PERSON_H
#define PERSON_H

struct Person
{
    int id;
    char name[30];
};

#endif

Preprocessor header File 2:

struct Dummy
{
    int id;
    char name[30];
};

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t194_ch6_preprocessor_header_1.c
 *   Title          : Preprocessors - Search Path
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to include a header file and its search path.
 *-----------------------------------------------------------------------------------------------*/ 

/* This header file will be included only once because of #ifndef */
#include "c_t195_ch6_preprocessor_header_1.h"
#include "c_t195_ch6_preprocessor_header_1.h"
/* This header file will be included the number of times it is included */
#include "c_t195_ch6_preprocessor_header_2.h"
#include "c_t195_ch6_preprocessor_header_2.h"

int main()
{
    struct Person p = {1, "Emertxe"};

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to define a object like macro.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t196_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Object Like
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to define a object like macro.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define NUM			100
#define STRING		"Hello World"

int main()
{
    /* These macro will get replaced as is */
	printf("%dn", NUM);
	printf("%sn", STRING);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to define a macros with arguments.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t197_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Arguments
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to define a macros with arguments.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define SQUARE(x) x * x

int main()
{
    int a = 2, res;

    res = SQUARE(a);
    printf("res = %dn", res);

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to define a macros with arguments, its pitfalls.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t198_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Arguments
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to define a macros with arguments, its pitfalls.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define SQUARE(x) x * x

int main()
{
    int a = 2, b = 2, res;

    /* The precedence rule has to be applied here */
    res = SQUARE(a + b);
    printf("res = %dn", res);

    /* The precedence rule has to be applied here */
    res = SQUARE(5 + 5);
    printf("res = %dn", res);

    /* So group it with parenthesis */
    res = SQUARE((5 + 5));
    printf("res = %dn", res);

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to define a macros with arguments and they are not type specific.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t199_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Arguments
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to define a macros with arguments and they are not 
 *                   type specific
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define SUM(x, y) ((x) + (y))

int main()
{
	int a = 5, b = 10, res1;
	float val1 = 2.5f, val2 = 3.0f, res2;

	/* Macros are not type specific */
	res1 = SUM(a, b);
	res2 = SUM(val1, val2);

	printf("res1 = %dn", res1);
	printf("res2 = %fn", res2);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This file shows how to define a macros with can span across multiline.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t200_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Multiline
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This file shows how to define a macros with can span across multiline.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define SWAP(a, b)		
{						
    int temp = a;		
    a = b;				
    b = temp;			
}

int main()
{
    int x = 5, y = 10;

    SWAP(x, y)
    printf("x = %d, y = %dn", x, y);

    SWAP(x, y)
    printf("x = %d, y = %dn", x, y);

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This example shows how a macro argument can be converted into a string.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t201_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Stringification - Example 1
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be converted into a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define WARN_IF(EXP)								
do													
{													
	x--;											
	if (EXP)										
	{												
		fprintf(stderr, "Warning: " #EXP "n");		
	}												
} while (x)

int main()
{
	int x = 5;

	WARN_IF (x == 0);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This example shows how a macro argument can be converted into a string.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t202_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Stringification - Example 2
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be converted into a string.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define PRINT(expr) printf(#expr " is %dn", expr)

int main()
{
    int x, y = 5, z = 10, a = 50, b = 12, c = 100;

    PRINT(x = y + c * (a / z) % y);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,
– Easy Development
– Readability
– Portability
This example shows how a macro argument can be used to concatinated.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t203_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Concatination
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how a macro argument can be used to concatinated.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define CAT(x) (x##_val)

int main()
{
	int int_val = 4;
	float float_val = 2.54;

	printf("int val = %dn", CAT(int));
	printf("float val = %fn", CAT(float));

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t204_ch6_preprocessor_macros.c
 *   Title          : Preprocessors - Macros - Standard Predefined
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows some standard predefined macros.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
	printf("Program: "%s" ", __FILE__);
	printf("was compiled on %s at %s. ", __DATE__, __TIME__);
	printf("This print is from Function: "%s" at line %dn", __func__, __LINE__);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use ifdef, undef.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t205_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 1
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use ifdef, undef.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define DEBUG_PRINT

int main()
{
	int sum, num1, num2;

	printf("Enter 2 numbers: ");
	scanf("%d %d", &num1, &num2);

#ifdef DEBUG_PRINT
    printf("1 The entered values are %d %dn", num1, num2);
#endif

#undef DEBUG_PRINT
#ifdef DEBUG_PRINT
    printf("2 The entered values are %d %dn", num1, num2);
#endif

	sum = num1 + num2;
    printf("The sum is %dn", sum);

    return 0;
}

Example output:

 

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use ifdef, undef.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t206_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 2
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use ifdef, undef.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define METHOD1 1

int main()
{
#ifdef METHOD1
    puts("Hello World");
#else
    printf("Hello World");
#endif

    return 0;
}

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use ifdef, ifndef.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t207_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 3
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use ifdef.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define SPACE_OPTIMIZED

int main()
{
    int x = 10, y = 20, temp;

#ifndef SPACE_OPTIMIZED
    temp = x;
    x = y;
    y = temp;

    printf("Time optimization selected. x = %d and y = %dn", x, y);
#else
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;

    printf("Space optimization selected. x = %d and y = %dn", x, y);
#endif

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use define a macro using command line.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t208_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 4
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use define a macro using command line.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

/* Use -D option to define the macro */

int main()
{
    int x, y, temp;

#ifdef SPACE_OPTIMIZED
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
	printf("Selected Space Optimizationn");
#else
    temp = x;
    x = y;
    y = temp;
	printf("Selected Time Optimizationn");
#endif

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use variable arguments to a macro.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t209_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 5
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use variable arguments to a macro.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#if (DEBUG == 1)
#define ERR_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#define WARN_PRINT(args...)
#define DBG_PRINT(args...)
#elif(DEBUG == 2)
#define ERR_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#define WARN_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#elif(DEBUG == 3)
#define ERR_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#define WARN_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#define DBG_PRINT(args...)		printf("Line %d: File %s: ", __LINE__, __FILE__); printf(args)
#else
#warning "DEBUG macro is not set. Please define it"
#define ERR_PRINT(args...)
#define WARN_PRINT(args...)
#define DBG_PRINT(args...)
#endif

int main()
{
	ERR_PRINT("This is error %dn", 3);
	DBG_PRINT("This is infon");
	WARN_PRINT("This is warning %dn", 1);

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use commented code.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t210_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 6
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to use commented code.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
#if 0
    printf("I am removed while preprocessingn");
#else
    printf("I am retained while preprocessingn");
#endif

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to redefine a macro.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t211_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 7
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to redefine a macro.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#ifdef BUFSIZ
#undef BUFSIZ
#endif

#define BUFSIZ 1024

int main()
{
    char buf[BUFSIZ];

	printf("Size of buf is %un", sizeof(buf));

    return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to #warning.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t212_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 8
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to #warning.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define WARNING		1

#if defined (WARNING)
#warning "Do you want to proceed further with compilation?"
#endif

int main()
{
	printf("Testing #if definedn");

	return 0;
}

Example output:

Brief:

One of the step performed before compilation. Is a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. Instructions given to preprocessor are called preprocessor directives and they begin with “#” symbol. Few advantages of using preprocessor directives would be,

– Easy Development
– Readability
– Portability

This example shows how to use #error.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t213_ch6_preprocessor_condtional.c
 *   Title          : Preprocessors - Conditional Compilation - Example 9
 *   Description    : One of the step performed before compilation. Is a text substitution tool 
 *                    and it instructs the compiler to do required pre-processing before the 
 *                    actual compilation. 
 *                    Instructions given to preprocessor are called preprocessor directives and 
 *                    they begin with “#” symbol.
 *                    Few advantages of using preprocessor directives would be,
 *                     - Easy Development
 *                     - Readability
 *                     - Portability 
 *              
 *                   This example shows how to #error.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

#define ERROR		1

#if (defined ERROR)
#error "Can't to proceed further with compilation"
#endif

int main()
{
	printf("Testing #if definedn");

	return 0;
}

Example output:

 

Chapter 15 : UDTs

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

-Structures
– Unions
– Typedef
– Enums

This file shows how to structures, pointer to structures and passing it functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t214_ch7_udt_struct.c
 *   Title          : UDTs - Structures - Example 1
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to structures, pointer to structures and passing it 
 *                    functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/*
 * Create a structure type
 * Name of the type is struct student (Not just student)
 */
struct student
{
    int id;
    char name[30];
    char addr[150];
};

void print_stud_info1(struct student stud);
void print_stud_info2(const struct student *stud_ptr);

void print_stud_info1(struct student stud)
{
    puts("******** Student Info ********");
    printf("id = %dn", stud.id);
    printf("Name = %sn", stud.name);
    printf("Address = %sn", stud.addr);
}

void print_stud_info2(const struct student *stud_ptr)
{
    puts("******** Student Info ********");
    printf("id = %dn", stud_ptr->id);
    printf("Name = %sn", stud_ptr->name);
    printf("Address = %sn", stud_ptr->addr);
}

int main()
{
    /* s1 is a variable of type struct student */
    struct student s1;
    /* Initialize the fields */
    struct student s2 = {20, "student 1", "MG Road"};
    struct student *sptr;

    sptr = &s2;

    s1.id = 10;
    strcpy(s1.name, "student 2");
    strcpy(s1.addr, "MG Road");

    /* Print by invoking functions */
    print_stud_info1(s1);
    print_stud_info2(&s2);

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

-Structures
– Unions
– Typedef
– Enums

This file shows how to define un named structures.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t215_ch7_udt_struct.c
 *   Title          : UDTs - Structures - Example 2
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to define un named structures.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/* 
 * Example of struct datatype without a name This is generally used if you are creating
 * only one instance of the struct. i.e, Only one variable
 */
struct
{
    int id;
    char name[30];
    char addr[150];
} stud, another_stud; /* stud, another_stud are variables, of the unnamed struct */

int main()
{
    stud.id = 1;
    strcpy(stud.name, "Mubeen");

    printf("id = %dn", stud.id);

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

-Structures
– Unions
– Typedef
– Enums

This file shows issues of structure padding.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t215_ch7_udt_struct.c
 *   Title          : UDTs - Structures - Example 2
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows issues of structure padding.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

struct Student
{
    int age; /* int is 4 bytes long */
    char ch1;
    char ch2;
};

struct MyData
{
    short Data1;
    short Data2;
    short Data3;
};

int main()
{
    printf("%un", sizeof(struct Student));
    printf("%un", sizeof(struct MyData));

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to define and use structure bit fields.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t217_ch7_udt_struct_bitfields.c
 *   Title          : UDTs - Structures - Bitfields
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to define and use structure bit fields.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

struct IeeeFormat
{
    unsigned int m : 23;
    unsigned int e : 8;
    unsigned int s : 1;
};


int main()
{
    struct IeeeFormat fb;
    float *sptr = (float *) &fb;

    *sptr = 3.2;

    printf("Sign: %Xn", fb.s);
    printf("Exponent: %Xn", fb.e);
    printf("Mantissa: %Xn", fb.m);

    *sptr = -3.2;

    printf("Sign: %Xn", fb.s);
    printf("Exponent: %Xn", fb.e);
    printf("Mantissa: %Xn", fb.m);

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to use unions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t218_ch7_udt_unions.c
 *   Title          : UDTs - Unions - Example 1
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to use unions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

/* Create a union type named register_data */
union register_data
{
    int reg32;
    char byte[4];
};

int main()
{
    /* Instantiate union, creates a variable named "r" */
    union register_data r;

    printf("sizeof(r) = %un", sizeof(r));
    printf("%p %p %pn", &r, &r.reg32, &r.byte);

    r.reg32 = 0x12345678;

    /* Access the int */
    printf("r.reg32 = %xn", r.reg32);
    /* Access a byte (Depends on Endianness) */
    printf("r.byte[0] = %xn", r.byte[0] & 0xFF);

    /* Modify Byte */
    r.byte[0] = 0x99;
    /* Access the int */
    printf("r.reg32 = %xn", r.reg32);
    /* Access a byte */
    printf("r.byte[0] = %xn", r.byte[0] & 0xFF);

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to use unions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t219_ch7_udt_unions.c
 *   Title          : UDTs - Unions - Example 2
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to use unions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

typedef union 
{
    float f;
    struct {
        unsigned int mantissa:23;
        unsigned int exponent:8;
        unsigned int negative:1;
    } IeeeFloat;
}FloatUnion;

int main()
{
    unsigned int mantissa, exponent, negative;
    FloatUnion val;

    printf("Float? ");
    scanf("%f", &(val.f));

    printf("val = %Xn", *(int *)&val.f);

    negative = val.IeeeFloat.negative;
    exponent = val.IeeeFloat.exponent;
    mantissa = val.IeeeFloat.mantissa;

    printf("float    = %.32fn", val.f);
    printf("sign     = 0x%Xn", negative);
    printf("mantissa = 0x%Xn", mantissa);
    printf("exponent = %Xn", exponent);

    return(0);
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to use enums.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t220_ch7_udt_unions.c
 *   Title          : UDTs - Enums
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to use enums.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

enum color {black, white = 5, orange, red, blue};
enum status {st_ok, st_cancel, st_retry};

int main()
{
    enum color c, d;

    printf("c = %dn", c);
    c = black;
    printf("c = %dn", c);

    printf("black = %d, white = %d, orange = %d, red = %d, blue = %dn",
            black, white, orange, red, blue);

    if (c == white)
    {
        printf("Color is whiten");
    }
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to define and use typedefs.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t221_ch7_udt_unions.c
 *   Title          : UDTs - Typedefs - Example 1
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to define and use typedefs.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

typedef enum
{
    e_false = 0,
    e_true
} Bool;

int main()
{
    Bool status = e_false;

    if (status == e_true)
    {
        puts("Condition is true");
    }
    else
    {
        puts("Condition is false");
    }

    return 0;
}

Example output:

Brief:

Sometimes it becomes tough to build a whole software that works only with integers, floating values, and characters. In circumstances such as these, you can create your own data types which are based on the standard ones. There are some mechanisms for doing this in C:

– Structures
– Unions
– Typedef
– Enums

This file shows how to define and use typedefs.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Fri 14 April 2017 16:00:04 IST
 *   File           : c_t222_ch7_udt_unions.c
 *   Title          : UDTs - Typedefs - Example 2
 *   Description    : Sometimes it becomes tough to build a whole software that works only with 
 *                    integers, floating values, and characters.
 *                    In circumstances such as these, you can create your own data types which 
 *                    are based on the standard ones.
 *                    There are some mechanisms for doing this in C:
 *                     - Structures
 *                     - Unions
 *                     - Typedef
 *                     - Enums
 *                    This file shows how to define and use typedefs.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

/* 
 * Create a structure type
 * Name of the type is struct student (Not just student)
 */
struct student
{
    int id;
    char name[30];
    char addr[150];
};

/* Create a new type StudentInfo */
typedef struct student StudentInfo;

static void print_stud_info1(StudentInfo stud);

static void print_stud_info1(StudentInfo stud)
{
    printf("id = %dn", stud.id);
    printf("name = %sn", stud.name);
    printf("addr = %sn", stud.addr);
}

int main()
{
    StudentInfo s1 = {10, "Student 1", "Bangalore"};

    printf("id = %dn", s1.id);
    printf("name = %sn", s1.name);
    printf("addr = %sn", s1.addr);

    return 0;
}

Example output:

Chapter 16 : File IO

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the fopen and fclose functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t223_ch8_file_io.c
 *   Title          : File IO - Example 1
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates the fopen and fclose functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    FILE *input_fp;

    input_fp = fopen("/etc/passwd", "r");

    if (input_fp == NULL)
    {   
        printf("Unable to open filen");

        return 1;
    }

    printf("File opened successfullyn");

    fclose(input_fp);

    return 0;
}

Example output:

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

This programs demonstrates the fgetc, fputc and feof functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t224_ch8_file_io.c
 *   Title          : File IO - Example 2
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates the fgetc, fputc and feof functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    FILE *fptr;
    char ch; 

    fptr = fopen("/etc/shells", "r");

    /* Need to do error checking on fopen() */

    while (ch = fgetc(fptr))
    {
        if (feof(fptr))
        {
            break;
        }

        fputc(ch, stdout);
    }

    fclose(fptr);

    return 0;
}

Example output:

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the ferror and clearerr functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t225_ch8_file_io.c
 *   Title          : File IO - Example 3
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates the ferror and clearerr functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    FILE *fptr;
    char ch; 

    fptr = fopen("file.txt", "w"); 

    ch = fgetc(fptr);/* This should fail since reading a file in write mode*/
    if (ferror(fptr))
    {
        fprintf(stderr, "Error in reading from file : file.txtn");
    }

    clearerr(fptr);

    /* This loop should be false since we cleared the error indicator */
    if (ferror(fptr))
    {
        fprintf(stderr, "Error in reading from file : file.txtn");
    }

    fclose(fptr);

    return 0;
}

Example output:

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the ftell functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t226_ch8_file_io.c
 *   Title          : File IO - Example 4
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates the ftell functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 
#include 

int main()
{
    FILE *fptr;
    char ch; 

    fptr = fopen("/etc/shells", "r");

    /* Need to do error checking on fopen() */

    printf("File offset is at -> %ldnn", ftell(fptr));
    printf("--> The content of file is <--n"); while ((ch = fgetc(fptr)) != EOF) { fputc(ch, stdout); } printf("nFile offset is at -> %ldn", ftell(fptr));

    fclose(fptr);

    return 0;
}

Example output:

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the fprintf, fscanf and rewind.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t227_ch8_file_io.c
 *   Title          : File IO - Example 5
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates fprintf, fscanf and rewind.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int num1, num2;
    float num3;
    char str[10], oper, ch;
    FILE *fptr;

    if ((fptr = fopen("text.txt", "w+")) == NULL)
    {   
        fprintf(stderr, "Can't open input file text.txt!n");
        return 1;
    }

    fprintf(fptr, "%d %c %d %s %fn", 2, '+', 1, "is", 1.1);
    rewind(fptr);
    fscanf(fptr, "%d %c %d %s %f", &num1, &oper, &num2, str, &num3);

    printf("%d %c %d %s %fn", num1, oper, num2, str, num3);

    fclose(fptr);

    return 0;
}

Example output:

 

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the fseek function.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t228_ch8_file_io.c
 *   Title          : File IO - Example 6
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates fseek function.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

int main()
{
    int num1, num2;
    float num3;
    char str[10], oper, ch;
    FILE *fptr;

    if ((fptr = fopen("text.txt", "w+")) == NULL)
    {   
        fprintf(stderr, "Can't open input file text.txt!n");
        return 1;
    }   

    fprintf(fptr, "%d %c %d %s %fn", 2, '+', 1, "is", 1.1);
    fseek(fptr, 0L, SEEK_SET);
    fscanf(fptr, "%d %c %d %s %f", &num1, &oper, &num2, str, &num3);

    printf("%d %c %d %s %fn", num1, oper, num2, str, num3);

    fclose(fptr);

    return 0;
}

Example output:

Brief:

Sequence of bytes, Could be regular or binary file Why?
Persistent storage
Theoretically unlimited size
Flexibility of storing any type data
C abstracts all file operations into operations on streams of bytes, which may be “input streams” or “output streams”
No direct support for random-access data files
To read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

 

This programs demonstrates the fwrite and fread functions.

 

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Mon 17 April 2017 16:00:04 IST
 *   File           : c_t229_ch8_file_io.c
 *   Title          : File IO - Example 7
 *   Description    : Sequence of bytes, Could be regular or binary file Why?
 *                    Persistent storage
 *                    Theoretically unlimited size
 *                    Flexibility of storing any type data
 *                    C abstracts all file operations into operations on streams of bytes, which 
 *                    may be "input streams" or"output streams"
 *                    No direct support for random-access data files
 *                    To read from a record in the middle of a file, the programmer must create 
 *                    a stream, seek to the middle of the file, and then read bytes in sequence 
 *                    from the stream
 *
 *                    This programs demonstrates fwrite and fread functions.
 *-----------------------------------------------------------------------------------------------*/ 

#include 

struct Data
{
    int num1;
    char oper;
    int num2;
    char str[10];
    float num3;
};

int main()
{
    struct Data d1 = {2, '+', 1, "is", 1.1};
    struct Data d2;
    FILE *fptr;

    if ((fptr = fopen("text.txt", "w+")) == NULL)
    {   
        fprintf(stderr, "Can't open input file text.txt!n");
        return 1;
    }

    fwrite(&d1, sizeof(d1), 1, fptr);
    rewind(fptr);
    fread(&d2, sizeof(d2), 1, fptr);

    printf("%d %c %d %s %fn", d2.num1, d2.oper, d2.num2, d2.str, d2.num3);

    fclose(fptr);

    return 0;
}

Example output: