Different Types Of Errors In C

Different Types Of Errors In C

Errors are mistake that we programmer often commit. Errors also called as bugs causes the program to either run unexpectedly ( shows unexpected result ) or prevent the execution of a program. As programmer we are prone to make mistakes. So we should keep in mind the following different types of errors in c which we might commit :

TYPES OF ERRORS

SYNTAX ERROR IN C

  • Syntax Errors are basically compiler errors or compile-time errors which occurs when we do not follow the grammar of the programming language. 
  • It is detected when you compile the program by the compiler.

Syntax Errors occurs : 
  • Due to missing semicolon ( ' ; ' ). It is used as an terminating statement. So when you forget to place a semicolon or use any other alternative then it causes syntax error. 
       #include<stdio.h>
       int main()
       {
         int a=10 // Syntax error as semicolon is missing
         int b=100 : // Syntax error as using ':' instead of ';'
         return 0;
       }
    
  • It occurs when we use a variable which is not declared in program.
  •   #include<stdio.h>
      int main()
      {
         printf("Value of a : %d",a); // error as 'a' is not declared anywhere in program
         return 0;
      }
    
  • Error Occurs due to missing and unmatched parenthesis.
      // Syntax Error as ')' parenthesis is missing
      void sum( 
    
      // Syntax Error as '}' parenthesis is missing
      void product()
      { statement
    
      // Syntax Error due to unmatched parenthesis
      void a{}
    

SEMANTIC ERROR IN C

  • Semantic errors occurs when the statement written in the program are not meaningful to the compiler.
  • Semantic errors indicate an improper use of Java statements.
    Example : int a+b=c; // Semantic Error
    Correct one : int c=a+b;

    int a=+b; // Semantic Error
    Correct one : int a+=b; // Shorthand notation 

LOGICAL ERROR IN C

  • Logical errors are errors that shows unexpected results.
  • It occurs when you write a program that works, but does not do what you intend it to do.
    Example : Suppose you want to find the factorial of a number but instead of multiplying number you end up adding it.
    #include<stdio.h>
     int main()
     {
       int i;
       int factorial=1;
       
       for(i=1;i<=n;i++)
         factorial=factorial+i; // Logical Error. Correct statement : factorial=factorial*i;
    
       return 0;
     }
    

    Though the program would work fine and would not show any syntax or run time error. But the output which you were expecting will not be shown.

LINKER ERROR IN C

  • Linker Errors are errors that occurs when we do not include header files for the predefined functions used in a program and when we  misspell a standard c function.
    #include<stdio.h>
     int Main() // Linker error as 'main' is misspelled as 'Main'
     {
       printf("Hello : ");
       return 0;
     }
    

RUNTIME ERROR IN C

  • Run-time errors are errors that occurs during the execution of the program.
    Example :
    • When we divide a number by zero.
    • When input data is not in the correct format.
    //Runtime error program in c
    #include<stdio.h>
     int main()
     {
       int a=10,b=0,result;
       int number;
    
       result=a/b; // Runtime error
       scanf("%d",&number); // Error occurs when you input some other character instead of 'numbers'
    
       return 0;
     }
    
More Informative Posts :
C Program to add, subtract, multiply and divide two numbers

C Program to add, subtract, multiply and divide two numbers

The following programs takes input of two numbers from user and add, subtract and divide two numbers.

Sample Input / Output :

Enter any two number : 20
10

Sum = 30
Subtracted value = 10
Multiplied value = 200
Division value = 2

// C Program to add, subtract, multiply and divide two numbers
#include<stdio.h>

int main()
{
    int a, b;
    
    printf("Enter any two number : ");
    scanf("%d",&a);
    scanf("%d",&b);
    printf("Sum=%d",a+b);
    printf("\nSubtracted value=%d",a-b);
    printf("\nMultiplied value=%d",a*b);
    printf("\n Division value=%d",a/b);

    return 0;
}
Counting Sort Program In C

Counting Sort Program In C

COUNTING SORT

COUNTING SORT IN C


In the code for counting sort, we assume that the input is an array A[1 . . . n] and  we require two other arrays: the array B[1 . . . n] holds the sorted output, and the array C[0 . . . k] provides temporary working storage. Here k = maximum element present in array.

Consider following elements to be sorted using counting sort : 2, 5, 3, 0, 2, 3, 0, 3

So we have in array A[1 . . . 8 ] :
 2   5   3   0   2   3   0   3 

Now what we have to do is initialize the auxiliary array C[0 . . . k] with 0. Here k = 5.
So C[0 . . . 5] becomes :
 0   0   0   0   0   0 

Next step is to count the frequency of each element and store it in their respective index position i.e here frequency of 0 = 2. So we place '2' at index position '0'. Similarly we place each element and the array becomes C[0 . . . 5] :
 2   0   2   3   0   1 

Now we add the current index position with its previous index position and store it in the current index position i.e C[ i ] = C[ i ] + C[ i - 1 ] where 'i' starts from '1'.

So C[ 0 . . . 5 ] becomes : 
 2   2   4   7   7   8 

The final step is to place the elements in B[ 1 . . . 8 ] with reference to C[ 0 . . . 5 ] i.e  Now we treat elements in C[ 0 . . . 5 ] as index of B[ 1 . . . 8 ] and index of C[ 0 . . . 5 ] as elements of B[ 1 . . . 8 ]. So at index position '8' we have element '5' so we place '5' at index position of '8' of B[ 1 . . . 8 ] ( B[ 8 ] = 5 ) and we reduce the index position by '1' i.e 8-1 = 7. Now note that we have element '7'  in C[ 4 ] position but '4' is not present in the original array so we skip it and move to C[ 3 ] position, so we place '3' at index position '7' of B[ 1 . . . 8 ]. Similarly we place each element in B[ 1 . . . 8 ] and we get sorted array.

So the sorted array B[ 1 . . . 8 ]  is :
 0   0   2   2   3   3  3  5 



// Counting Sort algorithm
CountingSort(A,B,n,k)
   int C[0 . . . k ]
   for i=0 to k
      C[i]=0
   for j=1 to n
      C[A[j]] = C[A[j]] + 1;
   for i=1 to k
      C[i] = C[i] + C[i-1];
   for j=n downto 1
      B[C[A[j]]] = A[j];
      C[a[j]] = C[A[j]] - 1;


// Counting sort program in c

#include<stdio.h> 

void CountingSort(int a[], int sorted_array[], int max_element, int n);

int main() 
{ 
 int a[20],i,n; 
 int max_element, sorted_array[20];
 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=1;i<=n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before counting sort
 printf("Items in the array are : "); 
 for(i=1;i<=n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 // Finding Maximum element
 max_element=a[1];
 
 for(i=2;i<=n;i++)
 {
  if(a[i] > max_element)
  {
           max_element = a[i];
  }
 }
 
 //Applying counting sort
 CountingSort(a, sorted_array, max_element, n); 
 
 // Displaying elements after count sort
 printf("\nElements after count sort : "); 
 for(i=1;i<=n;i++) 
 { 
    printf("%d ",sorted_array[i]); 
 } 
    
 return 0; 
} 

void CountingSort(int a[],int sorted_array[],int max_element, int n)
{
 int aux_array[max_element];
 int i,j;
 
 // Initializing auxiliary array
        for(i=0;i<=max_element;i++)
 {
  aux_array[i]=0;
 }
 
        // Placing Frequency of each element in aux_array
 for(j=1;j<=n;j++)
 {
  aux_array[a[j]]=aux_array[a[j]]+1;
 }
 
        // Adding elements of current and previous index position
 for(i=1;i<=max_element;i++)
 {
  aux_array[i]=aux_array[i]+aux_array[i-1];
 }
 
        // Placing elements in sorted_array 
 for(j=n;j>=1;j--)
 {
  sorted_array[aux_array[a[j]]] = a[j];
  aux_array[a[j]] = aux_array[a[j]] - 1;
 }
}


 More Informative Posts :

Selection Sort Program In C

Selection Sort


SELECTION SORT IN C

We start Selection Sort by scanning the entire given list to find its smallest element and exchange it with the first element, putting the smallest element in its final position in the sorted list. Then we scan the list, starting with the second element, to find the smallest among the last n - 1 elements and exchange it with the second element, putting the second smallest element in its final position. Generally, on the ith pass through the list, which we number from 0 to n - 2, the algorithm searches for the smallest item among the last n - i elements and swaps it with A[i].


Consider the following element that is to be sorted using selection sort :  89, 45, 68, 90, 29, 34, 17.
The analysis of selection sort is straightforward. The input's size is given by the number of elements 'n' and the algorithm's basic operation is the key comparison A[j] < A[min]. The number of times it is executed depends only on the array's size.

Selection Sort In C : Showing how elements are sorted
Selection Sort In C : Showing how elements are sorted

The above figure shows how given elements 89, 45, 68, 90, 29, 34, 17 are sorted according to selection sort. Each line corresponds to one iteration of the algorithm i.e. a pass through the list tail to the right of the vertical bar. An element in bold indicates the smallest element found. Elements to the left of the vertical bar are in their final positions and are not considered in this and subsequent iterations. 

SELECTION SORT ALGORITHM

SelectionSort(int a[],int n)
   for i=0 to n-2
     min=i

     for j=i+1 to n-1
        if a[min] > a[j]
           min = j
   
     swap a[i] with a[min]

   

SELECTION SORT PROGRAM IN C

// Selection sort program in c

#include<stdio.h> 

void SelectionSort(int [],int); 
 

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before selection sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 //Applying selection sort
 SelectionSort(a,n); 
 
 // Displaying elements after selection sort
 printf("\nElements after selection sort : "); 
 for(i=0;i<n;i++) 
 { 
 printf("%d ",a[i]); 
 } 
 return 0; 
} 

void SelectionSort(int a[],int n) 
{ 
 int i,loc,j,min,temp; 
 for(i=0;i<=n-2;i++) 
 { 
   min = i;
 
   for(j=i+1;j<=n-1;j++) 
   {   
     // Finding minimum element
     if(a[min] >a[j])  
     { 
       min=j;  
     } 
   }
  
   //Swapping a[i] with a[min]
   temp=a[i]; 
   a[i]=a[min]; 
   a[min]=temp;
 } 
}

More Informative Posts :

Bubble Sort Program In C

Bubble Sort


BUBBLE SORT IN C

Back To Bubble Sort

Bubble Sort is a popular but inefficient sorting algorithm.  Bubble Sort is another brute-force application to the sorting problem that compares adjacent elements of the list and exchange them if they are out of order. By doing it repeatedly, we end up "bubbling up" the largest element to the last position on the list. The next pass bubbles up the second largest element, and so on until, after n - 1 passes, the list is sorted. Pass i (0 <= i <= n - 2) of bubble sort can be represented by the following diagram: 

Consider element to be sorted are : 89, 45, 68, 90, 29, 34, 17 

Bubble Sort In C : Swapping elements
Quick Sort In C : Showing how elements are sorted


First two passes of bubble sort on the given list 89, 45, 68, 90, 29, 34, 17 is shown in above figure.  A new line is shown after a swap of two elements is done. The elements to the right of the vertical bar are in their final positions and are not considered in  subsequent iterations of the algorithm.

BUBBLE SORT ALGORITHM


// Algorithm for Bubble Sort
BubbleSort(int a[],int n)
  for i=0 to n-2
    for j=0 to n-2-i
      if a[j] > a[j+1]
        swap a[j] with a[j+1]

BUBBLE SORT PROGRAM IN C


// Bubble sort program in c

#include<stdio.h> 

void bubblesort(int a[],int n);

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
 printf("Enter number %d: ",i+1); 
 scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before bubble sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
 printf("%d ",a[i]); 
 } 
 
 //Applying bubble sort
 bubblesort(a,n); 
 
 // Displaying elements after bubble sort
 printf("\nElements after bubble sort : "); 
 for(i=0;i<n;i++) 
 { 
   printf("%d ",a[i]); 
 } 
 return 0; 
} 

void bubblesort(int a[],int n) 
{ 
  int i,j;
  for(i=0; i<=n-2; i++) 
  { 
    for(j=0;j<=n-i-2;j++) 
    { 
       // Swapping elements
       if(a[j]>a[j+1]) 
       { 
         int temp=a[j]; 
         a[j]=a[j+1]; 
         a[j+1]=temp; 
      } 
   } 
 } 
} 


More Informative Posts :

GOOD PROGRAMMING PRACTICES

GOOD PROGRAMMING PRACTICES


GOOD PROGRAMMING PRACTICES - FUNDAMENTALS

  • Every function should be preceded by a comment describing the purpose of the function.
  • Add a comment to the line containing the right brace, } that close every function, including the main(). This helps in determining that the function is ended.
  • Indent the entire body of each function. This indentation emphasizes the functional structure of a program and helps make program easier to read.
  • Set a convention for the size of indent you prefer and then uniformly apply that convention.
  • Choosing meaningful variable name helps make a program self-documenting i.e fewer comments are needed.
  • Multiple-word variable names can help make a program more readable.Separate the words with underscore eg : comp_psyche or good_programming_practices.
  • Place a space after each comma to make a program more readable.
  • Place spaces on either side of binary operator. This makes the operator stand out and makes the program more readable.
  • Although it is allowed that we can have multiple statement in a single line but to make program more readable there should be only one statement per line in a program.

GOOD PROGRAMMING PRACTICES - CONTROL STRUCTURES

  • Indent both body statement of an if...else statement.
  • If there are several level of indentation, each level should be indented with same additional amount of space.
  • When performing division by an expression whose value could be zero, explicitly test this case and handle it appropriately in your program ( such as printing an error message ) rather than allowing the fatal error to occur.
  • In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user what the sentinel value is.
  • Too many levels of nesting can make a program difficult to understand. As a rule, try to avoid using more than three levels of nesting.
  • Limit the size of the control statement headers to a single line if possible.
  • Although the case clauses and the default case clause in a switch statement can occur in any order but its advisable to place the default clause at last.
  • In a switch statement when the default clause is last then the break statement is not required.

GOOD PROGRAMMING PRACTICES - FUNCTION

  • Familiarize yourself with rich collection of functions in C standard library.
  • Although It is not incorrect to do so but do not use the same names for a function's arguments and the corresponding parameters in function definition. This helps avoid ambiguity.
  • Choosing meaningful function names and meaningful parameter names makes program more readable and helps avoid excessive use of comments.
  • Parameter names are sometimes included in function prototype for documentation purposes. The compiler ignore these names.
  • Use only uppercase letters in the names of enumeration constants to make these constants stand out in a program and to indicate that enumeration constants are not variable.  

GOOD PROGRAMMING PRACTICES - ARRAY

  • Defining the size of each array as a symbolic constant make program more readable.
  • Use only uppercase letter for symbolic constant names. This makes these constants stand out in a program and reminds you that symbolic constants are not variable.
  • In multi-word symbolic constant names, separate the words with underscores for readability.
  • Strive for program clarity. Sometimes it may be worthwhile to trade off the most efficient use of memory or processor time in favor of writing clearer programs.
  • When passing an array to a function, also pass the size of the array. This helps make function reusable in many programs.

GOOD PROGRAMMING PRACTICES - STRING

  • When storing a string of characters in a character array be sure that the array is large enough to hold the largest string that will be stored.
  • Familiarize yourself with the various predefined string function. This helps in achieving task easily.
  • When using functions from the string-handling library, include the <string.h> header.

GOOD PROGRAMMING PRACTICES - POINTERS


  • Its preferable to include the letters Ptr in pointer variable names to make it clear that these variables are pointer and thus need to be handled appropriately.
  • Initialize pointer to prevent unexpected result.
  • If a variable does not change in the body of a function to which it is passed, the variable should be declared const to ensure that it is not accidentally modified.
  • Pass large objects such as structures using pointers to constant data to obtain the performance benefits of pass-by-reference.

GOOD PROGRAMMING PRACTICES - STRUCTURE AND UNION

  • Always provide a structure tag name when creating structure type. The structure type name is convenient for declaring new variables of the structure type later in the program.
  • Do not use spaces around  '->' and '.' operators. Omitting spaces helps emphasize that the expressions the operators are contained in are essentially single variable names.
  • Passing structure by reference is more efficient than passing structure by value.
  • Use typedef to help make a program more protable.
  • Capitalize the first letter of the typedef names to emphasize that they are synonyms for other types names.
  • Using typedef can help make a program more readable and maintainable.

C Programming In Linux

C Programming In Linux

C Programming in Linux : In this tutorial we are going to study how to write, compile and run c program in Linux. Linux Wall command and make command  is also explained.

Contents


HOW TO WRITE C PROGRAM IN LINUX

Back to content

A c program is written in a text editor and is saved with ".c" extension. ".c" helps Unix or Linux OS(operating system) to identify that it is a C program.
I am assuming that all of you can have an access to a text editor and you know how to write in it and save it.

Lets write our first c program :

#include<stdio.h>
int main()
{
   printf("Yepeeeeeee this is my first C program\n"); // Displays the string as output
   return 0; // tell the OS that the program exited without errors
}

Type the above code in any editor and save it with ".c" extension say "firstprogram.c"


Explanation :

The execution of a C program starts with main() function.

// ( Double slash ) is a single line comment and is ignored by the compiler. It is used by the programmer to explain the working of the programs. so that other programmer who reads the program written by him would understand what the program is exactly doing.

/*

Written anything
.......

*/

The above syntax is for multiline comment i.e any text written in between is ignored by the compiler.

Now what does first line #include<stdio.h> mean :

The first line may be confusing, but it’s just a C syntax that tells the compiler to include headers for a standard input/output (I/O) library named "stdio.h". This header file is added to the program when it is compiled. It is located at /usr/include/stdio.h and it defines several constants and function prototypes for corresponding functions in the standard I/O library. Since the main() function uses the printf() function from the standard I/O library, a function prototype is needed for printf() before it can be used. This function prototype (along with many others) is included in the "stdio.h" header file. A lot of the power of C comes from its extensibility and libraries.

In  printf("Yepeeeeeee this is my first C program\n") we have used "\n" this is nothing but a escape sequence and is known as newline character and it causes the cursor to move to the start of the next line.

You can read more about escape sequence from : ESCAPE SEQUENCE

HOW TO COMPILE C PROGRAM IN LINUX

Back to content

Linux has a compiler named CC ( The C Compiler ) for compiling the C programs written in a text editor. Most unix or linux version also contain The GNU Compiler Collection (GCC) which is a free C compiler that translates C into machine language that a processor can understand.A compiler converts a high-level language into machine language.

How to compile  C program in Linux:


Note : The followed command should be issued carefully in terminal and keep in mind of the directory in which you are working. i.e if you have saved your file in media directory then in terminal you should type cd /media to go to that directory and then issue the following command. If you launch terminal from your taskbar or menu then the working directory is by default /home/username. It would be a better idea to open your terminal from the same directory in which your file is saved.

For compiling a C program you can simply type :

cc firstprogram.c or
gcc firstprogram.c

Now what does the above two statement does :

This will try to compile firstprogram.c and if successful will produce a runnable file called "a.out" which is a default name. If you want to give the runnable file a better name you can type :

cc firstprogram.c -o firstprogram ( or cc firstprogram.c -o testprog.out )
gcc firstprogram.c -o firstprogram ( or gcc firstprogram.c -o firstprogram.out )

This will compile firstprogram.c and  create a  runnable file firstprogram
If you notice we have excluded the extension ".out" but not to worry with extension or without extension your runnable or executable file will work.

LINUX MAKE COMMAND

Back to content

UNIX or Linux also includes a very useful program called "make". Make allows very complicated programs to be compiled quickly, by reference to a configuration file (usually called Makefile). If your C program is a single file, you can usually use "make" by simply typing :

make firstprogram

This will compile firstprogram.c and put the executable code in firstprogram
"make" does the same task what cc firstprogram.c -o firstprogram or gcc firstprogram.c -o firstprogram does.

LINUX WALL COMMAND

Back to content

The -Wall option causes the compiler to warn you about legal but dubious code constructs, and will help you catch a lot of bugs very early. To use -Wall option you can type :

gcc -Wall -c firstprogram.c or
cc -Wall -c firstprogram.c

If you want to be even more specific you can type :

gcc -Wall -Wstrict-prototypes -ansi -pedantic -c firstprogram.c or
cc -Wall -Wstrict-prototypes -ansi -pedantic -c firstprogram.c

The -Wstrict-prototypes option means that the compiler will warn you if you haven't written correct prototypes for all your functions. The -ansi and -pedantic options cause the compiler to warn about any non-portable construct (i.e  constructs that may be legal in gcc but not in other standard C compilers. We should try to avoid such features).

Note - Running the commands :

gcc -Wall -c firstprogram.c or
cc -Wall -c firstprogram.c

gcc -Wall -Wstrict-prototypes -ansi -pedantic -c firstprogram.c or
cc -Wall -Wstrict-prototypes -ansi -pedantic -c firstprogram.c

produces object file named firstprogram.o

So the next step is to make a runnable or executable file from the object file. To make an runnable or executale file type :

gcc firstprogram.o -o firstprogram or 
cc firstprogram.o -o firstprogram

This produces an executable file named firstprogram

To create an executable file directly without producing an object file. You can type :

gcc -g -Wall -o firstprogram firstprogram.c or
cc -g -Wall -o firstprogram firstprogram.c

This produces an executable file named firstprogram without producing an object file firstprogram.o


HOW TO RUN C PROGRAM IN LINUX

Back to content

Now that we are done with writing and compiling our code. Lets run it. You can run your code by simply typing the runnable or executable file name i.e type :

firstprogram

If in case the above command show error and does not execute your runnable file then you can type :

./firstprogram

This tells the compiler that the executable file is in the current working directory.

HOW DO YOU FEEL

Back to content

Now that you have executed your first C program. Tell us how do you feel by simply dropping a comment in the comment box.

More Informative post :

Quick Sort Program In C

Quick Sort

QUICK SORT IN C

Back to Quick Sort

Quick Sort is another sorting algorithm that is based on divide and conquer approach. Unlike merge sort that divides input elements according to their position in array, quick sort divides input element according to their values. Here is a three-step divide and conquer process for sorting a typical sub-array.

Need Python Homework Help: Get Python Homework Help from Epert

Divide : Partition or rearrange the array a[p . . r] into two sub-arrays a[ p . . q-1 ] and a[q+1 . . r] such that a[ p . . q-1 ] <= a[q] <= a[q+1 . . r] . Compute the index q as part of this partition procedure. Here a[q] is called the pivot element.

Conquer : Sort the two sub-arrays a[ p . . q-1 ] and a[q+1 . . r]  by recursive calls to quick sort.

Combine : Because the sub-arrays are already sorted, no work is needed to combine them : the entire array a[ p . . r ] is now sorted.

Lets understand Quick Sort with the help of an example : 

Array Elements ( List ) : 2 8 7 1 3 5 6 4

Steps :

  • Select the pivot element ( 4 in this case )
  • Rearrange elements such that elements before pivot element are less than it and element after pivot element are greater than it. This arrangement of elements in accordance with the pivot element is called partition operation.
  • Sort the sub-array recursively. 
Steps for Quick Sort
Steps for Quick Sort
  • The above image shows the partition of Array elements ( Initial list ).
  • Similarly the two sub-array before and after pivot element are partitioned.
  • The complete steps of quick sort is shown below.
Quick Sort Program In C
Quick Sort 

QUICK SORT ALGORITHM


// Algorithm for Quick Sort

QUICKSORT(a, p, r)
  if p<r
    q = PARTITION(a, p, r)
    QUICKSORT(a, p, q-1)
    QUICKSORT(a, q+1, r)

Partitioning the array :

PARTITION(a, p, r)
  x=a[r]
  i=p-1
  
  for j=p to r-1
     if(a[j]<=x)
        i=i+1
        swap a[i] with a[j]
  end loop
  
  swap a[i+1] with a[r]
  return i+1


QUICK SORT PROGRAM IN C


//Quick sort program ( code ) in c

#include<stdio.h> 

void quicksort(int a[],int p, int r); 
int partition(int a[],int p, int r); 

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before quick sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 //Applying quick sort
 quicksort(a,0,n-1); 
 
 // Displaying elements after quick sort
 printf("\nElements after quick sort : "); 
 for(i=0;i<n;i++) 
 { 
    printf("%d ",a[i]); 
 } 
 return 0; 
} 

void quicksort(int a[],int p, int r) 
{
   int q;
   if(p<r)
   {
     // q - index at which pivot element lies
     q=partition(a,p,r);

     // Sorting sub-array recursively
     quicksort(a,p,q-1);
     quicksort(a,q+1,r);
   }
}

int partition(int a[],int p, int r)
{
   int temp;
   int i=p-1;
   int j;

   // pivot element around which partition is done
   int x=a[r];
 
   for(j=p;j<=r-1;j++)
   {
     if(a[j]<=x)
     {
       i=i+1;
       temp=a[i];
       a[i]=a[j];
       a[j]=temp;
     }
   }
 
   temp=a[i+1];
   a[i+1]=a[r];
   a[r]=temp;
   return (i+1);
}

Quick Sort Program Output

Quick Sort Program In C With Output
Quick Sort : Quick Sort Program Output

More Informative Posts :
    Merge Sort Program In C

    Merge Sort Program In C

    Here I am providing you with Merge Sort program in c.
    #include<stdio.h> 
    
    void mergesort(int a[],int i, int j); 
    void merge(int a[],int p , int q, int r1); 
    
    int main() 
    { 
     int a[20],i,n,item; 
     printf("Enter number of elements in array : "); 
     scanf("%d",&n);
      
     // Inputting elements
     for(i=0;i<n;i++) 
     { 
       printf("Enter number %d: ",i+1); 
       scanf("%d",&a[i]);
     } 
     
     // Displaying Elements before merge sort
     printf("Items in the array are : "); 
     for(i=0;i<n;i++)
     { 
       printf("%d ",a[i]); 
     } 
     
     //Applying merge sort
     mergesort(a,0,n-1); 
     
     // Displaying elements after merge sort
     printf("\nElements after merge sort : "); 
     for(i=0;i<n;i++) 
     { 
       printf("%d ",a[i]); 
     } 
     return 0; 
    } 
    
    void mergesort(int a[],int i, int j) 
    { 
     int mid; 
     if(i>=j) 
     return; 
     
     else 
     { 
       mid=(i+j)/2; 
       mergesort(a,i,mid); 
       mergesort(a,mid+1,j); 
       merge(a,i,mid,j);  
     } 
    } 
    
    void merge(int a[],int p , int q, int r) 
    { 
     int n1=q-p+1; 
     int n2=r-q;
     int left[n1+1];
     int right[n2+1]; 
    
     int i=0;
     int j=0;
     int k=0;
     
     
     for(i=0;i<n1;i++) 
     {
       left[i]=a[p+i]; 
     }
     
     for(i=0;i<n2;i++) 
     {
       right[i]=a[q+i+1];
     }
     
     left[n1]=9999; 
     right[n2]=9999;  
     
     i=0;
     j=0;
     
     for(k=p;k<=r;k++) 
     { 
     
       if(left[i]<right[j]) 
       { 
         a[k]=left[i]; 
         i++; 
       } 
     
       else 
       { 
         a[k]=right[j]; 
         j++; 
       } 
     } 
    } 
    
    
    More Informative Posts :
    C PROGRAM TO FIND FIBONACCI SERIES

    C PROGRAM TO FIND FIBONACCI SERIES

    WHAT IS FIBONACCI SERIES

    Fibonacci series : Fibonacci series is one in which the nth term is sum of (n-1)th term and (n-2)th term. The first two numbers of series are 0 and 1.
    For example: 0 1 1 2 3 5 8 13 21 and so on

    Now we can write a c program to find fibonacci series in the following ways :

    PROGRAM TO FIND FIBONACCI SERIES USING LOOPS

    //C PROGRAM TO PRINT FIBONACCI SERIES USING LOOPS
     
     #include<stdio.h>
     
     int main()
     {
      /* Declaring variable for n=number, f=first, s=second, 
      t=third number, i=to iterate the loop */
      int n,f,s,t,i;
      
      // Inputing number till where fibonacci series is to be printed
      printf("Enter the number till which you want to print fibonacci series:");
      scanf("%d",&n);
      
      // Determining and printing fibonacii series
      printf("Fibonacci Series: ");
      
      f=0;
      s=1;
      printf("%d %d ",f,s);
      for(i=3;i<=n;i++)
      {
       t=f+s;
       printf("%d ",t);
       f=s;
       s=t;
      }
      
      return 0;
     }
    

    C PROGRAM TO FIND FIBONACCI SERIES USING FUNCTION

    //C PROGRAM TO FIND FIBONACCI SERIES USING FUNCTION
    #include<stdio.h>
    
    void fibonacci(int n);
    int main()
    {
      int n;
    
      // Inputing number till where fibonacci series is to be printed
      printf("Enter the number till which you want to print fibonacci series:");
      scanf("%d",&n);
      
      fibonacci(n);
      return 0;
    }
    
    void fibonacci(int n)
    {
      /* Declaring variable for f=first, s=second, 
      t=third number, i=to iterate the loop */
      int f,s,t,i;
      
      // Determining and printing fibonacii series
      printf("Fibonacci Series: ");
      
      f=0;
      s=1;
      printf("%d %d ",f,s);
      for(i=3;i<=n;i++)
      {
       t=f+s;
       printf("%d ",t);
       f=s;
       s=t;
      }
    }
    

    C PROGRAM TO FIND FIBONACCI SERIES USING RECURSION

    //WRITE A C PROGRAM TO FIND FIBONACCI SERIES USING RECURSION
    #include<stdio.h>
    
    int fibonacci(int n);
    
      /* Declaring variable for f=first, s=second, 
      t=third number, i=to iterate the loop */
      int f,s,t,i;
      f=0;
      s=1;
    
    int main()
    {
       int n;
      // Inputing number till where fibonacci series is to be printed
      printf("Enter the number till which you want to print fibonacci series:");
      scanf("%d",&n);
      
      printf("Fibonacci Series: ");
      printf("%d %d ",f,s);
      
      fibonacci(n);
      return 0;
    }
    
    int fibonacci(int n)
    {
     if(n==2)
     {
        return 0;
     }
     
     else
     {
        t=f+s;
        printf("%d ",t);
        f=s;
        s=t;
        fibonacci(n-1);
     }
    }
    
    Note : You can write much better code than these. So view these example and try to program by yourself. Use your own logic. This would improve your programming skills.
    Reverse String In C / Reversing String In C

    Reverse String In C / Reversing String In C

    Reversing string in C / Reverse String In C seems to be a daunting task for the newbies but after reading this post you can easily reverse string in C.

    What Is Reverse String In C

    Reverse string in c is basically taking input( i.e sentence ) from console and then display the sentence from last character to first character.

    The following Program to reverse string in c accepts a string from the user and print the reverse string. For example consider the following input from the user :

    Input String : The site name is comp-psyche.com
    Output String : moc.ehcysp-pmoc si eman etis ehT

    There are various ways to reverse string in c. You can either use string function to reverse string in c or you can reverse string in c without using c string function.
    In the following program we will reverse string in c using string function streev()

    
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
     // Declaring variable str=string 
     char str[50];
     
     // Inputing string
     printf("Enter any string : ");
     gets(str);
    
     // Printing string and reversed string
     printf("String : %s\n",str);
     printf("Reversed string : %s",strrev(str));
    
     return 0;
    }
    

    REVERSE STRING IN C WITHOUT USING STRING FUNCTION

    In the following program we will reverse string in c without using string function

    
    
    int main()
    {
     // Declaring variable str=string, revstr[50]=reverse string
     char str[50], revstr[50];
     
     // Declaring variable i=to iterate loop, l=length
     int i, j,l=0;
     
     // Inputing string
     printf("Enter any string : ");
     gets(str);
    
     // finding length
     while(str[l]!='\0')
     l++;
     
     // Reversing string
     j=0;
     for(i=l-1;i>=0;i--)
     {
      revstr[j]=str[i];
      j++;
     }
     revstr[j]='\0';
     
     // Printing string and reversed string
     printf("String : %s\n",str);
     printf("Reversed string : %s",revstr);
    
    }

    REVERSE STRING IN C USING RECURSION

    In the following program we will reverse string in c using recursion

    
    // Write a c program to reverse a string using recursion
    #include<stdio.h>
    void reverse (int index, char *str );
    
    int main (void)
    
    {
    
       char str[100];
       printf ("Enter any string : "); 
       gets(str);
     reverse (strlen(str) , str );
     return 0;
    
    }
    
    void reverse (int index, char *str )
    
    {
    
      if (--index < 0 )
    
      {
           return ;
      }
    
      else
      {
            putchar ( *(str + index) ) ;  
            reverse (index, str) ;
      }
    
    }
    
    

    REVERSE STRING IN C USING POINTER

    In the following program we will reverse string in c using pointer

    // Write a C program to reverse a string using pointer
    #include<stdio.h>
    int main()
    {
        
        // Declaring variable str = string and revstr = to store the revere string
        char str[50];
        char revstr[50];
        
        char *strptr = str; // strptr - holds the first position address of str
        char *revptr = revstr; // revptr - holds the first position address of revstr
        int i=-1;
    
        // Inputting string
        printf("Enter any string : ");
        gets(str);
       
        // strptr is pointed to the last position address
        while(*strptr)
        {
            strptr++;
            i++;
        }
    
        // string stored in str is copied to revstr
        while(i>=0)
    {
           strptr--;
           *revptr = *strptr;
           revptr++;
           --i;
        }
    
        *revptr='\0';
      
        printf("Reverse of string is : %s",revstr);
      
        return 0;
    }
    


    Best C Compiler For Windows

    Here I am providing you with three best c compiler for windows - CodeBlock, Dev C and Turbo C compiler. CodeBlock and Dev C are actually IDEs (Integrated Development Environment or Interactive Development Environment) whereas Turbo C is a basic compiler. CodeBlock which is provided here uses mingw compiler whereas Dev C uses gcc compiler. Though many suggest not to use Turbo C to learn c programming but as it is well documented and basic program runs without errors(pretty good). So I decided to keep it here.


    BEST C COMPILER


    C PROGRAMMING USING CODEBLOCKS

    DOWNLOAD CODE BLOCKS


    Code Blocks is an integrated development environment or IDE which uses mingw compiler or gcc compiler. Code Blocks provided here uses mingw compiler which is one of the best c compiler for windows to compile and run c program. This version of Code Block runs in Windows 7 / Windows 8. For windows XP it is not tested.

    You can download free c compiler for windows from : Download Code Blocks For Free

    HOW TO INSTALL CODE BLOCKS

    Back To Best C Compiler

    Now that you have downloaded CodeBlocks the next thing which you should know is how to install CodeBlocks. So follow these steps to install it :
    • Open the folder where you have downloaded CodeBlocks.
    • Run the exe file. A window pops up.

      Best C Compiler - How to install CodeBlocks : First step
      Best c compilers :  First Step

    • Click on next. Another window of License Agreement pops up.
      Best C Compiler - How to install CodeBlocks : License Agreement
      Best c compilers :  License Agreement
    • Click on I Agree. A window of Choose Components pops up.

      Best C Compiler - How to install CodeBlocks : Choose Components
      Best c compilers :  Choose Components
    • Click on Next. Install windows pops up.

      Best C Compiler - How to install CodeBlocks : Install Location
      Best c compilers :  Choose Install Location
    • Choose the location where you want CodeBlocks to be installed and then click on Install.
    • After Installation a windows pops up saying if you want to run CodeBlocks. Click on yes to run it.
    • A window of Installation Completion pops up.
      Best C Compiler - How to install CodeBlocks : Installation Completion
      Best c compilers :  Installation complete

    • Click on Next. Another windows pops up.

      Best C Compiler - How to install CodeBlocks : Finish Window
      Best c compilers :  Finishing the setup
    • Click on Finish. 

    HOW TO WRITE C PROGRAM

    Back To C Compiler

    Now that you have finished Installing Code Blocks. Lets write a simple c program.

    #include<stdio.h>
    int main()
    {
          printf("Congratulation.. You successfully run your first Program");
          return 0;
    }

    Note : If you want to know what the syntax of the c program then you can read it from : Basic Component Of C Program

    Now the question arises where should you write this code. Follow these steps to write your first C Program: 
    • Click on File - New - File...

      Best C Compiler - How to write C Program : File-New-File...
      Best c compilers :  How to write c program

    • Select C/C++ Source and click on Go.

      Best C Compiler - How to write C Program : C/C++ Source
      Best c compilers :  How to write c program

    • A window for Language Selection pops up. Select C and click on Next.

      Best C Compiler - How to write C Program : Language Selection
      Best c compilers :  How to write c program

    • Enter the File Location with File Name i.e where you want to save your file and click on Finish.

      Best C Compiler - How to write C Program : File Location with File Name
      Best c compilers :  How to write c program

    HOW TO COMPILE AND RUN C PROGRAM

    Back To Best C Compiler

    Congratulation You successfully wrote your first c program. Now the next step is to Compile and Run it. To Compile and Run your first c program follow these steps :
    • To Compile c program : Click on Build - Compile Current File. You can also use shortcut key - Ctrl + Shift + F9
    • To Run c program : Click on Build - Run. You can also use shortcut key - Ctrl + F10
    • To Compile and run c program at the same time : Click on Build - Build and Run. you can achieve the same task by pressing F9

    DOWNLOAD DEV C

    Back To Best C Compiler

    Dev C is another integrated development environment or IDE. Dev C provided here uses gcc compiler which is one of the best c compiler for windows with good graphic and user friendly environment. You can easily write, compile and run a c program using Dev C. This version of Code Block runs in Windows 7 / Windows 8. For windows XP it is not tested.

    You can download free c compiler for windows from : Download Dev C For Free

    HOW TO INSTALL C COMPILER DEV C

    Back To Best C Compiler

    Now that you have downloaded Dev C. Lets install it. Follow these step to install Dev C.
    • Open the folder where you have downloaded Dev C..
    • Run the exe file. Installer Language windows pops up. Select language according to your preference and then click OK.
      Best C Compiler - How to install Dev c/c++ : Installation language
      Best c compilers :  Installer Language

    • Another window of License Agreement pops up. Click I Agree.

      Best C Compiler - How to install Dev C/C++ : License Agreement
      Best c compilers : License Agreement


    • Choose Components windows Appears. Click Next.

      Best C Compiler - How to install Dev C/C++ : Choose component
      Best c compilers : Choose Components

    • Install windows pops up. Choose the location where you want Dev-C++ to be installed and then click on Install.

      Best C Compiler - How to install Dev C/C++ : Choose Install Location
      Best c compilers : Choose Install Location

    • Installation Completion windows pops up. Click on Finish.

      Best C Compiler - How to install Dev C/C++ : Installation Completion
      Best c compilers : Finishing the setup

    HOW TO WRITE C PROGRAM

    Back To Best C Compiler

    Now that you have finished Installing Dev C. Lets write a simple c program.

    #include<stdio.h>
    int main()
    {
          printf("Congratulation.. You successfully run your first Program");
          return 0;
    }

    Note : If you want to know about the syntax of c program  then you can read it from : Basic Component Of C Program

    Now where should you write the above code. Follow these steps to write your first c program :
    • Click on File - New - Source File
    • An editor opens up. Write your c program and then save it with ".c" extension.
    • To save c program : Click on File - Save As...
    • Give a name to your file and save it as C source files.

      Best C Complier - Saving c program in Dev C/C++
      Best c compilers : How to write c program in Dev C/C++

    HOW TO COMPILE AND RUN C PROGRAM

    Back To Best C Compiler

    Lets Compile and Run your first c program. Follow these steps to compile and run c program :
    • To compile c program : Click on Execute - Compile or F9
    • To Run c program : Click on Execute - Run or F10
    • To Compile and Run : Click on Execute - Compile & Run or F11