Q
Advanced C Programming | Sample Programs
Home » Embedded Systems » 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. These sample programs typically demonstrated in a classroom will ensure you are able to immediately see it running in front of your eyes. Added to that our mentors will provide you some exercises where you will be modifying the code in the class itself. By doing this fill-in-the-blanks approach, will take out your fear of coding and become an expert.

Brief:

Added:

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.

Added:

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:

Added:

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:

Added:

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 <stdio.h>
 
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:

Added:

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

Added:

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 <stdio.h>

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:

Added:

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

Added:

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 <stdio.h>

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:

Added:

Added:

Brief:

Added:

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

Added:

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 <stdio.h>
 
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:

Added:

Added:

Brief:

Added:

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

Added:

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 <stdio.h>
 
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:

Added:

Added:

Brief:

Added:

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

Added:

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 <stdio.h>
 
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:

Added:

Brief:

Added:

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

Added:

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 <stdio.h>
 
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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

Source Code:

/*------------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 08 Mar 2016 16:00:04 IST
 *   File           : c_t021_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 <stdio.h>

int main()
{
    char user_input;

    printf("Enter an alphabet [Please enter lower case]: ");
    scanf("%c", &user_input);

    switch (user_input)
    {
        /* This is called as fall through */
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("%c is an voweln", user_input);
            break;
        default:
            printf("%c is not a voweln", user_input);
            break;
    }

    return 0;
}

Example output:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 09 Mar 2016 16:00:04 IST
 *   File           : c_t032_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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

Source Code:

/*----------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://emertxe.com) 
 *   Date           : Wed 9 Mar 2016 16:00:04 IST
 *   File           : c_t040_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 <stdio.h>

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

    /* 
     * sizeof returns unsigned value. Comparing a signed and
     * unsigned value yields to type promotion. Signed type
     * gets converted to unsigned. Here -1 becomes a big positive
     * value. Hence comparison fails.
     * In short (-1 < 4u) is false.
     */
    for (i = -1; i < sizeof(array) / sizeof(int) - 1; i++)
    {
        printf("%dn", array[i + 1]);
    }

    printf("Please do see the next example for solutionn");

    return 0;
}

Example output:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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. Added:

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 <stdio.h>

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

    if ((a > b) && (b < c))
    {
        puts("Yes");
    }
    else
    {
        puts("No");
    }

    return 0;
}

Example output:

Added:

Brief:

Added:

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. Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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. Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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).

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

/* 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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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).

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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

    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:

Added:

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.

Added:

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t085_ch3_array_interpretations.c
 *   Title          : Pointer Basics - Array Interpretation
 *   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 different interpretation of an array by the compiler.
 *-------------------------------------------------------------------------------------------*/

#include <stdio.h>

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

	/* 
	 * This is the first interpretation by the compiler as a whole array
	 * The size of the array would be (size of int) * (number of array elements)
	 * Note: We have one more case, which we will see while doing pointer arithmetic
	 */
	printf("The size of a is %dn", sizeof(a));

    int *ptr;

	/* 
	 * 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
	 * Note: We have one more case, which we will see while passing an array to function
	 */
    ptr = a;
    printf("a = %pn", a);

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t086_ch3_array_arithmetic.c
 *   Title          : Pointer Basics - Array Arithmetic - 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 
 *                    demonstrates arithmetic operations on pointers.
 *-------------------------------------------------------------------------------------------*/

#include <stdio.h>

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

    /* 
     * 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;

    printf("ptr = %p, &a = %pn", ptr , &a);

    /*
     * Adding or substracting 1 results in the following compiler interpretation 
     * ptr = ptr + 1 * sizeof(datatype)
     * ptr = ptr + 1 * sizeof(int)
     * ptr = ptr + 4
     * Hence from the above lines we should note that the data type of pointers not only
     * helps in derefencing but also in arithmetic
     */
    ptr = ptr + 1;
    printf("ptr = %pn", ptr);

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

Source Code:

/*-------------------------------------------------------------------------------------------- 
 *   Author         : Emertxe (https://www.emertxe.com) 
 *   Date           : Thu 23 Mar 2016 16:00:04 IST
 *   File           : c_t087_ch3_array_interpretations.c
 *   Title          : Pointer Basics - Array Arithmetic - 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 
 *                    demonstrates arithmetic operations on pointers.
 *-------------------------------------------------------------------------------------------*/

#include <stdio.h>

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

    /* 
     * 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;

    printf("*ptr = %dn", *ptr);

    /*
     * Adding or subtracting 1 results in the following compiler interpretation 
     * ptr = ptr + 1 * sizeof(datatype)
     * ptr = ptr + 1 * sizeof(int)
     * ptr = ptr + 4
     * Hence from the above lines we should note that the data type of pointers not only
     * helps in dereferencing but also in arithmetic
     */
    ptr = ptr + 1;
    printf("*ptr = %dn", *ptr);

    /* The below lines shows the dereferencing with pointer arithmetic */
    printf("*(ptr + 3) = %dn", *(ptr + 3));

    /* 
     * The above line doesn't change the address in the pointer variable hence we
     * get back the first element of the array
     */
    printf("*ptr = %dn", *ptr);

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Brief:

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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..

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

/*
 * 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:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

/*
 * 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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

/* 
 * 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:

Brief:

Added:

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)).

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

/* 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:

Added:

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.

Added:

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 <stdio.h>

/* 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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Brief:

Added:

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.

Added:

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:

Added:

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.

Added:

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 <stdio.h>
/* Header file containing the declaration for sqrt function */
#include <math.h>

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:

Added:

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
.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Brief:

Added:

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

Added:

This program shows the usage of getchar and putchar functions.

Added:

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 <stdio.h>
/* For character classification routines */
#include <ctype.h>

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:

Added:

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

Added:

This program shows the usage of getchar and putchar functions.

Added:

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 <stdio.h>
#include <ctype.h>

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:

Added:

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

Added:

This program shows the difference between gets and fgets.

Added:

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 <stdio.h>

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:

Added:

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

Added:

This program shows different type specifiers to format the output.

Added:

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 <stdio.h>

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:

Added:

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

Added:

This program shows different width specifiers to format the output.

Added:

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 <stdio.h>

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:

Added:

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

Added:

This program shows different length specifiers to format the output.

Added:

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 <stdio.h>

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

	printf("%Lfn", 1.23456789L);

	return 0;
}

Example output:

Brief:

Added:

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

Added:

This program shows different flag specifiers to format the output.

Added:

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 <stdio.h>

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:

Added:

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

Added:

This program shows different precision specifiers to format the output.

Added:

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 <stdio.h>

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:

Added:

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

Added:

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

Added:

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 <stdio.h>

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:

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This program shows how to scan different data types from user

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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 memoryThis program demonstartes the return value of printf and how it is important to find its failure.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

int main()
{
    char ch;

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

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

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>

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

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

Example output:

Brief:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <unistd.h>

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

Example output:

Brief:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <unistd.h>

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

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <unistd.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <unistd.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <stdio_ext.h>
#include <unistd.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <stdio_ext.h>
#include <unistd.h>

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:

Added:

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.

Added:

This program demonstrates when output buffer get cleared.

Added:

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 <stdio.h>
#include <stdio_ext.h>
#include <unistd.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>
#include <stdlib.h>

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:

Brief:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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 behaviour of compiler in allocating the memory to a string based on different methods.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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

    return 0;
}

Example output:

Brief:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <ctype.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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 <stdio.h>
#include <string.h>

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:

Added:

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.

Added:

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 <stdio.h>

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:

Brief:

Added:

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

Added:

This program demonstrates the use register modifier on variables.

Added:

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 <stdio.h>

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:

Added:

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

Added:

This program demonstrates the use register modifier on variables.

Added:

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 <stdio.h>

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

	return 0;
}

Example output:

Brief:

Added:

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

Added:

This program demonstrates the use register modifier on variables.

Added:

Source Code:

/*------------------------------------------------------------------------------------------------ 
 *   Author         : Emertxe (https://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:

Added:

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

Added:

This program demonstrates the use global variable.

Added:

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 <stdio.h>
#include <unistd.h>

/*
 * 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:

Added:

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

Added:

This program demonstrates the use global variable.

Added:

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 <stdio.h>
#include <unistd.h>

/*
 * 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:

Added:

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

Added:

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

Added:

Handler Function:

#include <stdio.h>

/* 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 <stdio.h>
#include <signal.h>

/* 
 * 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:

Added:

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

Added:

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

Added:

Handler Function:

#include <stdio.h>

/* 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 <stdio.h>
#include <signal.h>

/* 
 * 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:

Brief:

Added:

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.

Added:

This example shows use of NULL pointers.

Added:

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 <stdio.h>
#include <string.h>
#include <stdlib.h>

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:

Added:

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.

Added:

This example shows use of void pointers.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to use malloc.

Added:

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 <stdio.h>
#include <stdlib.h>

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:

Added:

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.

Added:

This example shows how to use calloc.

Added:

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 <stdio.h>
#include <stdlib.h>

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:

Added:

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.

Added:

This example shows how to use realloc.

Added:

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 <stdio.h>
#include <stdlib.h>

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:

Added:

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.

Added:

This example shows how to use const pointers.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to use const pointers.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to use const pointers.

Added:

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 <stdio.h>

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:

Brief:

Added:

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.

Added:

This example shows how to define multilevel pointers.

Added:

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 <stdio.h>

int main()
{
	int num = 10;
	/* ptr1 points to num */
	int *ptr1 = &num;
	/* 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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>
#include <stdlib.h>

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:

Brief:

Added:

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.

Added:

This example shows how to define a 2D array.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

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

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to read a 2D array.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how 2D arrays are stored in memory.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to access a 2D array with pointer notation.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to access a 2D array with pointer notation.

Added:

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 <stdio.h>

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:

Added:

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.

Added:

This example shows how to access a 2D array with pointer notation.

Added:

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 <stdio.h>

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: