Sunday, 31 August 2014

C Function to compare two strings

This is a C function to compare two strings. The function takes two strings as arguments, loops while the characters in both the string are equal and the end of either string is not reached.  After finishing the loop, it returns the difference of ASCII values (string1[i] - string2[i]) of the characters where the loop is stopped. 

So the final value may be:
          -ve, if string 1 is less than string 2
          +ve, if string 1 is greater than string 2
           0 , if both the strings are same


Source Code


# include <stdio.h>
# include <conio.h>

/* Function definition */
int cmpstr (char str1 [], char str2[] ) {
    int i, diff;

    for (i=0;str1[i]==str2[i] && str1[i]!=0 && str2[i]!=0;i++);
    diff = str1[i]-str2[i];

    return diff;
}



int main() {
    char str1[30], str2[30];
    int diff;

    clrscr();

    printf("Enter a string:");
    scanf("%s", str1);
    printf("Enter another string:");
    scanf("%s", str2);


    diff=cmpstr(str1, str2); // Function Call

    if (diff<0)
        printf("\n\nstring 1 (%s) is less than string 2 (%s)", str1, str2);
    else if (diff==0)
        printf("\n\nstring 1 (%s) and  string 2 (%s) are same", str1, str2);
    else
        printf("\n\nstring 1 (%s) is greater than string 2 (%s)", str1, str2);



    getch();
    return 0;
}


Output

String1 is less than String2










String1 is greater than String2









String1 and  String2 are same





C Function to find out the length of a string

This is a function written in C language to find out the length of a string given by the user.


Source Code

# include <stdio.h>
# include <conio.h>

/* Function definition */
int lenstr (char str [] ) {
    int len=0;
    while (str[len++]!=0);
    len--;
    return len;
}




int main() {
    char str[30];
    int len=0;

    clrscr();

    printf("Enter a string:");
    scanf("%s", str);
    len=lenstr(str); // Function Call
    printf("\n\nLength of the string: %d", len);

    getch();
    return 0;
}



Output


C Program to merge two sorted arrays

 This program merges two sorted arrays and creates a third array with the values from the two arrays. The final array also is in sorted form. Here first element of list1 and list2 are compared, the lesser value will be assigned to list3. Index of the array, from where the value is taken, ie. i if the array is list1 and j if the array is list2 will be incremented. Index of the third array ie. k will be incremented in both cases. This process will be repeated up to the end of either list1 or list2.

Finally, if list1 or list2  contains any remaining values, it will be copied to list3.


Source Code

#include <stdio.h>
#include <conio.h>

int main() {
    int list1[6]={ 1, 3, 5, 7, 9, 11 };
    int list2[8]={ 2, 4, 6, 8, 10, 12, 13, 14 };
    int list3[14], i, j, k;

    clrscr();


    for (i=0, j=0, k=0; i<6 && j<8 ; k++) {
        /* 

             if ith element of list1 is less than jth element of list2, takes value from list1
             otherwise takes value from list2 and assigns to list3.
      */
        if (list1[i] < list2[j]) {
            list3[k] = list1[i];
            i++;
        }
        else {
            list3[k] = list2[j];
            j++;
        }

    }

  /* If list1 has remaining values assigns them to list3*/

    for (; i<6 ;i++, k++) {
        list3[k] = list1[i];
    }


  /* If list2 has remaining values assigns them to list3 */
     for (; j<8 ;j++, k++) {
        list3[k] = list2[j];
    }


    printf("\n\nList 1\n\n");
    for (i=0; i<6 ; i++) {
        printf ("%d ", list1[i]);
    }

    printf("\n\nList 2\n\n");
    for (i=0; i<8 ; i++) {
        printf ("%d ", list2[i]);
    }

    printf("\n\nList 3\n\n");
    for (i=0; i<14 ; i++) {
        printf ("%d ", list3[i]);
    }

    printf("\n\nPress any key to continue...");
    getch();

    return 0;
}


Output



Friday, 29 August 2014

C Program for Binary Searching

This program performs searching in a sorted array using Binary Search algorithm. It takes the Number of values (max) in the list, the actual values in the list, and the value to be searched for as inputs. The program then searches for the value in the list using Binary Search method and  prints the location of the value, if it is found. Otherwise it displays an error message.

Pre-condition
The array used as input for the program should be sorted in ascending order. So the user has to enter the values in sorted order. This program does not sort the array. You can find program for sorting this site itself in the following sections.

C Program for Quick Sorting
C Program for Insertion Sorting
C Program for Bubble Sorting

Source code for Binary Search


/*
    Binary Search
    -------------
    Input:
        1. No. of values in the List
        2. Actual values in the list (in ascending order)
        3. The value to be searched for
    Output:
        1. If the "search value" is there in the list, location of the value
        2. If the value is there in the list, an error message.
*/


#include <stdio.h>
#include <conio.h>

int main() {
    int i, first, last, middle, max, findme, list[100];

    clrscr();

    printf("Enter number of elements:");
    scanf("%d",&max);

    printf("Enter %d values:\n", max);

    for ( i = 0 ; i < max ; i++ )
        scanf("%d",&list[i]);

    printf("Enter value to be searched for:");
    scanf("%d",&findme);

    first = 0;
    last = max - 1;
    middle = (first+last)/2;

    while( first <= last )
    {
        if ( list[middle] < findme )
            first = middle + 1;
        else if ( list[middle] == findme )
        {
            printf("%d found at location %d.\n", findme, middle + 1);
            break;
        }
        else
            last = middle - 1;

        middle = (first + last)/2;
    }

    if ( first > last )
        printf("Not found! %d is not present in the list.\n", findme);

    getch();

    return 0;
}


Output



C Program for Quick Sorting

 C Source code for implementing Quick Sort using recursive function . This program accepts No. of values to be sorted and the actual values to be sorted from user. By using Quick Sort algorithm it sorts the values and prints the output.

Source Code

/*
    Quick Sorting
    --------------
    Input :
        1. No. of values to be sorted i.e. n.
        2. Values to be sorted. i.e. n values.
    Output:
        List of sorted values.
*/


#include<stdio.h>
#include<conio.h>

void quicksort(int [100], int, int);

int main() {
    int array[100], size, i;

    clrscr();
    printf("Enter size of the array: ");
    scanf("%d", &size);

    printf("Enter %d elements:\n", size);
    for(i=0;i<size;i++)
        scanf("%d", &array[i]);

    // Call the function by passing array, starting index and ending index
    quicksort(array, 0, size-1);

    printf("\n\nArray after sorting:\n");
    for(i=0;i<size;i++)
        printf("%d ", array[i]);

    getch();
    return 0;
}

/*  Function for Quick Sorting */

void quicksort(int array[100], int start_index, int end_index) {
    int pivot,j,temp,i;

    if(start_index<end_index){
        pivot=start_index;
        i=start_index;
        j=end_index;

        while(i < j){
            while(array[i] <= array[pivot] && i < end_index)
                i++;
            while(array[j] > array[pivot])
                j--;

            if(i < j){
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }

        temp = array[pivot];
        array[pivot] = array[j];
        array[j] = temp;
        quicksort(array,start_index,j - 1);
        quicksort(array,j + 1,end_index);

    }
}



Output
 

C Program for Insertion Sorting

 C Source code for implementing Insertion Sort. This program accepts No. of values to be sorted and the actual values to be sorted from user. By using Insertion Sort algorithm it sorts the values and prints the output.

Source Code
 
/*
    Insertion sorting
    --------------
    Input :
        1. No. of values to be sorted i.e. n.
        2. Values to be sorted. i.e. n values.
    Output:
        List of sorted values.
*/

# include <stdio.h>
# include <conio.h>


#include <stdio.h>

int main() {
    int n, list[100], i, j, temp;

    clrscr();
    printf("Enter number of elements (maximum: 100):");
    scanf("%d", &n);

    printf("Enter %d values for sorting:\n", n);

    for (i = 0; i < n; i++) {
        scanf("%d", &list[i]);
    }

    for (i = 1 ; i <= n - 1; i++) {
        j = i;

        while ( j > 0 && list[j] < list[j-1]) {
            temp = list[j];
            list[j] = list[j-1];
            list[j-1] = temp;

            j--;
        }
    }



    printf("\n\nSorted list:\n");

    for (i = 0; i <= n - 1; i++) {
        printf("%d\n", list[i]);
    }

    printf("\nPress any key to continue...");
    getch();
    return 0;
}


Output


C Program for Bubble Sorting

 C Source code for implementing Bubble Sorting. This program accepts No. of values to be sorted and the actual values to be sorted from user. By using bubble sort algorithm it sorts the values and prints the output.


Source code

/*
    Bubble sorting
    --------------
    Input :
        1. No. of values to be sorted i.e. n.
        2. Values to be sorted. i.e. n values.
    Output:
        List of sorted values.
*/

# include <stdio.h>
# include <conio.h>

int main() {
    int list[100], n, i, j, temp;

    clrscr();
    printf("Enter number of values to be sorted (Maximum: 100):");
    scanf("%d", &n);

    printf("Enter %d values:\n", n);

    for (i = 0; i < n; i++)
        scanf("%d", &list[i]);


    for (i = 0 ; i < ( n - 1 ); i++) {
        for (j = 0 ; j < n - i - 1; j++) {
            if (list[j] > list[j+1]) {
                temp = list[j];
                list[j] = list[j+1];
                list[j+1] = temp;
            }
        }

    }


    printf("Sorted list:\n");
    for ( i = 0 ; i < n ; i++ )
        printf("%d\n", list[i]);

    getch();

    return 0;
}


Output





Wednesday, 27 August 2014

C Program to reverse a number



C Program to reverse a number 

This is a C program to reverse a number. In this example, it takes the a number as input to the program, reverses the number and stores in another variable and prints the result.

See the source code of the program
/*
            Program to reverse a number
            input  : a number
            output : reverse of the number
*/

#include <stdio.h>
#include <conio.h>

int main() {
int n, reverse = 0;

                printf("Enter a number to reverse:");
                scanf("%d",&n);

                while (n != 0) {
                                reverse = reverse * 10;
                                reverse = reverse + n%10;
                                n = n/10;
                }

                printf("Reverse of entered number is = %d\n", reverse);
                getch();

                return 0;
}


Output


Tuesday, 26 August 2014

C Program to display triangle using *



C Program to display triangle using *

This is a C program to display a pyramid (triangle) of stars. In this example, it takes the number of rows required in the triangle and then prints the triangle using * character.

See the source code of the program

/*
            Program to display triangle using *
            input  : number of rows
*/

#include <stdio.h>
int main() {
clrscr();
 int i,j,rows;
 printf("Enter number of rows: ");
 scanf("%d",&rows);

                for(i=1;i<=rows;i++)  {
                                for(j=1;j<=i;j++)    {
                                                printf("* ");
                                }
                                printf("\n");
                }
   
                printf("\nPress any key to continue...");
                getch();
   
                return 0;
}


Output



C Program to find out factorial of a number



C Program to find out factorial of a number

This is a C program to find out the factorial of a given number. In this example, it takes the number as input to the program, calculates the factorial of the number and prints the result.
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example:

            5! = 1 x 2 x  3 x 4 x 5 = 120

See the source code of the program

/*
            Program to find out factorial of a number
            input   : a number
            output  : factorial
*/

# include <stdio.h>

void main () {
            long int n,factorial, i;

            clrscr();

            printf ("Input\n-----\n\n");
            printf ("Enter a number:");
            scanf ("%ld", &n);

            factorial = 1;

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

                        factorial  = factorial  * i;

            printf ("\n\nOutput\n------\n\n");
            printf("Factorial of %ld is %ld", n, factorial);

            printf("\n\nPress any key to continue...");
            getch();
}

Output