Monday, 22 April 2019

Do While Loop in C

While loop and do while loop in C is similar, the basic difference is that the test-condition in the while loop checks on the initial stage whereas in the do-while loop, the test-condition is defined at the bottom due to which the do-while loop runs at least once.


Do-while loop in C

Syntax of the do while loop in C

do
{
Body statements;
} while (test_condition);



Flow Diagram of do while loop in C

do while loop in C
Flow diagram of do while loop in C

Without checking test condition, the loop is executed at least once, after that test condition inside the while loop is evaluated, if it is true then loop body will execute otherwise. Let's try to understand this concept with the help of the program,

A Program which prints the value from 1 to 5.

#include <stdio.h>
int main( )
{
    int i=0;
    do
    {
      i++;
      printf ("output %d\n",i);
    }while(i<5);
    return 0;
}

Output
Output 1
Output 2
Output 3
Output 4
Output 5

Explanation
In the above program, the variable 'i' is initiated to 0. Now, the loop body is executed at least once. Variable 'i' is incremented to 1, after that output is printed. Now, test-condition (i<5) is evaluated, if this condition is true then output is occurring otherwise.

Do while loop without body

#include <stdio.h>
int main ( )
{
    int i=0;
    printf ("Hello World");
    do
    {

    }while(i<5);
    return 0;
}

Output
Hello World

Infinite do while loop in C

Example 1
#include <stdio.h>
int main( )
{
do
{
printf ("Infinite do while loop in C");
}while(1);
return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
:
:
:
:
:
up to infinity

Example 2
#include <stdio.h>
int main ( )
{
    do
    {
        printf ("Infinite do while loop in C\n");
    }while(11>1);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
.
.
.
.
.
.
.
.
.
.
.
up to infinity

Example 3
#include <stdio.h>
int main ( )
{
    int i=10;
    do
    {
        i--;
        printf ("Infinite do while loop in C\n");
    }while (i<11);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
..
.
..
.
.
up to infinity













Monday, 15 April 2019

While loop in C

In the for loop, we know how many times a loop will execute. While we did not know how many times a while loop will be executed. Execution of while loop is based on the test condition. 

While loop in C

The syntax of While loop in C

While loop will be executed until the test condition is failed.

while (test_condition)
{
body statements;
update expressions;
}



Flow Diagram of while loop in C


while loop in C

First, the test condition inside the parenthesis is evaluated. If the test condition is true then while loop body is executed until the test condition fails.

The test condition may be any value (true or non-zero) or any expression.

A program which prints the value from 1 to 10.

#include <stdio.h>
int main( )
{
    int value = 1; //Initialize value
    while (value <= 10) //Test condition
    {
        printf("value is %d\n",value);
        value++; //increment value
    }
    return 0;
}

Output
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
value is 7
value is 8
value is 9
value is 10

Explanation
In the above program variable 'value' is set to '1'. Execution of while loop is started. If the test condition is true then the statements inside the loop body will execute i.e. print statement and post-increment statement. This loop will execute until the test condition (value<=10) fails. 

While loop in C with no body

#include <stdio.h>
void main( )
{
    int a=1,b=11;
    printf ("%d\n",a);
    printf ("%d\n",b);
    while(a<b);
}

Output
1
11

Infinite while loop in C

Example 1
#include <stdio.h>
int main( )
{
    while(1)
        printf("Infinite While Loop in C");
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

Example 2
#include <stdio.h>
int main( )
{
    while(11>1)
        printf ("Infinite while loop in C\n ");
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

Example 3
#include <stdio.h>
int main( )
{
    int a = 10;
    while(a<=20)
    {
        printf ("Infinite While Loop in C\n");
        a--;
    }
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

C program to print the table of 3.

#include <stdio.h>
int main ( )
{
    int a = 3,i=1;
    while (i<=10)
    {
        printf ("%d\n",a*i);
        i++;
    }
    return 0;
}


Output
3
6
9
12
15
18
21
24
27
30

Use of Logical Operators in While loop in C

Like relational operators, logical operators can also use in the while loop in C

Using AND Operator 

while ( a > 10 && b 10)
The loop body will execute when both conditions are true.

Using OR Operator

while (<=10 || <=11)
The loop body will execute if the anyone test condition is true.

Using NOT Operator

while (!= b)
The loop body will execute if the variable 'a' is does not equal to 'b'.

Program for while loop using logical operator in C

#include <stdio.h>
int main ( )
{
    int a = 10, b = 30, c = 4;
    while((a > 6 || b < 35 && c)!=a)
    {
        printf ("Loop Body Executed\n");
        a--;
        b++;
        c--;
    }
}


Output
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed

What will happen when the test condition in the while loop has zero value?


#include <stdio.h>
int main ( )
{
    while(0) //Zero value is considered as false value, so the loop body will not execute.
    {
        printf ("Loop will executed\n");
    }
    printf ("Loop will not be executed\n");
    return 0;
}


Output
Loop will not be executed






Monday, 8 April 2019

Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free(), Realloc()


Dynamic memory allocation in C



















To understand the concept of dynamic memory allocation in C, first, we need to understand why we need it? Whether we talk about the C programming language or some other programming language, there are some rules for every programming language. C is a structured programming language and it has some fixed rules. Let's try to understand that need and concept of dynamic memory allocation in C with the help of array.



Declaration of an array in C

int employees [100];

An int is of 4 bytes, 100*4 = 400 bytes are reserved in memory. If you want to store details of 70 employees, you can do it but 30 memory locations will be wasted and if you want to store details of 120 employees, you can store detail of 100 employees, but details of 20 employees are not saved. Are you thinking that why this is happening? This is happening because we have used the concept of static memory here if we want that memory should be allocated at the time of execution of the program. So, Dynamic memory allocation concept meets our needs. Let's try to understand this concept. 

What is Dynamic Memory Allocation in C?

Dynamic memory allocation in C helps us to allocate memory during runtime of the program. The dynamic memory allocation is done by using the standard library function <stdlib.h>. This library function consist of malloc (), calloc(), free() and realloc() function in C.



1. malloc ( )

"malloc" or memory function allocates a block of memory of specified size. It returns a void pointer which can be used in a pointer of any form. 

Syntax
pointer_variable = (cast-type*)malloc(Size_in_bytes);

For example
pointer_variable = (int*)malloc(30*sizeof(int));


We know that the size of the integer data types in C is of 4 bytes, the above statement allocates 120 bytes of memory and pointer_variable holds the address of the first byte of the memory block. 

Dynamic memory allocation in c












If 40 bytes are not available in memory that means insufficient space then memory allocation fails and it returns a null pointer

Dynamic memory allocation in C using malloc ( ) function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; // This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    //Number of elements in an array.
    num = 4;
    printf ("Enter number of elements in an array:%d\n",num);
    //Allocate memory using malloc () function
    pointer = (int*)malloc(num*sizeof(int));
    //Check memory is successfully allocated by malloc () function
    if(pointer == NULL)
    {
        printf("Memory not allocated\n");
    }
    else
    {
        printf("Memory is allocated using malloc function\n");
        //Elements of an array
        for (i=0;i<num;i++)
        {
            pointer[i]=i+1;
        }
        printf("Elements of an array\n");
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}

Output
Enter the number of elements in an array:4
Memory is allocated using malloc function
Elements of an array
1
2
3
4

2. calloc ( )

"calloc" or contiguous allocation is used to allocate the block of memory during runtime of the program of the specified size. Every block of memory is initialized with default value zero.

Syntax
pointer_variable = (cast-type*)calloc(number_of_elements, Size_in_bytes);

For example
pointer_variable=(int*) calloc(10, sizeof(int));

The above statement contiguously allocates 40 bytes of memory for 10 elements and each element is of 4 bytes.

Dynamic memory allocation in C












Dynamic memory allocation in C using calloc ( ) function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}


Output
Memory is allocated
2
3
4
5

3. free ( )

This function is used to de-allocate memory. Calloc ( ) and malloc ( ) function does not de-allocate memory by themselves. So, the free ( ) function is used, it reduces the wastage of memory.

Syntax
free (pointer);

Dynamic memory allocation in C





















Free allocated memory using the free ( ) function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
    }
    free(pointer);
    printf("Memory is freed");
    return 0;
}


Output
Memory is allocated
Memory is freed

4. realloc ( ) 

"realloc" or re-allocation function is used to change the allocated memory. If the memory allocated by calloc and malloc function is insufficient then the realloc function is used to re-allocate memory dynamically.

Syntax
pointer_variable= realloc(pointer_variable, new_size);

Dynamic memory allocation in C





















Re-allocate memory using realloc () function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    //Change the size of new array
    int new_num=10;
    //Re-allocate memory using realloc() function
    pointer=realloc(pointer,new_num*sizeof(int));
    for(i=5;i<new_num;++i)
    {
        pointer[i]=i+2;
    }
    //Print the elements of the array
    for(i=0;i<new_num;++i)
    {
        printf("%d\n",pointer[i]);
    }
    free(pointer);
    return 0;
}


Output
Elements in an array
2
3
4
5
New Elements in an array
2
3
4
5
5
6
7
8
9
10

Difference between static memory allocation and dynamic memory allocation in C

1. In static memory allocation, memory is allocated at compiling time and dynamic memory is allocated at executing time of the program.
2. In static memory allocation, memory size can't be changed during execution of the program, it's size is fixed but in dynamic memory allocation, size of memory can be changed during execution of the program.

Difference between malloc ( ) and calloc ( ) funtion in C


Dynamic memory allocation in C





















































Monday, 1 April 2019

Memory Layout of C Program

memory layout of C program























Memory layout of C program contains four segments are text or code segment, data segment, heap segment and stack segment.

Every segment has its own ability to read, write and execute the statement. If a program does not attempt to access memory according to its capability, the segmentation fault is obtained. Program crashes due to the segmentation fault. Segmentation fault occurs when a program tries to read and write an illegal memory location. A dumbed core file is used by the developer to find the reason for a segmentation fault.

Memory Segments



1. Text Segment
2. Data Segment
a. Initialized data segment
b. Uninitialized data segment
3. Heap Segment
4. Stack Segment

Memory layout of c program
Memory layout of C program



























1. Text Segment


  • The text segment is also known as a code segment.
  • This segment contains the binary code of the compiled program.
  • We cannot modify the program abruptly because this segment is a read-only segment.

2.  Data Segment


  • Data of program stores in the Data segment. Data segment divided into two sub-data segments: Initialized data segment and Uninitialized data segment.
  • We can modify the value of the variables during run time of program because this segment is not a read-only segment.


i. Initialized data segment

#include <stdio.h>
int a = 5 //Initialization of global variable 'a' in Data segment
int main(void)
{
static int b = 6; //Initialization of static variable 'b' in Data segment
return 0;
}

ii. Uninitialized data segment


  • Uninitialized data segment stores all uninitialized static and global variables etc.
  • These variables are initialized to zero by default.


#include <stdio.h>
int a; //Uninitialized global variable in the data segment
int main(void)
{
static int b; //Uninitialized static variable in the data segment
return 0;
}

3. Heap Segment

  • Heap segment is part of RAM memory. Memory is allocated during execution of a program. 

  • Dynamic memory is allocated with the help of malloc and realloc function in the C programming language. Heap segment grows in the upward direction as shown in the above figure.


#include <stdio.h>
int main (void)
{
char *ptr = malloc(sizeof(char)*4);
return 0;
}

4. Stack Segment


  • In the stack, elements are stored in last in first out manner (LIFO). Function variables are pushed onto the stack when called and variables are popped from the stack when return. 
  • Whenever a function is called a stack frame is created.
  • Stack pointer tracks the address of the top of the stack.


#include <stdio.h>
int main (void)
{
int a; //variable stored in stack
return 0;
}

The size command helps us to find the size of text, data and bss segments in C. Read the sample of the program given below:


Program 1
#include <stdio.h>
int main(void)
{
return 0;
}

Program 2
In an above program, add global variable.
#include <stdio.h>
int a; //Uninitialized global variable
int main(void)
{
return 0;
}

Program 3
We are adding one static variable in a program as mention below
#include <stdio.h>
int a; //Uninitialized global variable
int main(void)
{
static int b; //Uninitialized static variable
return 0;
}

Program 4
Now, We are going to initialize the static variable in a program and variable is stored in the data segment.
#include <stdio.h>
int a; // Uninitialized global variable
int main(void)
{
static int b = 12; //Initialized static variable 
return 0;
}

Program 5
Initialized the global variable and variable is stored in the data segment.
#include <stdio.h>
int a = 78; //Initialized global variable 
int main(void)
{
static int b = 12; //Initialized static variable
return 0;
}



Recommended Post








































Monday, 25 March 2019

Storage Classes in C and it's types

Storage classes in C






















What is the scope of the variable?

The scope of variable means that where it is actually available in the program.

What is the lifetime of the variable?

Lifetime means how long a variable will stay in the memory. The lifetime of the variable also depends on the scope of the variable.

What is the default initial value of the variable?

The default initial value means that when we do not initialize a variable, what value does it store.



Types of the variable in C

We try to understand the types of variables with the help of a programming example. 
#include <stdio.h>
int d;
int main( )
{
 int add, a=10,b =20;
 add = a+b;
 printf ("Output of addition = %d\n",add);
 return 0;
}

1. Global variable

The variables that we declare before the main function or any function, we call them global variable.  Global variable stays in the memory throughout the program. For example, In the program, the variable 'd' is a global variable. The scope of the global variable is the entire program. We can use the variable 'd' anywhere in the program.

#include <stdio.h>
void newfunction( );
int d = 11;
int main ( )
{
    printf ("value of d = %d\n", d);
    newfunction ( );
    printf ("new value of d = %d\n",d);
    return 0;
}
 void newfunction ( )
 {
     d++;
 }

With the help of the program, we want to let you know that if we declare a variable, we can use it anywhere or in any function of the program.


Output

Storage Classes in C




When we declared variable globally then the default initial value is considered as zero.
#include <stdio.h>
int d;
int main( )
{
    printf("value of d= %d\n", d);
    return 0;
}

Output
value of d = 0

2. Local variable

And the variables that we have declared inside the function are called local variables. The scope of the variable is limited to function or block. For example, In the above program, the variable 'add', 'a' and 'b' is the local variable. 

#include <stdio.h>
void newfunction( );
int d = 11;
int main ( )
{
    int c = 20;
    printf ("\n\n");
    printf (" value of d = %d\n", d);
    newfunction ( );
    printf ("  value of d and c= %d%d\n",d,c);
    return 0;
}
 void newfunction ( )
 {
     c++;
     d++;
 }

Output
Storage Classes in C




Because of the variable 'c' is declared inside the main function and not declared inside the 'newfunction' then there is an error in the program because 'c' is the local variable.


Types of Storage Classes in C




1. Automatic (auto) Storage Classes in C

The variables that are defined inside the function or block is by default considered as a storage class in C. These variables are automatically finished when we come out of the function or block. The keyword 'auto' can be used to declare an automatic variable. These variables are stored in the stack memory.

Scope: These variables are local to the function or block.
Lifetime: Vanished when coming out of the function or block.
Default initial value: Garbage value.


Example
#include <stdio.h>
int main( )
{
    int a;
    auto int b;
    return 0;
}

In the above example, 'int a' and 'auto int b' are the same.

2. Static Storage Classes in C

If we declare a variable as static inside the function, then the variable remains until the program ends. If we declare a variable outside the function in a program, we can use this variable in the program not used in any other program.

Scope: These variables are local to the function or block.
Lifetime: This variable remains until the program's execution is complete.
Default initial value: Its initial value is considered as zero.

Example
#include <stdio.h>
void fun ( );
int main ( )
{
    fun ( );
    fun ( );
    fun ( );
    fun ( );
    return 0;
}
void fun ( )
{
    static int b = 0;
    b++;
    printf ("Static b %d\n", b);
}


Output
Storage Classes in C










3. Register Storage Classes in C

The register keyword suggests the compiler that the variable is stored in the CPU register, not in the memory. Accessing of a register variable is faster than the normal variable.


Scope: These variables are local to the function or block.
Default initial value: Garbage value
Lifetime: Till the end of function or block.

Example
#include <stdio.h>
int main ( )
{
    register int b = 11;
    printf ("address of b %u\n", &b);
    return 0;
}


Output
Storage Classes in C




We can't access the address of register's variable.

4. Extern Storage Classes in C

Let's understand the extern variable with the help of an example. In the below-given program, the variable 'a' has been declared outside the function, so let's see what the compiler tells us about this program.

#include <stdio.h>
int main ( )
{
    printf ("value of a %d\n",a);
    return 0;
}
int a = 23;

Output
Storage Classes in C




As we have seen, the compiler said that the variable 'a' has not been declared.

If we want to tell the compiler that the variable 'a' has been declared somewhere in the program, then we use 'extern' keyword.

Scope: Global that means everywhere in the program.
Default initial value: zero
Lifetime: Till the program doesn't finish its execution.