Saturday, July 30, 2016

using if statement in c

If statement:

if statement allows us to interrupt the flow of the program. The sequence of the program will be changed when we use if statement at that function. If statement is mainly used to take the decisions in the function. 
Now let us examine about the TRUE and FALSE terminology in programming. If a statement evaluates to a Non Zero number then it is said to be a TRUE statement. similarly if a statement evaluates to Zero number then it is said to be FALSE statement. 

Relational operators:

Relational operators are those which can be used for comparing two elements. Here are some examples for relational operators:

less than < 
greater than >
less than equal to <=
greater than equal to >=
equal to ==
not equal to !=

Basic if syntax:

if(condition is true)
  execute the statement;
if (condition is false)
   ignore this statement;


here is a small example of if statement

if(4<5)
{
   printf("This line of code will be executed as four is less than five is true");
}

Else statement:

Sometimes we need to execute some other lines of code if the statement is not true. If the if statement is false else function is executed.

if-else syntax:

if(the condition is true)
{
 Execute this line of code;
}
else
{
  This line of code will be executed if condition is false;
}

Else-if statement:

Some times there is a necessity to use multiple conditions in which all may all evaluate true yet you want only one if statement to be executed true.

Basic syntax:

int main()
{
  if(condition is true)
   execute this code
else if(this comdition is true)
        execute this code;
}






Sunday, July 24, 2016

introduction to c

compiler:   

                   A compiler is a software that converts a source code written in programming language into target computer language. A c program must have a compiler to run the source code.

Introduction to c

Every c program begins inside a "main" function. Whenever the program executes the main function is called first and later we can call functions inside the main function..A c program consists of three parts header, body and conclusion. We can include library functions into the program through the header by using a hash tag. 

    let's look into a small program:

#include<stdio.h>
int main()
{
  printf("Welcome to c");
  getchar();
   return();
}

Now look into the program, On  the top of the program we have #include header file. stdio stands for standard input and output functions. Everything inside the main function is the body of the program. Everything we used inside the program should follow the syntax rules.

Variables:

Input and data should be placed in variables. There are several types of variables. When are telling the compiler that you are declaring a variable you have to declare the data type of the variable along with the name of the variable. Different data types are char, int  and float..

A variable of type char stores a single character, whereas type int stores the integers(Numbers without decimals). Float stores the numbers with decimals.

To declare a variable one must follow the syntax used to declare in c programming i.e, <data_type> <variable_name>;

Examples of some variable declarations:

int x;
int a,b,c,d;
char letter;
float the_float;

Reading an input:

sample program to read an input

#include<stdio.h>
int main()
{
   int this_is_a_number;
   printf("Please enter your number:");
   scanf("%d", &this_is_a_number);
   printf("You entered %d",this_is_a_number);
   getch();
   return 0;
}








Friday, July 22, 2016

searching

Searching in programming :

         Searching is the most fundamental technique used in computer science.  It is the process of finding a particular item in the collection of items. Another use of searching algorithm is that it can check whether the particular item selected is present in the given collection of list or not. 
Searching techniques are of two types. They are linear search and binary search.

Linear Search:

 This is the most simplest and regular way to search a particular item. According to this algorithm the selected item will be checked with each and every element until the end. It checks each and every item in a sequence.

Code for linear search:

bool lineat_search(int a[], int length, int item)
{
  for(int i=0;i<length;i++)
  {
    if(item==a[i])
    {
      return true;
    }
  }
  return false;
}

Let's take an example. say a={1.9,2,4,6,3,7,5,8,0}... We need to find 3 in the given array. Now linear search starts from the beggining and checks whether the given number matches with the item or not.
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here
Now let us consider the modified search where we need to return the position, where the item is found. To solve this modified search problem, we need to change two lines of the linearserch() function.

code:

 int linear_search(int a[],int length, int item)
{
   for(i=0;i<length;i++)
   {
     if(item==a[i])
     {
       return i;
     }
      return -1;
    }
}

Binary search:

  Binary search is a divide and conquer algorithm. According to binary search we need to divide the larger problems into smaller subproblems recursively until the problem is small enough that the solution is trival.

 for using this binary search algorithm the array should be sorted. If the array is sorted in the ascending order binary search starts with the middle element of the array. If the selected item matches to the middle element then it returns true. Otherwise if the item selected is less than the middle item it takes the upper half and checks with the middle element on the upper subpart. If that middle element matches to the selected item then it again returns true. Otherwise if the element is greater than the middle element then it cheks with the lower half of the system.

here is an algorithm for the binary search:

algorithm binary_search(A, left, right, item)
{
  if(left<=right)
  mid=left+right/2
 if(A[mid]==item)
 return true;
else if(item<A[mid])
        recurse on the left sub array
else if(item >a[mid])
        recurse on right sub array;
else 
  return false;
}

enter image description here
enter image description here
enter image description here
enter image description here

Saturday, July 16, 2016

sorting

sorting:

sorting is a process of arranging items in either ascending or descending order. This process can be implemented by different types of algorithms. 
 
Different types of basic sorting algorithms are as follows:

  • bubble sort
  • selection sort
  • insertion sort 
  • merge sort
  • quick sort
  • count sort

bubble sort:

    This algorithm is based on repeatedly comparing the adjacent elements and switching their positions if they exist in wrong order. The code for bubble sort is as follows:

void bubble_sort(int a[], int n)
{
  int temp;
  for(int k=0;k<n-1;k++)
  {
     for(int i=0;i<n-k-1;i++)
     {
       if(a[i]>a[i+1])
       {
          temp=a[i];
          a[i]=a[i+1];
          a[i+1]=temp;
       }
     } 
  }
}
    
pictorial representation of the above code is as follows:

enter image description here



This bubble sort compares with the adjacent element. In the first step 7 is compared with 4 and since 7 is greater than 4 both got swapped. and if it is in ascending order the elements stay on the same position and the process repeats for the next iteration.

  The complexity of bubble sort is worst and average case i.e,, 0(n^2). This is because for every iteration element needs to be verified.

selection sort:

    This algorithm is based on the idea of selecting the maximum or minimum element in the given unsorted list of array and placing the selected element in the correct position to get a sorted array.

consider the given array of elements a[]={7,5,4,2}. now we need to sort the given array in ascending order.
 now, according to selection sort algorithm we need to select the minimum element in the list. minimum element in the list is 2. so we should replace it with the first position. i.e, 2 will be swapped with 7. now we should find the second minimum element in the list and replace it with a[1] th position. this process should be repeated until we get the exact result.

let's have look on the code:

n= number of elements in the array

code:

void selection_sort(int a[],int n)
{
  int minimum;
  for(i=0;i<n-1;i++)
  {
     minimum=i;
     for(int j=j+1;j<n;j++)
     {
       if(a[j]<a[minimum])
       {
         minimum=j;
       }
     }
     swap(a[minimum],a[j]);
  }
}

here is the pictorial representation of the above pseudo code:

enter image description here


complexity:

      To find the minimum number of  n elements , we require (n-1) number of comparisons. Putting minimum element to it's proper position size of unsorted array reduces to n-1 and then to n-2 comparisons are required to find the minimum in the unsorted array. therefore complexity is o(n^2).

insertion sort:

 According to this algorithm the element has to be inserted at it's correct position after each iteration. It consumes one element from the input elements removes it and find the correct position.i.e, where it  belongs in the sorted list and places it.

   It checks the current element with the largest value in the sorted list. If the current element is larger, then it leaves the element as it's place and moves to the next element, else it finds it's current position in the sorted list and moves it to that position.

implementation of the code is as follows:

pseudo code:

void insertion_sort(int a[], int n )
{
  for(int i=0;i<n;i++)
  {
    int temp=a[i];
    int j=1;
    while(temp<a[j-1] && j>0)
     {
       a[j]=a[j-1];
       j=j-1;
     }
    a[j]=temp;
  }
}


pictorial representation of the above pseudo code is as follows:

enter image description here

Since 7 is the first element and it is the largest element, so it's position cannot be changed.since 4 is less than 7 it changes it's position to first. and this process repeats and so on we can get the sorted list.

complexity:

o(n^2) is the final complexity of insertion sort.


merge sort:

  This sorting algorithm depends on divide and rule principle. first divide the array into two halves. Repeatedly sort each half, then merge two halves again.

let's take an example to solve merge sort.

a[]={9,7,8,3,2,1}

In this array "a" first divide it into two halves a1={9,7,8} and a2={3,2,1}. again divide these two halves into sub halves. Repeat the process until they cannot be divided. sort all the parts. now compare a1,  a2 and merge them.

 


arrays and strings

Arrays:  

    Array is a collection of similar data type variables. They can be accessed using an index which generally starts from 0. There are two types of arrays which can store the data in a continuous memory allocations. They are single dimensional array and multi dimensional array.

single dimensional array:

  single dimensional array is 1 dimensional array that stores elements in a linear sequential order. Syntax of declaring one dimensional array is as follows: 

        datatype arrayname[size of the array];

We can use this one dimensional array as follows
       datatype arrayname[size of the array]={Elements of the array};
  
Let us try this with a simple example;

    int array[ ]={2,3,4,5,6,7};            here array is the name of the array.

In the above example if we want to access 4th element we need to give array[3] to get the 4th element. This is because the sequential indexing starts with 0. similarly nth element can be accessed by array[n-1].

multidimensional array:

      It is also called as matrix array. Most commonly used multi dimensional array is 2 dimensional array. It consists of two columns. It is also popularly known as arrays of arrays.It stores elements using 2 indices which gives the information in which row which column the element is placed. A 2D array is essentially a matrix.

   declaration:

        datatype arrayname[size of rows][size of columns];

example: 

      char arr[3][2];
  here arr is a 2D array of character type. The array contains 3 rows and 2 columns. This array can store three words of length two. PI,OM,GD. These words can be stored as follows:

   

Here rows and columns start with 0 index. If you have to access D character, you can access it by arr[2][1].

Strings:

   A string is sequence of characters. Sting is an array of character data type. An instance of a string is called a string literal,  which are enclosed in double quotes(""). 

Declaration:

       char string_name[size of array];
       char str[5];

 string can be initialized as a normal array but with the characters.
 let us try this with an example:
    
    char string[5]={'h','a','i'}

We can initialize this string in another way:
    
   char str[]="hello";

enter image description here

here End of the string can be represented by the null character. In the above example str is a string which has an instance hello. Inspite of n characters the size of the string has n+1 characters because of the null string. The compiler automatically adds the null character at the end of the string. size of the string is always greater than the size of array.
enter image description here