Wednesday, 3 September 2014

C Program to check a number is prime or composite

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime because 1 and 5 are its only positive integer factors, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6.

Examples of prime numbers are:  2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,.....

Let us see a function to check whether a number is prime or not.

// Function to check prime returns 0 or 1
int isprime(int value) {
    int i;
    for (i=2;i<=value/2;i++)
        if (value%i==0)
            return (0);
    return 1;
}

Here value is the number to be checked given as parameter to the function. This function returns 1 if the value prime and returns 0 if it is not.

C Program to check whether an array is sorted or not

To sort an array there are different methods. And you may be familiar with them. However, what to do if you want to simply check whether an array is sorted or not.

Method 1
Start from the beginning of the array and compare whether the 0th element is less than 1st element and so on up to the end of the array (for Ascending order). If you can move up to the end of the array without any failure in the condition, then you can assure that the array is sorted.

Method 2
You can apply the reverse logic of method 1. Initially check whether the 0th element is greater than 1st element. If this condition is true, then you can say it is not sorted without checking further.

Let us see a function using the second method to check whether an array is sorted or not.

int issorted(int array[], int len){
    int i;
    for(i=0;i<len-1;i++)
        if (a[i]>a[i+1])
            return (0); //Unsorted

    return (1); //Sorted

}

Here array[] is the actual array and len is the length of the array. This function returns 1 if the array is sorted and returns 0 if it is not sorted.

C Program to Insert an element in an array

How to insert an element in a given position in an array. It is very simple, if you want insert an element at nth position, you want to move or shift the elements right to the nth location by one place and make the nth location free. Then you can just assign the new value to the nth location.

Let us see a function implemented in C Language for inserting an element in an array.

void insert(int array[],int value,int position,int len)
{
    int i;
    for (i=len + 1 ; i>=position;i--)
        a[i]=a[i-1];
    a[position-1]=value;
    return;
}

Here array[] is the actual array where insertion is to be made. value is the new value that has to be inserted and position is the location where the value is to be inserted. len is the existing length of the array.

C Program to check Amicable Numbers

Amicable numbers are two different numbers so related that the sum of the proper divisors of first number is equal to the other number and vice-versa. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.).

For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.

The first few amicable pairs are: (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368).

Following is a C language program to check the given two numbers are amicable or not.


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

int  main() {
    int i, sf1=0, sf2=0,  m, n;

    clrscr();
    printf("Enter the first number :");
    scanf("%d", &m);
    printf("Enter the second number :");
    scanf("%d",&n);

    if (m==n) {
       printf("Given numbers are not amicable");
       getch();
       return 0;
    }

   / * Finds sum of proper divisors of the first number (m) */
    for (i=1;i<=m/2;i++){
        if (m%i==0)
            sf1=sf1+i;
        }

 / * Finds sum of proper divisors of the second number (n) only if sum of proper divisors of first number is equal to the second number */

    if (sf1==n)
        for (i=1; i<=n/2;i++){
            if (n%i==0)
                sf2=sf2+i;
        }

     if (sf2==m)
        printf ("Given numbers are amicable");
     else
        printf("Given numbers are not amicable");

     
     getch();
     return 0;
}

Monday, 1 September 2014

Sample code for implementing "check availability option in registration form" using Ajax, PHP and MySQL



This example shows how you can include a ‘check availability’ option in a registration form using Ajax, PHP and MySQL. Using HTML input element, user enters the email id and submits to the server side PHP script ‘isavailable.php’ using Ajax. ‘isavailable.php’ script checks whether the email id is already available in the database table or not and returns the status as responseText.


checkavailability.php

This PHP file contains the form and the Ajax script to submit the email id to the server side PHP script (isavailable.php) and display the response on the page.


<!DOCTYPE html>
<html>
    <head>
        <title>Check Availability - Ajax, PHP and MySQL </title>
        <script>
        function checkavailability(){

        var xmlhttp;

        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

            xmlhttp=new XMLHttpRequest();

        }

        else {// code for IE6, IE5

            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

        }



        xmlhttp.onreadystatechange=function() {

            if (xmlhttp.readyState==4 && xmlhttp.status==200) {

                document.getElementById("divInfo").innerHTML=xmlhttp.responseText;

            }

        }



        url = "isavailable.php";

        param = document.getElementById('txtemail').value;                       

        url = url + "?txtemail=" + param;

       

               

        xmlhttp.open("GET",url,true);

        xmlhttp.send();

    }
</script>

</head>
   
<body>


<form>
    <table align="center">
        <tr>
            <td colspan="2"><h2>Check Availability</h2></td>
        </tr>
        <tr>
        <td>Email</td>
        <td><input type="text" size="40" id="txtemail" name="txtemail"></td>
        </tr>
       
        <tr>
        <td></td>
        <td><input type="button" id="cmdcheck" name="cmdcheck" value="Check Availability" onclick="checkavailability()"></td>
        </tr>
       
        <tr>
            <td colspan="2"><div id="divInfo"></div></td>       
        </tr>
       
    </table>
</form>


</body>
</html>




isavailable.php

 This PHP file extracts the email id submitted to the server from $_REQUEST array and check whether this id is available in the table by using PHP mysql functions. The availability status is sends back to the requested page.


<?php
    $email = $_REQUEST['txtemail'];

    $dblink=mysql_connect("localhost","root","");
    mysql_select_db("dbcheckavailability", $dblink);

    $sql="SELECT * FROM tblmember WHERE email='" . $email . "';";

    $result=mysql_query($sql, $dblink);

    $responseText ="";
   
   
    if (mysql_num_rows($result)) {
        $responseText = "Sorry, <b>" . $email . "</b> is already in use!";
    }
    else {
        $responseText = "Congratulation, <b>" .  $email . "</b> is available!";
    }
  
    echo $responseText;
    mysql_close($dblink);  
?>



Table Structure

Thsis is the structure of the table that has to be created in MySQL for this example.

--
-- Database: `dbcheckavailability`
--

-- --------------------------------------------------------

--
-- Table structure for table `tblmember`
--

CREATE TABLE IF NOT EXISTS `tblmember` (
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `email` varchar(40) NOT NULL,
  UNIQUE KEY `email` (`email`)
);


INSERT INTO `tblmember` (`firstname`, `lastname`, `email`) VALUES
('anand', 'kumar', 'csnotes32@gmail.com');



Output