Monday, March 29, 2021

What is pointer in C ? | Application of pointer | Allocation of pointer | Types of pointer and more

Introduction to pointer 

Pointers are as important part of c language. Pointer provide a powerful and flexible way to manipulate data. To understand pointer we need to understand how computer main memory RAM is organized.

Memory organization :

The computers main memory RAM consist of a large number of sequential storage locations. Each memory location is identified by unique address. The address are numbered sequential for 0 to some maximum number depending upon the memory size. i. e they are positive integer. When we run a program the program code and program data. Occupy some part of the main memory. When we use a variable in a program the compiler sets a side a memory location for that variable. It associates the address with the variable name.

WHAT IS POINTER ?

A pointer is a variable that stores the address of the another variable. i.e it points to the another variable.

APPLICATIONS OF POINTER:

1.The pointer are used to pass the parameter by reference. i.e. the actual argument can be modified.

2. All array are implemented as a pointer in c language.

3. They are used for passing array and string to the function.

4. Pointer are used for dynamic memory allocation where memory is allocated and released for a                variable during run time.

5. All file handling operation are performed using pointer.

6. They are used in complex data structure like  linked list ,tree ,graph etc.


THE BASIC OF POINTER:

1. PONTER DECLARATION:

Since the pointer is a variable it has to declare like any other variable before it can be used.

Syntax:

                        Pointer declaration in C

1. data_type is in c data type. It indicates the type of the variable that the pointer points to.

2. The asterisk(*) is indirection operator.

3. Pointer name is valid C identifire.


2. PONTER DEFINATTION :

The pointer must be assigned the address of the variable before it can be used. The address of the variable is obtained by the address of operator(&) The pointer can be defined by a statement of the form.

Syntax:

                                Pointer Declaration in C

E.G: ptr=&n;

assign address of variable n to ptr.

3. POINTER INITIALIZATION:

Assigning an address to a pointer during declaration is called initialization.

Syntax:

                    initialization of pointer in C

E.g: int *ptr=&n 

4. PONTER DEREFERENCING:

To use a pointer it has to declare dereferenced. De-referencing operation accesses the data in the memory address which the operator holds. The Dereferenced operatoris * (indirection operator). It is also called the value at the operator.

syntax :

                                Pointer Dereferncing in C

Example:

int n=20,*ptr;

ptr = &n;

printf("%d",*ptr) // display 20


POINTER ARITHMETICS:

The c language allows the five Arithmetics  operations to be performed on pointers.

1. Increment ++

2. Decrement --

3. Addition +

4. Subtraction -

5. Differencing


1.Increment or Decrement:

when a pointer incremented using ++, The address in the pointer is increment by a sizeof (data_type) the new value to the pointer will be 

            (current address in the pointer) + sizeof(data_type))

Incrementing a pointer to an int will cause its value to be incremented by sizeof(int).

similarly a pointer to a float will be incremented by sizeof(float).

The same concept is apply for decrementing the  pointer i.e if a pointer is decremented it is decremented by sizeof(data_type).

2. Addition and subtraction:

C allows integer to be added to or subtracted for pointer. When a pointer is incremented by an integer i.e. the new value will be 

(current address in pointer ) + i* sizeof(data)type))

Example: int *ptr,n = 20;

ptr = &n;

ptr= ptr+3;

This code will increment the address in the ptr by 3*sizeof(int). If the size of (int) is 2 then the pointer will increment by 6.

Subtraction is performed in the same way.

3. DIFFERENCING:

Differencing is the subtraction of two pointer. The subtraction of two pointer gives the number of element between the two pointer. The result which an integer which is ;

Address in pointer1 - address in poinnter2 / sizeof(data_type)

Example:

int a[5] = {10,20,30,40,50};

int *p,*q;

p = &a[0];

q= &a[3];

printf("%d",q-p);


The output of q-p will be (1006-1000)/sizeof(int). i.e 6/2 = 3.


RELATIONSHIP BETWEEN ARRAY AND POINTER:

Array and pointer are very closely related. All array are implemented as pointer in 'C'. The array name is a constant pointer and it is stores th base address of the array.

int a[5];

here a is an array name and it is also a pointer. It stores the base address of the array i.e &a[0]

An array operation is converted to corresponding pointer operation. The C compiler internally convert the subscripted notation a[i] to the form *(a+i).

    a[i] = *(a+i)

Dynamic memory allocation :

When variable are declared in a program, the compiler calculates the size of variable and allocates the memory to the variable. This method is called static memory allocation. The amount of memory required is calculated during compile time. In case of array the size of the array has to be declared at the beginning. In many cases a user does not know how many element are to be put. In such a case memory is either wasted if the size is specified is  very large or enough memory is not allocated if the size specified is smaller than required.

In the dynamic memory allocation method we can allocate and de-allocate memory whenever required. Dynamic memory allocation means allocating memory at run-time.

C-provide the four memory allocation and de-allocation functions. They are declared in stdlib.h.

1. malloc:- Allocates requested the number of bytes and returns the pointer to the first byte.

2. calloc:-This also allocates memory for a group of objects, initializes them zero  and returns a pointer                 to the first byte.

3. realloc:-It changes the size of previously allocated block of memory and returns the pointer to the                     block.

4. free:-Release or free previously allocated space.

ALLOCATION:

Two functions are used to allocates the block of memory dynamically: 

These are:

1. malloc allocation :- The allocation function is used to allocate memory aa single block of memory specified size. The malloc() function allocates the size number of bytes of 

storage and returns the a pointer to the first byte. It returns NULL if allocation is unsuccessful or if size is 0. 

The prototype of malloc is:

                                        prototype of mallocation in C

Usage: pointer = (type *)malloc(number_of_bytes);

2. calloc allocation : The calloc function() is similar to malloc. It allocates a single memory block of the specified  size and also initialize the byte is 0. 

The Prototype is :

                                    Prototype of callocation

Difference between malloc and calloc:

1. malloc require one argument   i.e total number of bytes to be allocated. calloc requires the two arguments- the number of objects and size of each object.

2. Memory allocates by malloc contain garbage value. i.e malloc does not initialize the memory whereas calloc() initialize the  memory to 0.


3. Reallocation : 

Reallocation means the changing the size of allocated block of memory. The realloc() function is used to reallocate memory for a block which was dynamically allocated memory using malloc() or calloc().

Prototype of reallocation:

                                            Prototype of reallocation in C

ptr  points to the original block, size is the required new size in bytes:

1. If ptr is NULL realloc acts like malloc and returns a pointer to it.

2. If argument size is 0, the memory that the ptr points to is freed and function returns NULL.

3. If sufficient space exits to expand memory block, additional memory is allocated and function returns ptr.

4. If sufficient space does not exist to expand the current block, a new block of the same size is allocated existing data coppied in to it. old block is freed and 

a pointer  to the new block is returned.

5. If memory is insufficient for reallocation , the function returns the NULL and the old block  remains unchanged. 

5.Freeing or De-allocating memory:

The dynamically allocated memory is taken from the dynamic memory pool(heap) that is avialble to the program. After the program finishes using that memory block, it should be freed to make memory available for future use. The free() function is used to release the memory  that was allocated by malloc() or calloc() or realloc().

Prototype of free allocation:

                                    Prototype of free allocation in C

Memory leak and dangling pointer:

Memory leak:

Memory leak occures when there is dynamically allocated memory area in a heap but no pointer vairable pointing to the memory. A memory leak is memory which hasn't been freed and there is no way to access it. This usually happens when a pointer which was the only reeference to the dynamically allocated memory location points somewhere else now.

Example:

int *ptr1 = (int *)malloc(10);

int * ptr2 = (int *)malloc(20);

ptr1 = ptr2;

here the first block of 10 bytes does not have any pointer pointing to it anymore. Hence it is a memory leak.

Dangling pointer:

When there is a pointer variable which holds the address of a memory block but there is no memory in heap, the pointer is dangling pointer. A dangling pointer is the  reverse of the memory leak. When you free an area of memory but still keep a pointer to it that the pointer is dangling.

Example: int *ptr = (int *)malloc(10);

printf("Address in ptr = %u",ptr);

free(ptr);

printf("Address in ptr =%u",ptr);

ptr = NULL; 


TYPES OF PPOINTER IN C :

1. NULL POINTER: A NULL is a pointer which is pointing to nothing. Usually pointers are initialized                                    in the begining to NULL indicates the it does not have any valid address.

2. DANGLING POINTER: A pointer pointing to a memory location that has been deleted is called                                                     dangling pointer.

3. GENERIC POINTER: When a pointer is declared as type void it is known as a generic pointer. this                                              pointer can not be used directly to points to any element i.e it can not be de-                                            referenced. This pointer can be typecast to any other pointer type. Hence it                                             is called the generic pointer.

4. WILD POINTER: A pointer which has not been initialized to anything is known as a wild pointer. A                                   wild pointer points to some random memory location.

5. NEAR POINTER : A near pointer can stores the 16 bit address which can points to only 64KB data                                        segments or segment number 8 is known as near pointer. It can not access the                                        data beyond the data segment to access data like graphics video memory, text                                        video  memory, etc. size of near pointer is two bytes.

6. FAR POINTER : A pointer which can point or access the while memory if RAM i.e all 16 segment is                                 known as fat pointer. Size of far pointer is 4 bytes or 32 bit. In case of far pointer a                                 segment is fixed. 

7. HUGE POINTER : A pointer which can point or access the whole the residense memory of RAM i.e.                                     which can access all 16 segments is known as huge pointer. Size ofof the far                                             pointer is 4 bytes or 32 bit. In huge pointer the segment part can be modified.

8.COMPLEX POINTER : Multilevel pointer, pointer to function, pointer to array function, pointer to                                               multidimensional array, pointer in nested in structure or union etc. are                                                       complex pointers.








Saturday, March 20, 2021

linked list in C | and their functions in data structure

 linked list :

a linked collection of data element which are stored at ranf=dom memory location and linked to one another the order among element is given by mean of links i e each item is linked to another item 

types of linked list 

1. singly linked list 

2. doubly llinked list 

3. singly circular linked list 

doubly circular linked list


1. singly linked list :

Each node in the list contain only one pointer which points to the next  node of the list The pointer in the last node stores NULL

Node structure :

 struct node                         

{

int info;

struct node next;

}

2. Doubly linked list :

Each node in the list contain two pointers on pointing to the previous node and the other pointing to the next node this list is used when we want to traverse the list in both directions.

Node structure:

struct node 

{

int info;

struct node *prev, *next;

};

3. Singly circular linked list :

This is a singly linked list in which the last node points to the first node . i . e it contain the address of the first node. 


4. Doubly circular linked list :

This is a doubly linked list in which the last node points to the first  and the first node points to the last .

operations on linked list :

teh various operation that can be performed on the linked list :

1, CREATE :  create a list of n nodes.

2. TRAVERSE : Visit each node of the list .

3. LENGTH :  Count the total numbers in the list.

4. INSERT : A node can be inserted at the beginning at end and in between the two nodes 5;

5. DELETE: The deletion  may be done either position wise or element wise .

6.SEARH : This process searches for a specific element in the list.

7 REVERSE: This process reverse the order of node in the list.

8. CONCATENATE: This operation apends the node of the second list of the end of the first list i . e it join two lists .

9. MERGE: This operation merge two sorted list in to a third list such that the third list is also in sorted order.









Wednesday, March 17, 2021

How to use Keil u vision 3. | interfacing 8051 microcontroller

 How to use Keil u vision 3.  for interfacing 8051 microcontroller   : 

1. Open keil u Vision 3. 

2. Click on Project > New uVision Project >

3. Create New Folder in my document by your name and give some name, e.g. ags


 

4. Save file by name of application, e.g. lcd. It automatically saves with .uv2 extension.

 5. Select CPU >NXP(founded by phillips) > P89V51RD2



 6. Create new file. 

7. Write program and save with .c extension. e.g. lcd.c.

8. In project workspace > target 1 > source group 1 > add files to group ‘source group1’. 




9. Click on filename. E.g. traffic > add > close. 

10. Right click on target 1 > option for ‘target 1’ a. target > set XTAL (MHz) =12 b. output – click on create Hex file. c. ok.






11. Build target. It shows errors and warnings and creates hex file in folder. e.g. ags.hex.



 12. Connect the 89V51RD2 Embedded Trainer Kit to PC.

 13. Set the switches 1 to 3 to HIGH on SW1. 

14. Set the switch SW4 and switch ON SW3. 

15. Open ECE Flash and browse the hex file from folder and burn hex file into microcontroller by Clicking on Flash.

 16. Change the position of switch SW4 and switch OFF switch SW3.

 17. Press RESET Key and Observe output on LCD.

Sorting methods in data structure | Bubble sort | insertion sort | selection sort | quick sort

 

Sorting  methods :

Sorting is nothing but arranging the data in ascending or descending order. The term sorting came into picture, as humans realized the importance of searching quickly.

There are so many things in our real life that we need to search for, like a particular record in database, roll numbers in merit list, a particular telephone number in telephone directory, a particular page in a book etc. All this would have been a mess if the data was kept unordered and unsorted, but fortunately the concept of sorting came into existence, making it easier for everyone to arrange data in an order, hence making it easier to search.

Sorting arranges data in a sequence which makes searching easier.

Types of sorting  methods :

comparison based sorting methods :                        NON- comparison based 

1. Bubble                                                                     1. Radix 

2.Insertion                                                                    2. Counting 

3.Selection                                                                   3.Bucket 

4.Quick 

5. Merge 


1.BUBBLLE SORT :

Bubble sort  one of the simplex and most popular sorting method.

In this method there are n-1 passes in each pass we compare each successive element a(i) with the a(i+1)  and interchange the two if they are not in require order .One element is placed in its correct position in each pass This element is not considered in next pass.  in the first pass the largest element is sink to the bottom. second largest is the second large  and so on. Thus a total of n-1 pass passes are require to sort n keys. 

Bubble sort  Example


Algorithm for bubble sort :

step 1. start 

step 2. pass =1

step 3. repeat step 4-8 while pass <=n-1 

step 4. i= 0 

step 5. Repeat step 6-7 while i<=n- pass-1 

step 6. if (a[i]> a[i+1]) then interchange a[i], a[i+1]

step 7. i =i+1

step 8. pass = pass +1

step 9. stop 


* FUNCTION FOR BUBBLE SORT :

void bubblesort (int a[], int n)

{

int i , temp, pass;

for(pass = 1 ;pass < = n-1 ;pass ++)

for (i =0;i<= n- pass -1 ; i++)

{

if (a[i] > a[i+1])

{

temp = a [i];

a[i] = a[i+1];

a[i +1 ] = temp;

}

}

}

*  Program for Bubble sort:

#include<stdio.h>
void bubblesort(int a[],int n)
{
    int i,temp,pass;
    for(pass=1;pass<n;pass++)
    for(i=0;i<=n-pass-1;i++)
    {
            if(a[i]>a[i+1])
            {
                temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
            }
    }
}

void display(int a[],int n)
{
        int i;
        printf("sorted numbers are :");
        for(i=0;i<n;i++)
        
        printf("\n--%d--",a[i]);
}
void main()
{
        int a[30],i,n;
        printf("enter how many numberrs you want :");
        scanf("%d",&n);
        printf("enter the unsorted elements :");
        for(i=0;i<n;i++)
        scanf("%d",&a[i]);
        bubblesort(a,n);
        
        display(a,n);
}


Advantages of bubble sort :

    It is a simple sorting method 

*     No additional data structure is require.

*     It is in place sorting method .

*     It is a stable sorting method.

Disadvantages ;

    It is very efficient method .

*    even if the element are sorted all n-1 passes will be done.

2. INSERTION SORT :

The basic idea of  insertion sort method is to insert an unsorted element in its correct position in the sorted set of element we select one element from the unsorted set at a time and insert it in to its correct position in the sorted set the process continue till the unsorted set becomes empty.

Insertion sort Example


for example :in order to arrange playing cards we pick one card at a time and insert this card in its correct position in the set held in the hand.

ALGORITHM FOR INSERTION SORT  :

step 1 . start

step 2. unsorted index i =1 

step 3. repeat step 4 to 10 while i <=n-1

step 4 . key = a[i] 

step 5 . sorted index j = i-1

step 6. repeat step 7 to 9 while j>= 0 and key < a[j]

step 7. shift a[j] to a[j+1]

step 8 . j = j-1 

step 9. insert key at a[j+1]

step 10. i = i+1 

step 11 . stop 


* Function for insertion sort :

void insertionsort(int a[],int n)

{

        int i,j,key;

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

        {

            key = a[i];

            for(j=i-1;j>=0;j--)

            if(key < a[j])

            a[j+1]=a[j];

            else

            break;

            a[j+1] = key;

        }

}

* program for insertion sort :

#include<stdio.h>

void insertionsort(int a[],int n)

{

        int i,j,key;

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

        {

            key = a[i];

            for(j=i-1;j>=0;j--)

            if(key < a[j])

            a[j+1]=a[j];

            else

            break;

            a[j+1] = key;

        }

}

void main()

{

        int i,a[40],n;

        printf("enter how many numbers you want :");

        scanf("%d",&n);

        printf("enter the unsortd numbers :");

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

        sccanf("%d",&a[i]);

        insertionsort(a,n);

        prinntf("sorted numbers are :");

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

        printf("--%d--",a[i]);


}

ADVANTAGE INSERTION SORT :

1. It is a simple sorting method 

2. No additional data structure is required.

3. It is in-place sorting method.

4. It is a stable method sorting.

5. This method gives best efficiency if the elements are almost sorted.

DISADVANTAGE :

1. worst case efficiency is O(n2).

SELECTION SORT :

Selection sort method is one of the most intuitive sorting method suppose we are given a list of the items to sort what would we do  we would select the smallest item and put it in another list then we pick the next smallest and so on till we have a sorted list.

Selection sort Example

In this Selection sort method  the set is divided into two sets sorted and unsorted initially the sorted set is empty and unsorted set is full we select the smallest element from the unsorted set and add it at the end of the sorted set to add it to the sorted set we exchange it with the first element in the unsorted set after each exchange the sorted set grow by 1 element and the unsorted set reduces by 1 element thus to sort n element we need to select and place n-1 element Hence there are n-1 passes in this method.

ALGORITHM  FOR  SELECTION  SORT :

STEP1. START 

STEP 2. sorted index current = 0 

step 3. repeat step 4 - 11 while current <=n-1

step 4. smallest = a[current] 

step 5. pos = current ;

step 6. i =current +1

step 7 . repeat step 7 - 9 while i= <n-1

step 8 . if (a[i] <smallest) then smallest = a[i]

            pos =i

step 9  .i = i+1

step 10 .  swap a[pos]  and a[current] 

step 11. current = current +1

step 12. stop


* Function for selection sort : 

int selectionsort(int a[],int n)

{

        int i,temp,pos,current,smallest;

        for(current=0;current<n-1;current++)

        {

            smallest = a[current];

            pos = current;

            for(i=current+1;i<=n-1;i++)

            if(a[i]<smallest)

            {

                smallest = a[i];

                pos = i;

            }

            else

            {

                temp = a[current];

                a[current] = a[pos];

                a[pos] = temp;

            }

        }

        

}

* Program for selection sort: *

#include<stdio.h>

int selectionsort(int a[],int n)

{

        int i,temp,pos,current,smallest;

        for(current=0;current<n-1;current++)

        {

            smallest = a[current];

            pos = current;

            for(i=current+1;i<=n-1;i++)

            if(a[i]<smallest)

            {

                smallest = a[i];

                pos = i;

            }

            else

            {

                temp = a[current];

                a[current] = a[pos];

                a[pos] = temp;

            }

        }

        

}

void main()

{

        int n,i,a[30];

        printf("enter how many number you want : ");

        scanf("%d",&n);

        printf("enter numbers in an array :");

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

        scanf("%d",&a[i]);

        selectionsort(a,n);

        printf("the sorted output is :");

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

        printf("--%d--",a[i]);

        

}


ADVANTAGES  SELECTION SORT :

1. It is a simple sorting method.

2. non additional data structure is required.

3. It is in place sorting method.

4. it is a stable sorting method. 

DISADVANTAGE SELECTION SORT :

Best  and Worst case efficiency is O(n^2). 

learn  about more sorting methods 👇

Read more 


linear vs binary searching in c | linear search |binary search

 

Searching Methods :

1. linear  or  sequential search .

2. Binary search .

1. Linear search /Sequential search : 

This is a simplex method of searching It is also called as a linear search and applied to sequential storage structure like file array or linked list.

linear searching method



Procedure : In this method the search for the key begin from the fist element and search continuous sequentially till the element will matching key value is found till the list end. 

ANALYSIS OF LINEAR SEARCH :

BEST CASE :

 The best case occurs when the key is found  at the first position. i . e. at index 0 here only one comparison performed Hence the best time complexity is omega 1.

WORST CASE :

 This case occurs when the  key is found in the array in such a case n comparisons are performed  Hence the ort case time complexity is O(n).

AVERAGE CASE :

Let us consider that all keys occurs with equal probability for all keys Ki (0 <= i<n) the total number of comparisons for successful searches are :

1 + 2 + . . . . . + n = n(n+1) /2

so average comparison is = n(n+1)/2n = (n+1 ) /2 Hence the average case time complexity of this method is O(n).

EFFICIENCY OF LINEAR SEARCHES ARE :

BEST CASE :  OMEGA 1 .

WORST CASE : O(n).

AVERAGE CASE : O(n).

Advantages :

1. It is a very simple method .

2. It does not require the data to be ordered.

3. It does not require any additional data structure.

Disadvantage :

1. If n  is very large this method is very inefficient and slow.

2. its worst case complexity is O(n) Hence the worst case search time increase in proportion to the number of elements. 


FUNCTION FOR LINEAR  SEARCH :

The function for linear search accepts an array , number of element and key as arguments it return the position of of key is found and return -1 if key is not found.

int linear_ search (int A[], int n, int key)

{

int  i ; 

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

if (A[ i ] = = key )

return 1;                /// return position 

return -1 ;             ///key not found 

}

Program for linear / sequential  search :

#include<stdio.h>

#include<stdlib.h>

int compcount=0;

int linearsearch(int a[],int n, int key)

{

        int i;

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

     {  

         compcount++;

        if(a[i] ==key)

        return 1;

        

     }

     return -1;

        

}

void accept(int a[],int n)

{

    int i;

    printf("enetr the %d element :",n);

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

    scanf("%d",&a[i]);

}

void main()

{

        int a[30],pos,key,n;

        printf("how many number you wnat in an array:");

        scanf("%d",&n);

        accept(a,n);

        printf("enetr number to be searched  :");

        scanf("%d",&key);

       pos = linearsearch(a,n,key);

       if(pos==-1)

       printf("%d not found in the array ",key);

       else

       printf("\n %d  found at position : ",pos);

       printf("\nthe total number of comparision =%d",compcount);

      }


2. Binary Search :

This method is based on  divide an conquer algorithmic strategy. in this strategy problem is solved by dividing the set of element and performing operation on each part

Binary searching method

Precondition for binary search:

1. Data must be organized in linear way. 

2. Data has to be in the sorted order in either ascending or descending order.

Procedure :

* In this method the list is partitioned in two equal halves.

* The key compared with the middle element If a match is found the search is terminate.

* If the key is less than middle element search proceed in the same manner in the upper half of the table. 

* if the key is greater than middle element search proceed in the same way in the lower half of the table.

* The process continues till the key is found or no more partition are possible.

* Thus every time a match is not found the remaining list sized to searched reduce to half .

EFFICIENCY :

BEST CASE :

In this best case key is found at the middle position after 1 comparison . Hence the best case time complexity is  omega 1

WORST CASE :

If we observe the loop is repeatedly halving the number off element. Hence the algorithm complexity is logarithmic. Thus the time complexity is O(log2 n) which is very efficient.

ADVANTAGE :

Worst case time complexity is O (log2n) which is very efficient compared to sequential search (O(n)).

DISADVANTAGE :

Data has to be in sorted order.

Difference between linear search and binary search .


* FUNCCTION FOR BINARY SEARCH :

int binarysearch( int A[],int n ,int key )

{

int begin = 0, middle, end = n- 1;

while (begin < = end )

{

mid = (begin + end )/2;

if (key == A[mid] 

return mid ;

if (key < A[mid ]) 

end = mid -1 ;

else 

begin = mid +1 ;

}

return -1;

}

* program for Binary search : 

#include<stdio.h>

#include<stdlib.h>

int binarysearch(int a[],int n,int key)

{

    int begin=0,end=n-1,mid;

    if(begin<=end)

    {

            mid=(begin+end)/2;

            if(key == a[mid])

            return mid;

            if(key <= a[mid])

            end=mid-1;

            else

            begin=mid+1;

            

    }

    else

    {

            return -1;


    }


    }

void accept(int a[],int n)

{

    int i;

    printf("enter numbers in an array :");

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

    scanf("%d",&a[i]);

    

}

int main()

{

    int n,key,a[30];

    int pos;

    printf("enter how many numbers you want in an array :");

    scanf("%d",&n);

    accept(a,n);

    printf("enter number i to be search :");

    scanf("%d",&key);

     pos = binarysearch(a,n,key);

     if(pos == -1)

     printf("key is not found ");

     else

     printf("key is found ");

     

}

learn more about searching methods 👇



Thursday, March 11, 2021

Data structure and algorithm -1

 

Need for data structures :

1.Modern day computing problems are complex and large.

2. They need to handle data in large volumes.

3.There is need to store and process information of a variety of types:  character, numeric, audio , video ,graphics, etc. 

4. Data has to be stored such that the logical relationship between the data element is retained. 

ADVANTAGE OF DATA STRUCTURE 

1. Structured data makes it easier to access the manipulate the information as compared to the raw unstructured data.

2. A variety of operation can be performed in structured data. 

3. Related data can be stored together and in the required format. 

4. better algorithm can be used on organized data. This improve program efficiency. 

5. They provide a means to store organize and retrieve data in an efficient manner.

DATA:

Data is a unprocessed input given to an a system or process.

1:ATOMIC DATA :Atomic data is a single elementary piece of data which cannot be further decomposed 

example: character 'a' and number 20etc. 

2:COMPOSITE DATA :Composite data is a grouped data item which consist of subfield each of which atomic 

example: a data like a subfield like day, month, and year.

DATA TYPE :

Data describe the  format in which data is stored and processed by a computer It also refers to the kind of data that variable hold in a programming language.

DATA OBJECT :

Data object refers to a set of element(D) of a specific data type. this  set may be finite or infinite. If the set is infinite we have to advise some mechanism to represent that set in memory because available memory is limited. 

DATA STRUCTURE :

A data structure consist of a data object , their properties and the set of legal operation which may be applied to the element of the data object.

definition:

A data structure is set of domains D a designated domain d belongs to D a set of function F and a set of axioms A. The triple (D F A ) denotes the data structure .

D = denotes the data object that is set of element.

F = denotes the set of operation that can be carried out on the element.

A = describe the properties and rules of operation.\

ABSTRACT DATA TYPE :

An ADT  is a mathematical and conceptual definition of a data structure the data structure i . e the triple DFA is called the abstract data type because it  is simply to conceptual specification off the data structure. 

IMPLEMENTATION OF DATA STRUCTURE :

The ADT is just a abstract data type. To use the data type or data structure it must  be implemented in a programming language. The implementation is concerned with 

1. How the elements are stored in memory.

2. How the operation are performed .

3. How the rules are enforced. 

SPACE COMPLEXITY :

The space complexity of an algorithm/program is the amount of memory is needs to execute. 

COMPONENTS OF SPACE COMPLEXITY :

1. Fixed part : This part is the independent of the characteristics of the input and the output of the memory space for simple variable component variable and constant. 

2.Variable part : It consist of the space needed by variable whose size depend on the particular problem instant being solved the space needed by reference variable and the recursive stack space. 

The space complexity S(P) for an algorithm is written as 

S(P) = C + Sp 

where c is a constant and is the fixed part Sp is the variable part which depend on the instance characteristics i . e. the program instance being run. 

example : float area (float r)

{

return 3.142 *r *r ;

}

the space needed is independent of the input and output of the characteristics it requires space for only one variable r 

Sp= 0, c= 1 .

TIME COMPLEXITY :

The time complexity of a program is the amount of time the program requires to execute however it is difficult to calculate the extract running time also the extract running time depend on the underlaying hardware and software. 

Hence instead of calculating exact running time a rough estimate can be made to do this we have to identify the 'active operation' of the program . The other operation like initialization assignment input and output etc. are called' book keeping operation'. and will not execute any times at the active operation. 

The total number of active operations is defined as frequency count.. 

BEST CASE AVERAGE CASE AND WORST CASE :

1. BEST CASE :

The term best case is analyze an algorithm under optimal conditions. The best case performance is the minimum number of steps that can be executed for the given input values. 

Best case (Tn) = min (Tx1, Tx2, . . . .. . Txn)

2.WORST CASE :

The worst case count the number of steps count the maximum number of steps that can be executed for the given parameter. This is the slowest possible time an algorithm may take an it upper bound. It is important to calculate the worst case behavior because  we know that the running time will execute this limit.

worst case Tn = Max(Tx1,Tx2, . . . .. . . . ,Txn)

3. AVERAGE CASE :

Average case running time assume that all input of a given are equally likely The average case step count is the average number of step executed 

Average case  =   1/  All possible inputs T(x1, x2, . . . . , xn )


 ADT of array :The ADT specifies the data object (D), function (F),axioms (A) of the data structure .

FUNCTIONS :

1. CREAT(array, type, size ): This operation creates the new array . This operation needs information like type of data of data element like a number of data element to be stored .

example : int [10]; 

2. STORE(array , index ,value ): store a value at a particular position. This operation needs the name of array the position in an array and value to be stored at that position. 

example : a[0] = 5; 

3. RETRIEVE (array , index): Retrieve a value at a position This operation requires the array  name and an index and it return to corresponding value .

example : num = a[0];

AXIOMS :

Create : The array name should be valid identifier size should be an integer and type should be a valid type.

Store : The index must be an integer value should be of the same type array .

Retrieve : the index must be an integer.

APPLICATION OF ARRAY :

Most application which handle large volume of data use array to store the element.

1. Searching .

2. Sorting .

3. Matrix operation.

4. Static implementation of data structure like stack , queue , tree, graph , etc.

SEARCHING : It is a process of locating an element with particular key value.

Key: particular element searched is called as key.

Retrieval : A successful search is called retrieval .

Internal searches : searches in which the entire table is stored in the main memory  are called as internal searches.

External searches : In this case most of the table is stored in auxiliary storage devise.

SORTING :

The sorting is a process of arranging the elements in the ascending or descending order.

1. Internal sorting : sorting is done on the data which is stored in the main memory.

2. External sorting : sorting is done on the data which is stored in auxiliary storage device. 

3. Stable sorting technique: A sorting method  is said to stable if the order of key having the same values in the unsorted set is retained in the sorted set. 

4. In place sorting : A sorting algorithm is said to be in place sorting if it does not use a lot of additional memory for sorting. 

Example : bubble sort , insertion sort etc. 

















Monday, March 8, 2021

prescriptive process models

 prescriptive process model orderly approach to software engineering. its specific step by step sequence of activities addressing how to do the software development. all activities involve the dependent on one or other activity.

1 . THE WATERFALL MODEL :

It is also referred as "traditional" or "typical" or "classic life cycle" . model an is the oldest model of the software engineering. This model was proposed by Winston Royce in 1970.

Different phases and activities performed in each phase of waterfall model.


waterfall model follows the generic framework activities in sequential manner. The developer completes each phase before moving to the next . As the diagram resembled cascading waterfalls this model in called as "waterfall model".

PHSES OF WATERFALL MODEL :

1. Communication and requirement analysis phase : understanding user requirement and documenting the it is the basic aim of the phase.

2. Planning and scheduling phase : This phase aims to schedule the various activities of software development it identifies the risk involve and estimate the cost of development. it is also helps in tracking the development. 

3. Modeling and design phase : The main goal of this phase is to design the overall system with detailed specification. 

4. Construction or coding and testing : As the name of suggest this phase is responsible for implementation of the system design.  various components of the system are coded and tested of ensuring accuracy . 

5. deploying or operating maintenance phase : The phase aims of maintenance and successful operation of development software at users end for final acceptance. 

FEATURES OF WATERFALL MODEL:

1. The entire development process is divided in to number of phase.

2. It uses a linear process flow.

3. Each phase perform a specific task or activity.

4. Each phase generates a certain outcome called as a "work product ".

5.Outcomes of previous page acts as a input for the next stage. 

ADVANTAGES OF WATERFALL MODEL :

1. It is very simple to understand and use.

2.As each stage is responsible for a specific task it helps in good scheduling as cost estimation.

3. Efficient use of resource because of good scheduling. 

4. Work product helps in the judging the progress of the development process. 


LIMITATIONS OF WATERFALL MODEL :

1.Software product rarely follow the sequential process.

2. IT is not easy for user to explicitly specify all requirement of the beginning of the project which the model expects. 

3. It is unable to ideal with uncertainty which exists at beginning off the project. 

4. when project enter in a later stage i e. coding and testing it becomes difficult to accommodate change.

5. If a problem is identified in later stage then rectifying the problem leads to increase in cost and time of development.

2. V- MODEL :

This model is also referred as Verification and validation model. basic phase performed for software development in v- model are same as waterfall model. this model considered at as extension to the waterfall model. In this model action be be carried out for ensuring the quality development are describe with with each fundamental phase of waterfall model. This action involve various tests do validate the product at which as shown in the below figure.



VALIDATION PHASES IN V- MODEL :

1. Unit testing : unit test are designed and performed to ensure error free code at program module level. It checks the correct execution of each functionality implemented. 

2.Integration testing: system testing and ensure the error free and smooth working of various component module together. 

3. System Testing : System testing ensures that the system that whole working and correctly and providing the expected functionalities. 

4. Acceptance testing :The system tested in user environment  before the final acceptance. 

ADVANTAGE OF V- MODEL :

1. testing is planned before planned well before coding.

2. higher chances for success over waterfall model. 

3.Efficient for small project when requirement are clearly specified. 

DISADVANTAGE OF V- MODEL :

1. Not flexible.

2. Does not work efficiently with large and complex project. 

3. Difficult to adapt to changing requirement. 

 

THE UNIFIELD PROCESS MODEL :

The unified process model tries to extract the best of all traditional model. The process flow in unified process is incremental iterative and highly focused. on customer involvement . It is mainly designed for object oriented developing using UML (Unified Modeling Language).

PHASES OF UNIFIED PROCESS ARE AS FOLLOWS :

Inception Phase :  Inception phase mainly focused on objectives, business requirement and scope of project. It involves communication and planning activities.

Elaboration phase :  At the end of this phase most of requirement of the system is identified .It involves communication and modeling activities. 

Construction phase : This phase results in the actual software increment. different software components are integrated together and software increment is developed and tested.  Analysis and design models developed in elaboration are thus completed here.

Transition phase :  The outcome of this phase results is product release. Here the developed software is transferred for beta testing to client environment. All supporting document like user manual installation procedure etc. are also delivered to the client together with the software. 

 













 

Saturday, March 6, 2021

software quality guidelines and attributes

 The design process work in iterative manner. After each iteration the quality of involving design needs to be accessed with series of technical reviews. following are the three characters are suggested by mclaughlin (MCG91) that can serve as a guideline for evaluation of good design. 


1. The design  must cover all the explicit requirement  as a specified in the requirement models and must also support the explicit requirement as desired by the stack holders. e. g if you are designing a battery operated toy then one of the explicit requirement is to provide for the battery slot within the toy body where as the implicit requirement is providing an interface for charging the battery. this is so because without charging the interface the battery slot is of to use the toy.

2. The design must support for documentation must be readable and an understandable  guide for the  code  developers and testers who would be then providing technical support o the software. 

3. The design artifacts all put together must provide  a complete picture  of the software focusing on the data functional and behavioral domain from the implementation point of view. 

each of the above characteristics from the goal for a good design. There should be some guideline as to how to achieve this characteristics.  In order to evaluate the quality of a design the software team must establish technical criteria for good design 

The following guideline can be followed  to establish good quality criteria :

1. A design should support an architecture that is a part of recognizable or standard architecture style and pattern is made up of components with good design. characteristics can be implemented in an evolutionary manner thereby facilitating coding and testing.

2. a design should define the software as a set of modules or subsystem that are logically interconnected to each other. 

3. A design should provide a distinct representation of data interface and components. 

4. A design should depict the data structure that are appropriate for class implementation drawn from the known data pattern. 

5, A design should also depict the all known components along with their functional characteristics , and also define their degree of interrelation ship with the other component system. 

\6. The design should exhibit the interface that the component will use to provide their services and get services from  the external environments. 

7. A design should be obtained in a iterative manner driven by the requirement obtained during requirement analysis phase. 

8. A design should depicted using notation that depicts its meaning. 


QUALITY   ATTRIBUTES :

Hewlett - packard(Gra87) developed a set of attributes with (acronym FURPS) that is the target for overall software design.

1/ Functionality is accessed by evaluating the generality of the services that are provided by the software and the security of aver all system. 

2. Usability is evaluated by considering the aver all feature consistency and documentation.

3. Reliability factors and software defines the extent to which the system can continue to  work inspite of failure. it is checked by measuring the frequency and the severity of failure of accuracy of output result the mean-time -to -failure (MTTP)and the ability to recover a failure. 

4. Performance measured by a factor like processing speed response time throughput to recover from a failure. 

5. Supportability refers to the ability of the design to support for maintenance testability, compatibility and configurability. 

it should be understand that all the quality attribute need not me of equal weightage while  designing a software application it depends on the requirement of software application. like an application may stress more on reliability whereas another one way give more weightage to performance or functionality. regardless of which attribute  the application focus on which this quality attributes must be considered during its design phase. 


DESIGN PROCESS :

The software design work in an iterative manner and translate the requirement into a blueprint for construction the software. The blueprint present a high level abstraction of software. 

Further iteration in design process leads to frequent refinement thereby providing design to a lower level of abstraction or in a much detailed manner. All these refinement can be traced back to the requirement but the connection is more delicate. This is so because the higher view of the system whereas the design phase provide a mire detailed  architecture of required models. 

SOFTWARE REQUIREMENT SPECIFICATION(SRS):

it a document produced as result of requirement elicitation SRS basically describe what functionalities that the proposed software should provide that is should do it does it does not focus on how to achieve the specified functionality an error in srs results into error in final product.

Characteristics of SRS 

1. correct : 

every requirement specified in SRS  shows something required from the software.

2. Complete : 

All functional expected from the software should be mentioned in the SRS it is very important and difficult to achieve.

3.clear/ unambiguous ;

every requirement specified in SRS should be clear to understand it should not lead to any ambiguity.

4. verifiable :.

there should some co-efficient process to check whether the final product meets every requirement specified in the SRS. 

5. consistent :

There should not be requirement which are confliciting with each other in the SRS 

6. Stability :

It refers to the chances of the requirement to changed in future.


ADVANTAGES OF SRS :

1: It creates a general agreement between the client and the developer on what facilities the developed software should produce.

2. It also provide specification for validating the final product. it helps both customer and developer to convince whether the final software developed is same as per the user's expectation.

3. High quality SRS  results in high quality software.

4. A high quality SRS also reduce the development cost as fixing bugs in later step of development id very expensive. 







Wednesday, March 3, 2021

Explain Block Diagram of Communication system

   communication system 

The word "communication" means exchange of information. from ancient times human being were using this technology to convey one's thoughts , ideas and feelings .  the rapid development in  electronic field have the change the mode of communication from human messengers and birds to radio , tv , telephone ,mobile , WI-FI , LI-FI , internet of things and so on . the application domain of communication system is so developed and have became so common that we often take it for granted the powerful technologies that allows us to communicate nearly instantaneously . it is almost impossible to imagine our society without communication system . the rapid development in communication system is playing a vital role in globalization thus stimulating a bursting growth of complex social and economic activities . The growth of communication industry has no end since people had a natural desire and need to communicate rapidly to any one at any time and at any location . Number of users utilizing communication system are increasing day- by- day . To accommodate them and to fulfill the above three requirement , continuous updation in communicating devices and technologies is required in the field of communication .

Elements of communication system :)

The communication system convey information from one place to another place . Thus system must have information source at ane end and destination at the other end. Source generates the information (a human voice , video, digital data from computer etc . ) 

Basic blocks of communication system : 
1:  source
2: Transmitter 
3: Transmission channel
4: Receiver 5: User 
6: Noise


BLOCK  DIAGRAM OF COMMUNICATION SYSTEM :)


Block diagram of communication system



The role of  each block in information transmission :

1. SOURCE: 

The source generates the information . The information can be audio, video, digital data , text etc.  depending upon the type of information signal ,communication system , application differs . e.g. radio communication transmit the audio signal, TV communication transmit the audio and video signal , mobile communication has audio ,video, text, digital data etc.

* further the type of information signal can be analog or digital.
 

2. TRANSMITTER:

The information sent via the communication link originates at the source. Since information can have various forms , it may not be suitable for transmission at it is. The job of transmitter is to process the information of to produce a signal suited for the transmission through the transmission channel. processing may involve amplification, signal conversion, modulation, encoding , encryption , multiplexing etc. The last element of transmitter is antenna. Antenna is responsible for conversion of electrical signals into electromagnetic signals and linked to transmission channel.

3. TRANSMISSIONN CHANNEL: 
   This is the physical transmission medium over which the information is sent. During travel through channel, some amount of transmission loss or attenuation is observed. So the information signal strength decrease with increasing distance. Depending upon transmission channel, communication system is divided in two types:

3.1:wired communication  :

3.1.1: co-axial cable :
co-axial cable has two conductors arranged in concentric manner and are separated by an insulating material. co-axial cable widely used for long-distance telephone communication but now have largely been replaced by by optic fiber cable because of several advantages.

3.1.2: Optic fiber cable :
optic fiber cable transmit the information in terms of light waves. it consist of core and clad material having different refractive indices. The light travel through the optical -phenomenon - total internal reflection. 

Advantages of optical fiber cable :
a) Immunity to crosstalk.
b) Immunity  to static interference. 
c) Durability and reliability. 
d) Smaller size and light weight.


3.2: Wireless communication :

In wireless transmission, information is sent and received as electromagnetic waves from one point to another point through the atmosphere or free space. Different layer of the atmosphere are used for propagating electromagnetic waves. the layer selection is dependent upon frequency of information and range of coverage.

4. RECEIVER :
Receiver is the block which accept the transmitted and propagated signal through it's antenna and convert it back into original information. It performs many operation on the received signal to extracts original information. The operation includes amplification , demodulation, decoding, to reverse signal processing performed at the transmitter, decryption, etc. 

5. USER :
The user is a recipient of the information.

6. NOISE:
Noise is a unwanted electrical signal superimposing on original information signal.
This superimposing of noise signal either partially corrupts  or totally  modifies the original information. Identification of the  information at the receiver depend upon the amount of noise accompanied by the information during the process of communication. in the absence of noise identification of information at the receiver is the perfect.