Sunday, 11 June 2017

Write a C program for Binary Search ?

C Program for Binary Search

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

 main()
{
   int c, first, last, middle, n, search, array[100];
   printf("Enter number of elements\n");
   scanf("%d",&n);
   printf("Enter %d integers\n", n);
   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);
   printf("Enter value to find\n");
   scanf("%d",&search);
   first = 0;
   last = n - 1;
   middle = (first+last)/2;
   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;   
      else if ( array[middle] == search )
      {
         printf("%d found at location %d.\n", search, 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", search);
   return 0;  
}

Write a C Program for Bubble Sort ?


/* Bubble sort code */

#include<stdio.h>

main()
{
   int array[100], n, c, d, swap;

   printf("Enter number of elements\n");
   scanf("%d", &n);

   printf("Enter %d integers\n", n);

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

   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      for ( d = 0 ; d < n - c - 1 ; d++ )
      {
          if ( array[d] > array[d+1] ) /* For decreasing order use < */
          {
             swap = array[d];
             array[d] = array[d+1];
             array[d+1] = swap;
          }
      }
   }

   printf("Sorted list in ascending order:\n");

   for ( c = 0 ; c < n ; c++ )
       printf("%d\n", array[c]);

   return 0;
}

Write a C Program for Finding a Leap Year.

C Program for Finding Leap Year.


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

main()
{
   int year;

   printf("Enter a year to check if it is a leap year\n");
   scanf("%d", &year);

   if ( year%400 == 0)
      printf("%d is a leap year.\n", year);
   else if ( year%100 == 0)
      printf("%d is not a leap year.\n", year);
   else if ( year%4 == 0 )
      printf("%d is a leap year.\n", year);
   else
      printf("%d is not a leap year.\n", year);

   return 0;
}

Write a Program for compare Strings by using If in C ?

Compare Strings by using If

#include<stdio.h>
#include<string.h>

main()
{
   char a[100], b[100];

   printf("Enter the first string\n");
   gets(a);

   printf("Enter the second string\n");
   gets(b);

   if( strcmp(a,b) == 0 )
      printf("Entered strings are equal.\n");
   else
      printf("Entered strings are not equal.\n");

   return 0;
}

Write a C program to find ncr and npr value ?

C Program for finding the value for Combinations & Permutations.

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

long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);

main()
{
   int n, r;
   long ncr, npr;

   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);

   ncr = find_ncr(n, r);
   npr = find_npr(n, r);

   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);

   return 0;
}

long find_ncr(int n, int r)
{
   long result;

   result = factorial(n)/(factorial(r)*factorial(n-r));

   return result;
}

long find_npr(int n, int r)
{
   long result;

   result = factorial(n)/factorial(n-r);

   return result;
}

long factorial(int n)
{
   int c;
   long result = 1;

   for( c = 1 ; c <= n ; c++ )
      result = result*c;

   return ( result );
}

Write a Program for compare Strings by using pointers in C ?

Compare Two Strings.

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

int compare_string(char*, char*);

main()
{
    char first[100], second[100], result;

    printf("Enter first string\n");
    gets(first);

    printf("Enter second string\n");
    gets(second);

    result = compare_string(first, second);

    if ( result == 0 )
       printf("Both strings are same.\n");
    else
       printf("Entered strings are not equal.\n");

    return 0;
}

int compare_string(char *first, char *second)
{
   while(*first==*second)
   {
      if ( *first == '\0' || *second == '\0' )
         break;

      first++;
      second++;
   }
   if( *first == '\0' && *second == '\0' )
      return 0;
   else
      return -1;
}

How to Print Star in C ?



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

main()
{
    int n, c, k, space;

    printf("Enter number of rows\n");
    scanf("%d",&n);

    space = n;

    for ( k = 1 ; k <= n ; k++ )
    {
        for ( c = 1 ; c < space ; c++ )
            printf(" ");

        space--;

        for( c = 1 ; c <= k ; c++ )
            printf("*");

        printf("\n");
    }

    return 0;
}

How to Check Palindrome String in C ?

What is Palindrome?
 
It's a word, phrase, or sequence that reads the same backwards as forwards, e.g. malayalam , madam or nurses run.

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

int is_palindrome(char*);
void copy_string(char*, char*);
void reverse_string(char*);
int string_length(char*);
int compare_string(char*, char*);

main()
{
   char string[100];
   int result;

   printf("Enter a string\n");
   gets(string);

   result = is_palindrome(string);

   if ( result == 1 )
      printf("\"%s\" is a palindrome string.\n", string);
   else
      printf("\"%s\" is not a palindrome string.\n", string);

   return 0;
}

int is_palindrome(char *string)
{
   int check, length;
   char *reverse;

   length = string_length(string);   
   reverse = (char*)malloc(length+1);   

   copy_string(reverse, string);
   reverse_string(reverse);

   check = compare_string(string, reverse);

   free(reverse);

   if ( check == 0 )
      return 1;
   else
      return 0;
}

int string_length(char *string)
{
   int length = 0; 

   while(*string)
   {
      length++;
      string++;
   }

   return length;
}

void copy_string(char *target, char *source)
{
   while(*source)
   {
      *target = *source;
      source++;
      target++;
   }
   *target = '\0';
}

void reverse_string(char *string)
{
   int length, c;
   char *begin, *end, temp;

   length = string_length(string);

   begin = string;
   end = string;

   for ( c = 0 ; c < ( length - 1 ) ; c++ )
       end++;

   for ( c = 0 ; c < length/2 ; c++ )
   {       
      temp = *end;
      *end = *begin;
      *begin = temp;

      begin++;
      end--;
   }
}

int compare_string(char *first, char *second)
{
   while(*first==*second)
   {
      if ( *first == '\0' || *second == '\0' )
         break;

      first++;
      second++;
   }
   if( *first == '\0' && *second == '\0' )
      return 0;
   else
      return -1;
}

Friday, 9 June 2017

How to add 3 numbers through ajax.

First of all Make an indexpage.php.





<html>

<head>

<title>How to add three value through Ajax</title>

<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">

</head>



<body>

   

    <h2 style="text-align:center;">How to add three value through Ajax</h2>

   

<form action="javascript:add(document.getElementById('frm'));" name="frm" id="frm">

    <div class="col-md-12">

        <div class="col-md-4"></div>

          <div class="col-md-4">

              <table style="border:10px;">

<tr>

<td>Enter Value One</td>

<td><input id="num1" type="text"/></td>

</tr>

<tr>

<td>Enter Value Two</td>

<td><input id="num2" type="text"/></td>

</tr>

<tr>

<td>Enter Value Three</td>

<td><input id="num3" type="text"/></td>

</tr>





<tr>

<td colspan="10">

<input type="submit" name="button" value="Answer">

</td>

</tr>

</table>

</form>

   

<div name="txt" id="txt"></div>

    </div>

<div class="col-md-4"></div>

    </div>

<script type="text/javascript" language="javascript">

function add(obj)

{



var XMLHttpRequestObject=false;

if(window.XMLHttpRequest)

{

XMLHttpRequestObject=new XMLHttpRequest();

}

else if(window.ActiveXObject)

{

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

}



var str1= "num1=" + document.getElementById("num1").value;

var str2="&num2=" +document.getElementById("num2").value;

var str3="&num3=" +document.getElementById("num3").value;



XMLHttpRequestObject.onreadystatechange = show;

XMLHttpRequestObject.open('POST', '<?php echo base_url();?>jobsite/tes5', true);

XMLHttpRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


XMLHttpRequestObject.send(str1+str2+str3);


function show()

{

if (XMLHttpRequestObject.readyState == 4)

{

if (XMLHttpRequestObject.status == 200)

{

result = XMLHttpRequestObject.responseText;

document.getElementById('txt').innerHTML = result;

}

}

}

}

</script>

</body>

</html>






Now Make another page named it sum.php.


<?php
$num1=$_POST['num1'];
$num2=$_POST['num2'];
$num3=$_POST['num3'];
$num4=$num1+$num2+$num3;
echo $num4;
?>





Friday, 19 May 2017

Write a C Program for Depth First Binary Tree Search Recursion in Linux.

 C Program for Depth First Binary Tree Search Recursion in Linux.

Source Code:

#include <stdio.h>

#include <stdlib.h>



struct node

{

    int a;

    struct node *left;

    struct node *right;

};



void generate(struct node **, int);

void DFS(struct node *);

void delete(struct node **);



int main()

{

    struct node *head = NULL;

    int choice = 0, num, flag = 0, key;



    do

    {

        printf("\nEnter your choice:\n1. Insert\n2. Perform DFS Traversal\n3. Exit\nChoice: ");

        scanf("%d", &choice);

        switch(choice)

        {

        case 1: 

            printf("Enter element to insert: ");

            scanf("%d", &num);

            generate(&head, num);

            break;

        case 2: 

            DFS(head);

            break;

        case 3: 

            delete(&head);

            printf("Memory Cleared\nPROGRAM TERMINATED\n");

            break;

        default: 

            printf("Not a valid input, try again\n");

        }

    } while (choice != 3);

    return 0;

}



void generate(struct node **head, int num)

{

    struct node *temp = *head, *prev = *head;



    if (*head == NULL)

    {

        *head = (struct node *)malloc(sizeof(struct node));

        (*head)->a = num;

        (*head)->left = (*head)->right = NULL;

    }

    else

    {

        while (temp != NULL)

        {

            if (num > temp->a)

            {

                prev = temp;

                temp = temp->right;

            }

            else

            {

                prev = temp;

                temp = temp->left;

            }

        }

        temp = (struct node *)malloc(sizeof(struct node));

        temp->a = num;

        if (num >= prev->a)

        {

            prev->right = temp;

        }

        else

        {

            prev->left = temp;

        }

    }

}



void DFS(struct node *head)

{

    if (head)

    {

        if (head->left)

        {

            DFS(head->left);

        }

        if (head->right)

        {

            DFS(head->right);

        }

        printf("%d  ", head->a);

    }

}



void delete(struct node **head)

{

    if (*head != NULL)

    {

        if ((*head)->left)

        {

            delete(&(*head)->left);

        }

        if ((*head)->right)

        {

            delete(&(*head)->right);

        }

        free(*head);

    }

}



OUTPUT 

$ cc pgm34.c
$ a.out

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 5

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 3

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 4

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 2

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 7

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 8

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 1
Enter element to insert: 6

Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 2
2  4  3  6  8  7  5  
Enter your choice:
1. Insert
2. Perform DFS Traversal
3. Exit
Choice: 3
Memory Cleared
PROGRAM TERMINATED

Write a C Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements From 1 to N.

C Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements From 1 to N.

It is successfully compiled and run on a Linux system.

Source Code:

   
 #include <stdio.h>

    void print(const int *v, const int size)

    {

        int i;

        if (v != 0) {

        for ( i = 0; i < size; i++) {

            printf("%4d", v[i] );

        }

        printf("\n");

      }

    }

    void alexanderbogomolyn(int *Value, int N, int k)

    {

        static level = -1;

        int i;

        level = level+1; Value[k] = level;

        if (level == N)

            print(Value, N);

        else

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

        if (Value[i] == 0)

            alexanderbogomolyn(Value, N, i);

        level = level-1;

        Value[k] = 0;

    }

    int main()

    {

        int N = 4;

        int i;

        int Value[N];

        for (i = 0; i < N; i++) {

          Value[i] = 0;

        }

        printf("\nPermutation using Alexander Bogomolyn's algorithm: ");

        alexanderbogomolyn(Value, N, 0);

        return 0;

    }

OUTPUT


$ gcc permute.c -o permute
$ ./permute
Permutation using Alexander Bogomolyns algorithm:
   1   2   3   4
   1   2   4   3
   1   3   2   4
   1   4   2   3
   1   3   4   2
   1   4   3   2
   2   1   3   4
   2   1   4   3
   3   1   2   4
   4   1   2   3
   3   1   4   2
   4   1   3   2
   2   3   1   4
   2   4   1   3
   3   2   1   4
   4   2   1   3
   3   4   1   2
   4   3   1   2
   2   3   4   1
   2   4   3   1
   3   2   4   1
   4   2   3   1
   3   4   2   1
   4   3   2   1




 

 

Write a C Program to Generate All Possible Combinations of a Given List of Numbers in Linux.

C Program to Generate All Possible Combinations of a Given List of Numbers.

It's successfully compiled and run on a Linux system. 

Source Code:

    #include<stdio.h>

   
 #include<string.h>

    #define N 10


    void print(int *num, int n)

    {

        int i;

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

            printf("%d ", num[i]);

        printf("\n");

    }

    int main()

    {

        int num[N];

        int *ptr;

        int temp;

        int i, n, j;

        printf("\nHow many number you want to enter: ");

            scanf("%d", &n);

        printf("\nEnter a list of numbers to see all combinations:\n");

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

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

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

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

                temp = num[i];

                num[i] = num[i+1];

                num[i+1] = temp;

                print(num, n);

        }

        }

        return 0;

    }


OUTPUT

$ gcc combination.c -o combination
$ ./combination
How many number you want to enter: 4
Enter a list of numbers to see all combinations: 1 2 3 4
2 1 3 4 
2 3 1 4 
2 3 4 1 
3 2 4 1 
3 4 2 1 
3 4 1 2 
4 3 1 2 
4 1 3 2 
4 1 2 3 
1 4 2 3 
1 2 4 3 
1 2 3 4
 
 
 

Write a C Program to Permute All Letters of an Input String in Linux System.

A C Program to Permute All Letters of an Input String in Linux System. 


This algorithm finds all permutations of the letters of a given string. It is a recursive algorithm using concept of backtracking.

The source code for the C program to permute all letters of an input string. This program is successfully compiled and run on a Linux system.


    #include <stdio.h>

    #include <string.h>

    void swap (char *x, char *y)

    {

        char temp;

        temp = *x;

        *x = *y;

        *y = temp;

    }

    void permute(char *a, int i, int n) 

    {

       int j; 

       if (i == n)

         printf("%s\n", a);

       else

       {

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

           {

              swap((a + i), (a + j));

              permute(a, i + 1, n);

              swap((a + i), (a + j)); //backtrack

           }

       }

    } 

int main()

    {

       char str[21];

       int len;

       printf("\nEnter a string: ");

       scanf("%s", str);

       len = strlen(str);

       permute(str, 0, len - 1);

       return 0;

    }


OUTPUT

$ gcc permute.c -o permute
$ ./permute

Enter a string: SAN

All possible permutations are:
    SAN
    SNA
    ASN
    ANS
    NAS
    NSA



Write a C++ Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected.

A C++ Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected.

A C++ Program to find minimum number of edges to cut to make the graph disconnected. An edge in an un-directed connected graph is a bridge if removing it disconnects the graph. For a disconnected un-directed graph, definition is similar, a bridge is an edge removing which increases number of connected components.

A Source Code for the C++ Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected. It's also successfully compiled and run on a Linux system.


#include<iostream>

#include <list>

#define NIL -1

using namespace std;



// A class that represents an undirected graph

class Graph

{

        int V; // No. of vertices

        list<int> *adj; // A dynamic array of adjacency lists

        void bridgeUtil(int v, bool visited[], int disc[], int low[],

                int parent[]);

    public:

        Graph(int V); // Constructor

        void addEdge(int v, int w); // function to add an edge to graph

        void bridge(); // prints all bridges

};



Graph::Graph(int V)

{

    this->V = V;

    adj = new list<int> [V];

}



void Graph::addEdge(int v, int w)

{

    adj[v].push_back(w);

    adj[w].push_back(v); // Note: the graph is undirected

}



void Graph::bridgeUtil(int u, bool visited[], int disc[], int low[],

        int parent[])

{

    // A static variable is used for simplicity, we can avoid use of static

    // variable by passing a pointer.

    static int time = 0;



    // Mark the current node as visited

    visited[u] = true;



    // Initialize discovery time and low value

    disc[u] = low[u] = ++time;



    // Go through all vertices aadjacent to this

    list<int>::iterator i;

    for (i = adj[u].begin(); i != adj[u].end(); ++i)

    {

        int v = *i; // v is current adjacent of u



        // If v is not visited yet, then recur for it

        if (!visited[v])

        {

            parent[v] = u;

            bridgeUtil(v, visited, disc, low, parent);



            // Check if the subtree rooted with v has a connection to

            // one of the ancestors of u

            low[u] = min(low[u], low[v]);



            // If the lowest vertex reachable from subtree under v is

            // below u in DFS tree, then u-v is a bridge

            if (low[v] > disc[u])

                cout << u << " " << v << endl;

        }



        // Update low value of u for parent function calls.

        else if (v != parent[u])

            low[u] = min(low[u], disc[v]);

    }

}



// DFS based function to find all bridges. It uses recursive function bridgeUtil()

void Graph::bridge()

{

    // Mark all the vertices as not visited

    bool *visited = new bool[V];

    int *disc = new int[V];

    int *low = new int[V];

    int *parent = new int[V];



    // Initialize parent and visited arrays

    for (int i = 0; i < V; i++)

    {

        parent[i] = NIL;

        visited[i] = false;

    }



    // Call the recursive helper function to find Bridges

    // in DFS tree rooted with vertex 'i'

    for (int i = 0; i < V; i++)

        if (visited[i] == false)

            bridgeUtil(i, visited, disc, low, parent);

}



// Driver program to test above function

int main()

{

    // Create graphs given in above diagrams

    cout << "\nBridges in first graph \n";

    Graph g1(5);

    g1.addEdge(1, 0);

    g1.addEdge(0, 2);

    g1.addEdge(2, 1);

    g1.addEdge(0, 3);

    g1.addEdge(3, 4);

    g1.bridge();



    cout << "\nBridges in second graph \n";

    Graph g2(4);

    g2.addEdge(0, 1);

    g2.addEdge(1, 2);

    g2.addEdge(2, 3);

    g2.bridge();



    cout << "\nBridges in third graph \n";

    Graph g3(7);

    g3.addEdge(0, 1);

    g3.addEdge(1, 2);

    g3.addEdge(2, 0);

    g3.addEdge(1, 3);

    g3.addEdge(1, 4);

    g3.addEdge(1, 6);

    g3.addEdge(3, 5);

    g3.addEdge(4, 5);

    g3.bridge();

    return 0;

} 



OUTPUT 

$ g++ Bridges.cpp

$ a.out
Bridges in first graph

3 4



Write a Program to Find the Maximum Size Clique in a Graph in C++.

A C++ Program to Find the Maximum Size Clique in a Graph.

 
 It's a C++ Program to find the cliques of size k in  a graph. An un-directed graph which is formed by a finite set of vertices and a set of un-ordered pairs of vertices, which are called edges. In algorithm analysis, the number of vertices in the graph is denoted by n and the number of edges is denoted by m. A clique in a graph G is a complete sub-graph of G; that is, it is a subset S of the vertices such that every two vertices in S are connected by an edge in G. A maximal clique is a clique to which no more vertices can be added; a maximum clique is a clique that includes the largest possible number of vertices, and the clique number ?(G) is the number of vertices in a maximum clique of G.


Here is the source code for the C++ Program to Find the Maximum Size Clique in a Graph which is
successfully compiled and run on a Linux system.

    #include <iostream>

    #include <fstream>

    #include <string>

    #include <vector>

    using namespace std;

     

    bool removable(vector<int> neighbor, vector<int> cover);

    int max_removable(vector<vector<int> > neighbors, vector<int> cover);

    vector<int> procedure_1(vector<vector<int> > neighbors, vector<int> cover);

    vector<int> procedure_2(vector<vector<int> > neighbors, vector<int> cover,

            int k);

    int cover_size(vector<int> cover);

    ifstream infile("graph.txt");

    ofstream outfile("cliques.txt");

     

    int main()

    {

        
        cout << "Clique Algorithm." << endl;

        int n, i, j, k, K, p, q, r, s, min, edge, counter = 0;

        infile >> n;

        vector<vector<int> > graph;

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

        {

            vector<int> row;

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

            {

                infile >> edge;

                if (edge == 0)

                    row.push_back(1);

                else

                    row.push_back(0);

            }

            graph.push_back(row);

        }

        // To Find Neighbors

        vector<vector<int> > neighbors;

        for (i = 0; i < graph.size(); i++)

        {

            vector<int> neighbor;

            for (j = 0; j < graph[i].size(); j++)

                if (graph[i][j] == 1)

                    neighbor.push_back(j);

            neighbors.push_back(neighbor);

        }

        cout << "Graph has n = " << n << " vertices." << endl;

        // To Read maximum size of Clique wanted

        cout << "Find a Clique of size at least k = ";

        cin >> K;

        k = n - K;

        //Find Cliques

        bool found = false;

        cout << "Finding Cliques..." << endl;

        min = n + 1;

        vector<vector<int> > covers;

        vector<int> allcover;

        for (i = 0; i < graph.size(); i++)

            allcover.push_back(1);

        for (i = 0; i < allcover.size(); i++)

        {

            if (found)

                break;

            counter++;

            cout << counter << ". ";

            outfile << counter << ". ";

            vector<int> cover = allcover;

            cover[i] = 0;

            cover = procedure_1(neighbors, cover);

            s = cover_size(cover);

            if (s < min)

                min = s;

            if (s <= k)

            {

                outfile << "Clique (" << n - s << "): ";

                for (j = 0; j < cover.size(); j++)

                    if (cover[j] == 0)

                        outfile << j + 1 << " ";

                outfile << endl;

                cout << "Clique Size: " << n - s << endl;

                covers.push_back(cover);

                found = true;

                break;

            }

            for (j = 0; j < n - k; j++)

                cover = procedure_2(neighbors, cover, j);

            s = cover_size(cover);

            if (s < min)

                min = s;

            outfile << "Clique (" << n - s << "): ";

            for (j = 0; j < cover.size(); j++)

                if (cover[j] == 0)

                    outfile << j + 1 << " ";

            outfile << endl;

            cout << "Clique Size: " << n - s << endl;

            covers.push_back(cover);

            if (s <= k)

            {

                found = true;

                break;

            }

        }

        //Pairwise Intersections

        for (p = 0; p < covers.size(); p++)

        {

            if (found)

                break;

            for (q = p + 1; q < covers.size(); q++)

            {

                if (found)

                    break;

                counter++;

                cout << counter << ". ";

                outfile << counter << ". ";

                vector<int> cover = allcover;

                for (r = 0; r < cover.size(); r++)

                    if (covers[p][r] == 0 && covers[q][r] == 0)

                        cover[r] = 0;

                cover = procedure_1(neighbors, cover);

                s = cover_size(cover);

                if (s < min)

                    min = s;

                if (s <= k)

                {

                    outfile << "Clique (" << n - s << "): ";

                    for (j = 0; j < cover.size(); j++)

                        if (cover[j] == 0)

                            outfile << j + 1 << " ";

                    outfile << endl;

                    cout << "Clique Size: " << n - s << endl;

                    found = true;

                    break;

                }

                for (j = 0; j < k; j++)

                    cover = procedure_2(neighbors, cover, j);

                s = cover_size(cover);

                if (s < min)

                    min = s;

                outfile << "Clique (" << n - s << "): ";

                for (j = 0; j < cover.size(); j++)

                    if (cover[j] == 0)

                        outfile << j + 1 << " ";

                outfile << endl;

                cout << "Clique Size: " << n - s << endl;

                if (s <= k)

                {

                    found = true;

                    break;

                }

            }

        }

        if (found)

            cout << "Found Clique of size at least " << K << "." << endl;

        else

            cout << "Could not find Clique of size at least " << K << "." << endl

                    << "Maximum Clique size found is " << n - min << "." << endl;

        cout << "See cliques.txt for results." << endl;

        return 0;

    }

     

    bool removable(vector<int> neighbor, vector<int> cover)

    {

        bool check = true;

        for (int i = 0; i < neighbor.size(); i++)

            if (cover[neighbor[i]] == 0)

            {

                check = false;

                break;

            }

        return check;

    }

     

    int max_removable(vector<vector<int> > neighbors, vector<int> cover)

    {

        int r = -1, max = -1;

        for (int i = 0; i < cover.size(); i++)

        {

            if (cover[i] == 1 && removable(neighbors[i], cover) == true)

            {

                vector<int> temp_cover = cover;

                temp_cover[i] = 0;

                int sum = 0;

                for (int j = 0; j < temp_cover.size(); j++)

                    if (temp_cover[j] == 1 && removable(neighbors[j], temp_cover)

                            == true)

                        sum++;

                if (sum > max)

                {

                    max = sum;

                    r = i;

                }

            }

        }

        return r;

    }

     

    vector<int> procedure_1(vector<vector<int> > neighbors, vector<int> cover)

    {

        vector<int> temp_cover = cover;

        int r = 0;

        while (r != -1)

        {

            r = max_removable(neighbors, temp_cover);

            if (r != -1)

                temp_cover[r] = 0;

        }

        return temp_cover;

    }

     

    vector<int> procedure_2(vector<vector<int> > neighbors, vector<int> cover,

            int k)

    {

        int count = 0;

        vector<int> temp_cover = cover;

        int i = 0;

        for (int i = 0; i < temp_cover.size(); i++)

        {

            if (temp_cover[i] == 1)

            {

                int sum = 0, index;

                for (int j = 0; j < neighbors[i].size(); j++)

                    if (temp_cover[neighbors[i][j]] == 0)

                    {

                        index = j;

                        sum++;

                    }

                if (sum == 1 && cover[neighbors[i][index]] == 0)

                {

                    temp_cover[neighbors[i][index]] = 1;

                    temp_cover[i] = 0;

                    temp_cover = procedure_1(neighbors, temp_cover);

                    count++;

                }

                if (count > k)

                    break;

            }

        }

        return temp_cover;

    }

     

    int cover_size(vector<int> cover)

    {

        int count = 0;

        for (int i = 0; i < cover.size(); i++)

            if (cover[i] == 1)

                count++;

        return count;

    }





OUTPUT

 

 
$ g++ MaxClique.cpp
$ a.out
 
graph.txt:
4
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
 
cliques.txt:
Clique ( 4 ): 1 2 3 4
------------------
(program exited with code: 0)
Press return to continue

 

 





Thursday, 18 May 2017

How to Know IP Location with their city code,Region Code, Country Code,Latitude & Longitude also.

A Simple function for finding the IP location  with their city code,Region Code, Country Code, Latitude & Longitude.



<html>

<head>

  <title>Display IP Location with Full Information </title>

  <link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">

</head>

  

<body>

    

 <div class="fluid-container">

   <div class="row">

      <div class="col-md-12">&nbsp;</div>

         <div class="col-md-12">

          <div class="col-md-3"></div>

           <div class="col-md-6">

           <?php

           function getiplocationdetails()

          {

             $ip = '192.190.85.178';

             $result = '';

             $ip_datails = @json_decode

            (file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip)); 

             return $ip_datails;

              }





              echo "<>";

              print_r(getiplocationdetails());

              ?>

              </div>

              <div class="col-md-3"></div>

            </div>

         </div>

     </div>

  </body>

</html>




Sunday, 23 April 2017

How to Declare Variable & Constant in PL/SQL Database Management System But not in SQL

--Variable & Constant--

DECLARE  
a integer := 10;  
b integer := 20;  
c integer;  
f real;
BEGIN  
c := a + b;  
dbms_output.put_line('Value of c: ' || c);  
f := 70.0/3.0;  
dbms_output.put_line('Value of f: ' || f);
END;

DECLARE  
-- Global variables   
num1 number := 95;   
num2 number := 85;
BEGIN   
dbms_output.put_line('Outer Variable num1: ' || num1);  
dbms_output.put_line('Outer Variable num2: ' || num2);  
DECLARE      
-- Local variables     
num1 number := 195;      
num2 number := 185;   
BEGIN      
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);  
END;
END;

CREATE TABLE CUSTOMERS(  
ID   INT NOT NULL,  
NAME VARCHAR (20) NOT NULL,  
AGE INT NOT NULL,  
ADDRESS CHAR (25),  
SALARY   DECIMAL (18, 2),         
PRIMARY KEY (ID) );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ron', 32, 'America', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Khilan', 25, 'Rome', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Emma', 23, 'Manchester', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Chibabva', 25, 'Mumbasa', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Henry', 27, 'london', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Katty', 22, 'Jamaica', 4500.00 );


DECLARE  
c_id customers.id%type := 1;  
c_name  customers.name%type;  
c_addr customers.address%type;  
c_sal  customers.salary%type;
BEGIN  
SELECT name, address, salary INTO c_name, c_addr, c_sal   FROM customers   WHERE id = c_id;
   dbms_output.put_line   ('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;


DECLARE  
-- constant declaration  
pi constant number := 3.141592654;  
-- other declarations   radius number(5,2);   
dia number(5,2);   
circumference number(7, 2);  
area number (10, 2);
BEGIN   
-- processing  
radius := 9.5;   
dia := radius * 2;   
circumference := 2.0 * pi * radius;  
area := pi * radius * radius;  
-- output  
dbms_output.put_line('Radius: ' || radius);  
dbms_output.put_line('Diameter: ' || dia);  
dbms_output.put_line('Circumference: ' || circumference);  
dbms_output.put_line('Area: ' || area);
END;

How to Create Trigger Function in PL/SQL Database Management System But not in SQL

--Trigger creation row level--
 
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
   sal_diff number;
BEGIN
   sal_diff := :NEW.salary  - :OLD.salary;
   dbms_output.put_line('Old salary: ' || :OLD.salary);
   dbms_output.put_line('New salary: ' || :NEW.salary);
   dbms_output.put_line('Salary difference: ' || sal_diff);
END;

delete from customers where id=7;
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

UPDATE customers
SET salary = salary + 500
WHERE id = 2;

How to Create String Function in PL/SQL Database Management System But not in SQL

--String Function-- 
 
DECLARE
   name varchar2(20);
   company varchar2(30);
   introduction clob;
   choice char(1);
BEGIN
   name := 'Ron Kennedy';
   company := 'Infotech';
   introduction := ' Hello! I''m Ron Kennedy from Yahoo.';
   choice := 'y';
   IF choice = 'y' THEN
      dbms_output.put_line(name);
      dbms_output.put_line(company);
      dbms_output.put_line(introduction);
   END IF;
END;

--String Functions
DECLARE
   greetings varchar2(11) := 'hello world';
BEGIN
   dbms_output.put_line(UPPER(greetings));
  
   dbms_output.put_line(LOWER(greetings));
  
   dbms_output.put_line(INITCAP(greetings));
  
   /* retrieve the first character in the string */
   dbms_output.put_line ( SUBSTR (greetings, 1, 1));
  
   /* retrieve the last character in the string */
   dbms_output.put_line ( SUBSTR (greetings, -1, 1));
  
   /* retrieve five characters,
      starting from the seventh position. */
   dbms_output.put_line ( SUBSTR (greetings, 7, 5));
  
   /* retrieve the remainder of the string,
      starting from the second position. */
   dbms_output.put_line ( SUBSTR (greetings, 2));
  
   /* find the location of the first "e" */
   dbms_output.put_line ( INSTR (greetings, 'e'));
END;

--String Functions more
DECLARE
   greetings varchar2(30) := '......Hello World.....';
BEGIN
   dbms_output.put_line(RTRIM(greetings,'.'));
   dbms_output.put_line(LTRIM(greetings, '.'));
   dbms_output.put_line(TRIM( '.' from greetings));
END;

How to Create Table based records in PL/SQL Database Management System But not in SQL

--Table based records--
 
DECLARE
   customer_rec customers%rowtype;
BEGIN
   SELECT * into customer_rec
   FROM customers
   WHERE id = 5;

   dbms_output.put_line('Customer ID: ' || customer_rec.id);
   dbms_output.put_line('Customer Name: ' || customer_rec.name);
   dbms_output.put_line('Customer Address: ' || customer_rec.address);
   dbms_output.put_line('Customer Salary: ' || customer_rec.salary);
END;

--Cursor based records
DECLARE
   CURSOR customer_cur is
      SELECT id, name, address
      FROM customers;
   customer_rec customer_cur%rowtype;
BEGIN
   OPEN customer_cur;
   LOOP
      FETCH customer_cur into customer_rec;
      EXIT WHEN customer_cur%notfound;
      DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
   END LOOP;
END;

--User defined record
DECLARE
   type books is record
      (title varchar(50),
       author varchar(50),
       subject varchar(100),
       book_id number);
   book1 books;
   book2 books;
BEGIN
   -- Book 1 specification
   book1.title  := 'C Programming';
   book1.author := 'Nuha Ali ';
   book1.subject := 'C Programming Tutorial';
   book1.book_id := 6495407;

   -- Book 2 specification
   book2.title := 'Telecom Billing';
   book2.author := 'Zara Ali';
   book2.subject := 'Telecom Billing Tutorial';
   book2.book_id := 6495700;

   -- Print book 1 record
   dbms_output.put_line('Book 1 title : '|| book1.title);
   dbms_output.put_line('Book 1 author : '|| book1.author);
   dbms_output.put_line('Book 1 subject : '|| book1.subject);
   dbms_output.put_line('Book 1 book_id : ' || book1.book_id);
 
   -- Print book 2 record
   dbms_output.put_line('Book 2 title : '|| book2.title);
   dbms_output.put_line('Book 2 author : '|| book2.author);
   dbms_output.put_line('Book 2 subject : '|| book2.subject);
   dbms_output.put_line('Book 2 book_id : '|| book2.book_id);
END;

--Records as subprogram parameters
DECLARE
   type books is record
      (title  varchar(50),
      author  varchar(50),
      subject varchar(100),
      book_id   number);
   book1 books;
   book2 books;

PROCEDURE printbook (book books) IS
BEGIN
   dbms_output.put_line ('Book  title :  ' || book.title);
   dbms_output.put_line('Book  author : ' || book.author);
   dbms_output.put_line( 'Book  subject : ' || book.subject);
   dbms_output.put_line( 'Book book_id : ' || book.book_id);
END;
 
BEGIN
   -- Book 1 specification
   book1.title  := 'C Programming';
   book1.author := 'Nuha Ali ';
   book1.subject := 'C Programming Tutorial';
   book1.book_id := 6495407;

   -- Book 2 specification
   book2.title := 'Telecom Billing';
   book2.author := 'Zara Ali';
   book2.subject := 'Telecom Billing Tutorial';
   book2.book_id := 6495700;

   -- Use procedure to print book info
   printbook(book1);
   printbook(book2);
END;

How to Create Procedure in PL/SQL Database Management System But not in SQL

--Creation of procedure--
 
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
   dbms_output.put_line('Hello World!');
END;

--Execution of standalone procedure
EXECUTE greetings;

BEGIN
   greetings;
END;

--Delete procedure
BEGIN
   DROP PROCEDURE greetings;
END;

DROP PROCEDURE greetings;

--Procedure example
DECLARE
   a number;
   b number;
   c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
   IF x < y THEN
      z:= x;
   ELSE
      z:= y;
   END IF;
END;

BEGIN
   a:= 23;
   b:= 45;
   findMin(a, b, c);
   dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;

--Procedure in and out mode
DECLARE
   a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
  x := x * x;
END;
BEGIN
   a:= 23;
   squareNum(a);
   dbms_output.put_line(' Square of (23): ' || a);
END;

How to Use Operator Function in PL/SQL Database Management System But not in SQL

--Operator Function--

DECLARE  
message  varchar2(30):= ''That''s code4use.com!'';
BEGIN   dbms_output.put_line(message);
END;
--Arithmetic operator example
BEGIN
   dbms_output.put_line( 10 + 5);
   dbms_output.put_line( 10 - 5);
   dbms_output.put_line( 10 * 5);
   dbms_output.put_line( 10 / 5);
   dbms_output.put_line( 10 ** 5);
END;

--Relational operator example
DECLARE
   a number (2) := 21;
   b number (2) := 10;
BEGIN
   IF (a = b) then
      dbms_output.put_line('Line 1 - a is equal to b');
   ELSE
      dbms_output.put_line('Line 1 - a is not equal to b');
   END IF;

   IF (a < b) then
      dbms_output.put_line('Line 2 - a is less than b');
   ELSE
      dbms_output.put_line('Line 2 - a is not less than b');
   END IF;
  
   IF ( a > b ) THEN
      dbms_output.put_line('Line 3 - a is greater than b');
   ELSE
      dbms_output.put_line('Line 3 - a is not greater than b');
   END IF;

   -- Lets change value of a and b
   a := 5;
   b := 20;
   IF ( a <= b ) THEN
      dbms_output.put_line('Line 4 - a is either equal or less than b');
   END IF;

   IF ( b >= a ) THEN
      dbms_output.put_line('Line 5 - b is either equal or greater than a');
   END IF;
  
   IF ( a <> b ) THEN
      dbms_output.put_line('Line 6 - a is not equal to b');
   ELSE
      dbms_output.put_line('Line 6 - a is equal to b');
   END IF;

END;

--Conditional operator example
--Like operator
DECLARE
PROCEDURE compare (value  varchar2,  pattern varchar2 ) is
BEGIN
   IF value LIKE pattern THEN
      dbms_output.put_line ('True');
   ELSE
      dbms_output.put_line ('False');
   END IF;
END;

BEGIN
   compare('Zara Ali', 'Z%A_i');
   compare('Nuha Ali', 'Z%A_i');
END;

--Between operator
DECLARE
   x number(2) := 10;
BEGIN
   IF (x between 5 and 20) THEN
      dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;
  
   IF (x BETWEEN 5 AND 10) THEN
      dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;
  
   IF (x BETWEEN 11 AND 20) THEN
      dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;
END;

--In and Null operators
DECLARE
   letter varchar2(1) := 'm';
BEGIN
   IF (letter in ('a', 'b', 'c')) THEN
      dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;

   IF (letter in ('m', 'n', 'o')) THEN
       dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;
  
   IF (letter is null) THEN
    dbms_output.put_line('True');
   ELSE
      dbms_output.put_line('False');
   END IF;
END;

--Logical Operators
DECLARE
   a boolean := true;
   b boolean := false;
BEGIN
   IF (a AND b) THEN
      dbms_output.put_line('Line 1 - Condition is true');
   END IF;
   IF (a OR b) THEN
      dbms_output.put_line('Line 2 - Condition is true');
   END IF;
   IF (NOT a) THEN
      dbms_output.put_line('Line 3 - a is not true');
   ELSE
      dbms_output.put_line('Line 3 - a is true');
   END IF;
   IF (NOT b) THEN
      dbms_output.put_line('Line 4 - b is not true');
   ELSE
      dbms_output.put_line('Line 4 - b is true');
   END IF;
END;

--Operator precedence example
DECLARE
   a number(2) := 20;
   b number(2) := 10;
   c number(2) := 15;
   d number(2) := 5;
   e number(2) ;
BEGIN
   e := (a + b) * c / d;      -- ( 30 * 15 ) / 5
   dbms_output.put_line('Value of (a + b) * c / d is : '|| e );

   e := ((a + b) * c) / d;   -- (30 * 15 ) / 5
   dbms_output.put_line('Value of ((a + b) * c) / d is  : ' ||  e );

   e := (a + b) * (c / d);   -- (30) * (15/5)
   dbms_output.put_line('Value of (a + b) * (c / d) is  : '||  e );

   e := a + (b * c) / d;     --  20 + (150/5)
   dbms_output.put_line('Value of a + (b * c) / d is  : ' ||  e );
END;

How to Create Loop Function in PL/SQL Database Management System But not in SQL

--Basic Loop--
 
DECLARE
   x number := 10;
BEGIN
   LOOP
      dbms_output.put_line(x);
      x := x + 10;
      IF x > 50 THEN
         exit;
      END IF;
   END LOOP;
   -- after exit, control resumes here
   dbms_output.put_line('After Exit x is: ' || x);
END;

DECLARE
   x number := 10;
BEGIN
   LOOP
      dbms_output.put_line(x);
      x := x + 10;
      exit WHEN x > 50;
   END LOOP;
   -- after exit, control resumes here
   dbms_output.put_line('After Exit x is: ' || x);
END;

--While Loop
DECLARE
   a number(2) := 10;
BEGIN
   WHILE a < 20 LOOP
      dbms_output.put_line('value of a: ' || a);
      a := a + 1;
   END LOOP;
END;

--For Loop
DECLARE
   a number(2);
BEGIN
   FOR a in 10 .. 20 LOOP
       dbms_output.put_line('value of a: ' || a);
  END LOOP;
END;

--Reverse For Loop
DECLARE
   a number(2) ;
BEGIN
   FOR a IN REVERSE 10 .. 20 LOOP
      dbms_output.put_line('value of a: ' || a);
   END LOOP;
END;

--Nested Loop
DECLARE
   i number(3);
   j number(3);
BEGIN
   i := 2;
   LOOP
      j:= 2;
      LOOP
         exit WHEN ((mod(i, j) = 0) or (j = i));
         j := j +1;
      END LOOP;
   IF (j = i ) THEN
      dbms_output.put_line(i || ' is prime');
   END IF;
   i := i + 1;
   exit WHEN i = 50;
   END LOOP;
END;

--Labeling a loop
DECLARE
   i number(1);
   j number(1);
BEGIN
   << outer_loop >>
   FOR i IN 1..3 LOOP
      << inner_loop >>
      FOR j IN 1..3 LOOP
         dbms_output.put_line('i is: '|| i || ' and j is: ' || j);
      END loop inner_loop;
   END loop outer_loop;
END;

--Exit Statement
DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a > 15 THEN
         -- terminate the loop using the exit statement
         EXIT;
      END IF;
   END LOOP;
END;

--Exit when statement
DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      -- terminate the loop using the exit when statement
   EXIT WHEN a > 15;
   END LOOP;
END; 

--Continue Demo
DECLARE
   a number(2) := 10;
BEGIN
   -- while loop execution
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a = 15 THEN
         -- skip the loop using the CONTINUE statement
         a := a + 1;
         --CONTINUE;
      END IF;
   END LOOP;
END;

--goto demo
DECLARE
   a number(2) := 10;
BEGIN
   <<loopstart>>
   -- while loop execution
   WHILE a < 20 LOOP
      dbms_output.put_line ('value of a: ' || a);
      a := a + 1;
      IF a = 15 THEN
         a := a + 1;
         GOTO loopstart;
      END IF;
   END LOOP;
END;

How to Create Function in PL/SQL Database Management System But not in SQL

--Function Creation--

CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
   total number(2) := 0;
BEGIN
   SELECT count(*) into total
   FROM customers;
  
   RETURN total;
END;

--Calling of function
DECLARE
   c number(2);
BEGIN
   c := totalCustomers();
   dbms_output.put_line('Total no. of Customers: ' || c);
END;

--Funciton to find max of two numbers
DECLARE
   a number;
   b number;
   c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
    z number;
BEGIN
   IF x > y THEN
      z:= x;
   ELSE
      Z:= y;
   END IF;

   RETURN z;
END;
BEGIN
   a:= 23;
   b:= 45;

   c := findMax(a, b);
   dbms_output.put_line(' Maximum of (23,45): ' || c);
END;

--Recursice Funciton
DECLARE
   num number;
   factorial number;

FUNCTION fact(x number)
RETURN number
IS
   f number;
BEGIN
   IF x=0 THEN
      f := 1;
   ELSE
      f := x * fact(x-1);
   END IF;
RETURN f;
END;

BEGIN
   num:= 6;
   factorial := fact(num);
   dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;

How to Use Exception in PL/SQL Database Management System But not in SQL.

--Exception--
 
DECLARE
   c_id customers.id%type := 8;
   c_name  customers.name%type;
   c_addr customers.address%type;
BEGIN
   SELECT  name, address INTO  c_name, c_addr
   FROM customers
   WHERE id = c_id;

   DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);
   DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
   WHEN no_data_found THEN
      dbms_output.put_line('No such customer!');
   WHEN others THEN
      dbms_output.put_line('Error!');
END;

--User defined exception
DECLARE
   c_id customers.id%type := &cc_id;
   c_name  customers.name%type;
   c_addr customers.address%type;

   -- user defined exception
   ex_invalid_id  EXCEPTION;
BEGIN
   IF c_id <= 0 THEN
      RAISE ex_invalid_id;
   ELSE
      SELECT  name, address INTO  c_name, c_addr
      FROM customers
      WHERE id = c_id;
     
      DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);
      DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
   END IF;
EXCEPTION
   WHEN ex_invalid_id THEN
      dbms_output.put_line('ID must be greater than zero!');
   WHEN no_data_found THEN
      dbms_output.put_line('No such customer!');
   WHEN others THEN
      dbms_output.put_line('Error!');
END;

How to Use Cursor Attribute in PL/SQL Database Management System But not in SQL.

--Cursor attribute--
 
DECLARE
   total_rows number(2);
BEGIN
   UPDATE customers
   SET salary = salary + 500;
   IF sql%notfound THEN
      dbms_output.put_line('no customers selected');
   ELSIF sql%found THEN
      total_rows := sql%rowcount;
      dbms_output.put_line( total_rows || ' customers selected ');
   END IF;
END;

--Working of cursor
DECLARE
   c_id customers.id%type;
   c_name customers.name%type;
   c_addr customers.address%type;
   CURSOR c_customers is
      SELECT id, name, address FROM customers;
BEGIN
   OPEN c_customers;
   LOOP
      FETCH c_customers into c_id, c_name, c_addr;
      EXIT WHEN c_customers%notfound;
      dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
   END LOOP;
   CLOSE c_customers;
END;

How to Use Condition in PL/SQL Database Management System But not in SQL.

--Conditions--
DECLARE
   a number(2) := 10;
BEGIN
   a:= 10;
  -- check the boolean condition using if statement
   IF( a < 20 ) THEN
      -- if condition is true then print the following 
      dbms_output.put_line('a is less than 20 ' );
   END IF;
   dbms_output.put_line('value of a is : ' || a);
END;

select * from customers;

DECLARE
   c_id customers.id%type := 1;
   c_sal  customers.salary%type;
BEGIN
   SELECT  salary
   INTO  c_sal
   FROM customers
   WHERE id = c_id;
   IF (c_sal <= 2000) THEN
      UPDATE customers
      SET salary =  salary + 1000
         WHERE id = c_id;
      dbms_output.put_line ('Salary updated');
   END IF;
END;

DECLARE
   a number(3) := 100;
BEGIN
   -- check the boolean condition using if statement
   IF( a < 20 ) THEN
      -- if condition is true then print the following 
      dbms_output.put_line('a is less than 20 ' );
   ELSE
      dbms_output.put_line('a is not less than 20 ' );
   END IF;
   dbms_output.put_line('value of a is : ' || a);
END;

DECLARE
   a number(3) := 100;
BEGIN
   IF ( a = 10 ) THEN
      dbms_output.put_line('Value of a is 10' );
   ELSIF ( a = 20 ) THEN
      dbms_output.put_line('Value of a is 20' );
   ELSIF ( a = 30 ) THEN
      dbms_output.put_line('Value of a is 30' );
   ELSE
       dbms_output.put_line('None of the values is matching');
   END IF;
   dbms_output.put_line('Exact value of a is: '|| a );
END;

DECLARE
   grade char(1) := 'A';
BEGIN
   CASE grade
      when 'A' then dbms_output.put_line('Excellent');
      when 'B' then dbms_output.put_line('Very good');
      when 'C' then dbms_output.put_line('Well done');
      when 'D' then dbms_output.put_line('You passed');
      when 'F' then dbms_output.put_line('Better try again');
      else dbms_output.put_line('No such grade');
   END CASE;
END;

DECLARE
   grade char(1) := 'B';
BEGIN
   case
      when grade = 'A' then dbms_output.put_line('Excellent');
      when grade = 'B' then dbms_output.put_line('Very good');
      when grade = 'C' then dbms_output.put_line('Well done');
      when grade = 'D' then dbms_output.put_line('You passed');
      when grade = 'F' then dbms_output.put_line('Better try again');
      else dbms_output.put_line('No such grade');
   end case;
END;

--Nested if demo
DECLARE
   a number(3) := 100;
   b number(3) := 200;
BEGIN
   -- check the boolean condition
   IF( a = 100 ) THEN
   -- if condition is true then check the following
      IF( b = 200 ) THEN
      -- if condition is true then print the following
         dbms_output.put_line('Value of a is 100 and b is 200' );
      END IF;
   END IF;
   dbms_output.put_line('Exact value of a is : ' || a );
   dbms_output.put_line('Exact value of b is : ' || b );
END;