Sunday 22 July 2018

A Java Program to illustrate Caesar Cipher Technique (CSS)


class CaesarCipher
{
    // Encrypts text using a shift od s
    public static StringBuffer encrypt(String text, int s)
    {
        StringBuffer result= new StringBuffer();

        for (int i=0; i<text.length(); i++)
        {
            if (Character.isUpperCase(text.charAt(i)))
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 65) % 26 + 65);
                result.append(ch);
            }
            else
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 97) % 26 + 97);
                result.append(ch);
            }
        }
        return result;
    }

    // Driver code
    public static void main(String[] args)
    {
        String text = "ATTACKATONCE";
        int s = 4;
        System.out.println("Text  : " + text);
        System.out.println("Shift : " + s);
        System.out.println("Cipher: " + encrypt(text, s));
    }
}

Thursday 26 April 2018

Implementation of simple mobile node scenario using NS simulator (MCC)

# simple-wireless.tcl
# A simple example for wireless simulation

# ======================================================================
# Define options
# ======================================================================
set val(chan)           Channel/WirelessChannel    ;# channel type
set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model
set val(netif)          Phy/WirelessPhy            ;# network interface type
set val(mac)            Mac/802_11                 ;# MAC type
set val(ifq)            Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)             LL                         ;# link layer type
set val(ant)            Antenna/OmniAntenna        ;# antenna model
set val(ifqlen)         50                         ;# max packet in ifq
set val(nn)             3                          ;# number of mobilenodes
set val(rp)             DSDV                       ;# routing protocol
set val(x)              500           ;# X dimension of the topography
set val(y)              500       ;# Y dimension of the topography

# ======================================================================
# Main Program
# ======================================================================


#
# Initialize Global Variables
#
set ns_ [new Simulator]
set tracefd     [open simple.tr w]
set namtrace    [open simple.nam w]
$ns_ trace-all $tracefd
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)

# set up topography object
set topo       [new Topography]

$topo load_flatgrid $val(x) $val(y)

#
# Create God
#
create-god $val(nn)

#
#  Create the specified number of mobilenodes [$val(nn)] and "attach" them
#  to the channel.
#  Here two nodes are created : node(0) and node(1)

# configure node

$ns_ node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF

for {set i 0} {$i < $val(nn) } {incr i} {
set node_($i) [$ns_ node]
$node_($i) random-motion 0 ;# disable random motion
}

#
# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodes
#
$node_(0) set X_ 200.0
$node_(0) set Y_ 100.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 100.0
$node_(1) set Y_ 355.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0
$node_(2) set Y_ 150.0
$node_(2) set Z_ 0.0

#
# Now produce some simple node movements
# Node_(1) starts to move towards node_(0)
#
$ns_ at 20.0 "$node_(1) setdest 145.0 20.0 15.0"
$ns_ at 10.0 "$node_(0) setdest 150.0 50.0 1.0"

# node 2 starts tomove towards node 0
$ns_ at 30.0 "$node_(2) setdest 148.0 40.0 1.0"
$ns_ at 10.0 "$node_(0) setdest 150.0 50.0 1.0"

# Node_(1) then starts to move away from node_(0)
$ns_ at 90.0 "$node_(1) setdest 390.0 160.0 15.0"
$ns_ at 90.0 "$node_(2) setdest 222.0 150.0 15.0"

# Setup traffic flow between nodes
# TCP connections between node_(0) and node_(1)

set tcp [new Agent/TCP]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns_ attach-agent $node_(0) $tcp
$ns_ attach-agent $node_(1) $sink
$ns_ connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns_ at 10.0 "$ftp start"

#
# Tell nodes when the simulation ends
#
for {set i 0} {$i < $val(nn) } {incr i} {
$ns_ at 150.0 "$node_($i) reset";
}
$ns_ at 200.0 "stop"
$ns_ at 200.01 "puts \"NS EXITING...\" ; $ns_ halt"
proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
exec nam simple.nam
}
puts $tracefd "M 0.0 nn $val(nn) x $val(x) y $val(y) rp $val(rp)"

puts "Starting Simulation..."
$ns_ run

Output:


Pass-2 Macro processor flowchart (SPCC)


Pass-1 Macro processor flowchart (SPCC)


Implementation of Simple mobile application using Netbeans (MCC)

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* @author codept
*/
public class Midlet extends MIDlet {

public void startApp() {
Form form=new Form("Computer Engg Dept");
form.append("Welcome To AIKTC\n");
form.append("experiment No: 07\n");
form.append("Subjetc: MCC\n");
form.append("Name: Chandresh Prasad\n");
form.append("Roll No: 11CO35");

Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {

}
public void destroyApp(boolean unconditional) {

}
}

Output:



WAP in C to find first & follow of given grammer (SPCC)

#include<stdio.h>
#include<ctype.h>
char a[8][8];

struct firTab
{
int n;
char firT[5];
};
struct folTab
{
int n;
char folT[5];
};
struct folTab follow[5];
struct firTab first[5];
int col;
void findFirst(char,char);
void findFollow(char,char);
void folTabOperation(char,char);
void firTabOperation(char,char);
void main()
{
int i,j,c=0,cnt=0;
char ip;
char b[8];
printf("\nFIRST AND FOLLOW SET \n\nenter 8 productions in format A->B+T\n");
for(i=0;i<8;i++)
{
scanf("%s",&a[i]); 
}
for(i=0;i<8;i++)
{   c=0;
for(j=0;j<i+1;j++)
{
if(a[i][0] == b[j])
{
c=1;   
break;
}   
}
if(c !=1)
{
b[cnt] = a[i][0];
cnt++;
}             

}
printf("\n");

for(i=0;i<cnt;i++)
{   col=1;
first[i].firT[0] = b[i];
first[i].n=0;
findFirst(b[i],i);
}
for(i=0;i<cnt;i++)
{
col=1;
follow[i].folT[0] = b[i];
follow[i].n=0;
findFollow(b[i],i);
}

printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=first[i].n;j++)
{
if(j==0)
{
printf("First(%c) : {",first[i].firT[j]);
}
else

printf(" %c",first[i].firT[j]);
}
}
printf(" } ");
printf("\n");
}
printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=follow[i].n;j++)
{
if(j==0)
{
printf("Follow(%c) : {",follow[i].folT[j]);
}
else

printf(" %c",follow[i].folT[j]);
}
}
printf(" } ");

printf("\n");
}

}
void findFirst(char ip,char pos)
{
int i;
for(i=0;i<8;i++)
{
if(ip == a[i][0])
{
if(isupper(a[i][3]))
{
findFirst(a[i][3],pos);
}
else
{

first[pos].firT[col]=a[i][3];
first[pos].n++;
col++;
}
}
}
}
void findFollow(char ip,char row)
{   int i,j;
if(row==0 && col==1)
{
follow[row].folT[col]= '$';
col++;
follow[row].n++;
}
for(i=0;i<8;i++)
{
for(j=3;j<7;j++)
{
if(a[i][j] == ip)
{
if(a[i][j+1] == '\0')
{
if(a[i][j] != a[i][0])
{
folTabOperation(a[i][0],row);
}
}
else if(isupper(a[i][j+1]))
{   if(a[i][j+1] != a[i][0])
{
firTabOperation(a[i][j+1],row);                                   

}
}
else
{
follow[row].folT[col] = a[i][j+1]; 
col++;
follow[row].n++;           



}
}

}
void folTabOperation(char ip,char row)
{   int i,j;
for(i=0;i<5;i++)
{
if(ip == follow[i].folT[0])
{
for(j=1;j<=follow[i].n;j++)
{
follow[row].folT[col] = follow[i].folT[j];
col++;
follow[row].n++;
}
}

}
void firTabOperation(char ip,char row)

int i,j;
for(i=0;i<5;i++)
{
if(ip == first[i].firT[0])
{
for(j=1;j<=first[i].n;j++)
{
if(first[i].firT[j] != '0')
{
follow[row].folT[col] = first[i].firT[j];
follow[row].n++;
col++;                 
}
else
{
folTabOperation(ip,row);
}
}
}
}

}

Output:

input productions

E->TA
A->+TA
A->0
T->FB
B->*FB
B->0
F->(E)
F->#

enter 8 productions in format A->B+T
E->TA
A->+TA
A->0
T->FB
B->*FB
B->0
F->(E)
F->#

First(E) : { ( # }
First(A) : { + 0 }
First(T) : { ( # }
First(B) : { * 0 }
First(F) : { ( # }

Follow(E) : { $ ) }
Follow(A) : { $ ) }
Follow(T) : { + $ ) }
Follow(B) : { + $ ) }
Follow(F) : { * + $ ) } 

WAP in C to remove left recursion from a given grammar (SPCC)

#include<stdio.h> 
#include<string.h> 
#define SIZE 10 
int main () { 
char non_terminal; 
char beta,alpha; 
int num; 
char production[10][SIZE]; 
int index=3; /* starting of the string following "->" */ 
printf("Enter Number of Production : "); 
scanf("%d",&num); 
printf("Enter the grammar as E->E-A :\n"); 
for(int i=0;i<num;i++){ 
scanf("%s",production[i]); 

for(int i=0;i<num;i++){ 
printf("\nGRAMMAR : : : %s",production[i]); 
non_terminal=production[i][0]; 
if(non_terminal==production[i][index]) { 
alpha=production[i][index+1]; 
printf(" is left recursive.\n"); 
while(production[i][index]!=0 && production[i][index]!='|') 
index++; 
if(production[i][index]!=0) { 
beta=production[i][index+1]; 
printf("Grammar without left recursion:\n"); 
printf("%c->%c%c\'",non_terminal,beta,non_terminal);     
printf("\n%c\'->%c%c\'|E\n",non_terminal,alpha,non_terminal); 

else 
printf(" can't be reduced\n"); 

else 
printf(" is not left recursive.\n"); 
index=3; 



Output:

Enter Number of Production : 2
Enter the grammar as E->E-A :
E->EA|A
A->AT|a

GRAMMAR : : : E->EA|A is left recursive.
Grammar without left recursion:
E->AE'
E'->AE'|E

GRAMMAR : : : A->AT|a is left recursive.
Grammar without left recursion:
A->aA'
A'->TA'|E

WAP in c to find first of given grammar (SPCC)

#include<stdio.h>
#include<ctype.h>

void FIRST(char[],char );
void addToResultSet(char[],char);
int numOfProductions;
char productionSet[10][10];
main()
{
int i;
char choice;
char c;
char result[20];
printf("How many number of productions ? :");
scanf(" %d",&numOfProductions);
for(i=0;i<numOfProductions;i++)//read production string eg: E=E+T
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",productionSet[i]);
}
do
{
printf("\n Find the FIRST of  :");
scanf(" %c",&c);
FIRST(result,c); //Compute FIRST; Get Answer in 'result' array
printf("\n FIRST(%c)= { ",c);
for(i=0;result[i]!='\0';i++)
printf(" %c ",result[i]);       //Display result
printf("}\n");
printf("press 'y' to continue : ");
scanf(" %c",&choice);
}
while(choice=='y'||choice =='Y');
}

void FIRST(char* Result,char c)
{
int i,j,k;
char subResult[20];
int foundEpsilon;
subResult[0]='\0';
Result[0]='\0';
if(!(isupper(c)))
{
addToResultSet(Result,c);
return ;
}
for(i=0;i<numOfProductions;i++)
{
if(productionSet[i][0]==c)
{
if(productionSet[i][2]=='$') addToResultSet(Result,'$');
else
{
j=2;
while(productionSet[i][j]!='\0')
{
foundEpsilon=0;
FIRST(subResult,productionSet[i][j]);
for(k=0;subResult[k]!='\0';k++)
addToResultSet(Result,subResult[k]);
for(k=0;subResult[k]!='\0';k++)
if(subResult[k]=='$')
{
foundEpsilon=1;
break;
}
if(!foundEpsilon)
break;
j++;
}
}
}
}
return ;
}

void addToResultSet(char Result[],char val)
{
int k;
for(k=0 ;Result[k]!='\0';k++)
if(Result[k]==val)
return;
Result[k]=val;
Result[k+1]='\0';
}

Output:

How many number of productions ? :3
Enter productions Number 1 : E=Jp
Enter productions Number 2 : J=q
Enter productions Number 3 : S=E

Find the FIRST of  :E

FIRST(E)= {  q }
press 'y' to continue : Y

Find the FIRST of  :S

FIRST(S)= {  q }
press 'y' to continue : Y

WAP in c to find first & follow of given grammer (SPCC)

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

int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void first(char c);

void follow(char c)
{
if(a[0][0]==c)
f[m++]='$';
for(i=0;i<n;i++)
{
for(j=2;j<strlen(a[i]);j++)
{
if(a[i][j]==c)
{
if(a[i][j+1]!='\0')
first(a[i][j+1]);
if(a[i][j+1]=='\0' && c!=a[i][0])
follow(a[i][0]);
}
}
}
}

void first(char c)
{
int k;
if(! isupper(c))
f[m++]=c;
for(k=0;k<n;k++)
{
if(a[k][0]==c)
{
if(a[k][2]=='<')
follow(a[k][0]);
else if(islower(a[k][2]))
f[m++]=a[k][2];
else
first(a[k][2]);
}
}
}

int main() {
int i,z;
char c,ch;
printf("Enter the no of productions:\n");
scanf("%d",&n);
printf("Enter the productions:\n");
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
do {
m=0;
printf("Enter the elemets whose first & follow is to be found:");
scanf("%c",&c);
first(c);
printf("First(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
strcpy(f," ");
m=0;
follow(c);
printf("Follow(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
printf("Continue(0/1)?");
scanf("%d%c",&z,&ch);
} while(z==1);
return(0);
}

OUTPUT:

Enter the no of productions:
5
Enter the productions:
S=AbCd
A=Cf
A=a
C=gE
E=h
Enter the elemets whose first & follow is to be found:S
First(S)={ga}
Follow(S)={$}
Continue(0/1)?1
Enter the elemets whose first & follow is to be found:A
First(A)={ga}
Follow(A)={b}
Continue(0/1)?1
Enter the elemets whose first & follow is to be found:C
First(C)={g}
Follow(C)={df}
Continue(0/1)?1
Enter the elemets whose first & follow is to be found:E
First(E)={h}
Follow(E)={df}
Continue(0/1)?0

WAP in Java (pre defined in file) to display pseudo opcode and location counter (SPCC)

import java.io.*;
import java.lang.*;

class Mot
{
//static int n=0,LOC=0,locn=0,stmt=0,i;
public static void main(String args[]) throws Exception

String s;
String program[]=new String[100];
String label[]=new String[100];
String mneop[]=new String[10];
// int[] LOC=new int[15];
int N=0,n=0,j,i,k=0;

System.out.println("Assembly lang program :\n--------------------------");

//code for file  opening and printing the program  line by line
FileReader fr=new FileReader("program1.asm");
BufferedReader br=new BufferedReader(fr);
while((s = br.readLine()) != null)
{
program[N++]=s;
System.out.println(s);
//System.out.println(N);
}

fr.close(); // closing the file

FileReader labels=new FileReader("label1.txt");
BufferedReader buff=new BufferedReader(labels);

while((s=buff.readLine())!= null)
{
label[n++]=s;
System.out.println();
}

labels.close();

System.out.println("\n\n Machine Opcode Table :--\n \nMnemonic opcode | LENGTH(in bytes) | Instruction Format");
System.out.println("-------------------------------------------------------------------------");
for(i=0;i<N;i++)
{
//char codearr[]=new char[15];
//codearr=program[i].toCharArray();
for(j=0;j<n;j++)
{     
if(program[i].startsWith("END"))
return;

if(program[i].startsWith("USING"))
break;

if(program[i].startsWith(label[j]))
break;

else if(j==n-1)
{
for(String l:program[i].split("\\s"))
{
mneop[k++]=l;
System.out.println(l+"\t\t| 4 \t\t   | 001");
break;
}
break;
}
}
}
}
}

label1.txt

ST 2,TEMP
FOUR DC F '4'
FIVE DC F '5'
TEMP DS '1'F
END

Output:

Machine Opcode Table :--

Mnemonic opcode | LENGTH(in bytes) | Instruction Format
-------------------------------------------------------------------------
L | 4    | 001
A | 4    | 001
ST | 4    | 001
------------------
(program exited with code: 0)
Press return to continue

Implement Macro processor to create MNT (SPCC)

import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class macro
{
public static void main(String args[])throws IOException
{
int MDTC=1;
int MNTC=1;
int index=1;
int macroindex=0;
String arg[]=new String[10];
String mname[]=new String[10];
String MNT [][]=new String[10][10];
String MDT [][]=new String[10][10];
String output =new Scanner(new File("File1.txt")).useDelimiter("\\Z").next();
String result[]=output.split("\n");
String result1[]=output.split("[,\\s\\?]");
for(int k=0;k<result1.length;k++)
{
if(result1[k].equals("MACRO")||result1[k].equals("macro"))
{
mname[macroindex]=result1[k+2];
macroindex++;
}
}
System.out.println("\nMACRO NAME TABLE\n—————————————–");
System.out.println("VALUE OF MDTC\tMNTC\tNAME");
for(int k=0;k<macroindex;k++)
{
System.out.println("\t"+MDTC+"\t"+MNTC+"\t"+mname[k]);
MNTC=MNTC+1;
}
}}

Output:

aiktc@aiktc93 ~/Desktop $ java macro
MACRO NAME TABLE
—————————————–
VALUE OF MDTC MNTC NAME
1 1 &arg1

File1.txt

MACRO
ADDITION &arg1,&arg2,&arg3
MOV ax,&arg1
ADD ax,&arg2
ADD ax,&arg3
MEND
ADDITION 34,45,44
END

WAP to remove left recursion from a given grammar (SPCC)

production=input("Enter the production:")
print(production)
product=production.split('->')
l=product[1].split('|')
ans=product[0]+'\''
anslist=[]
anslist2=['epsilon']
for e in l:
if(product[0] not in e):
anslist.append(e+ans)
else:
anslist2.append(e[1:]+ans)
answer=''
for e in anslist:
answer=answer+e+'|'
answer=answer[:-1]
if(answer==''):
answer=ans
print(product[0]+'->'+answer)
answer=''
for e in anslist2:
answer=answer+e+'|'
answer=answer[:-1]
print(ans+'->'+answer)

Output:

Enter the production:E->E+T|E*T|T
E->E+T|E*T|T
E=>TE'
E'=>epsilon|+TE'|*TE'

Enter the production:E->E+T|E*T|T|T2
E->E+T|E*T|T|T2
E=>TE'|T2E'
E'=>epsilon|+TE'|*TE'

Sunday 8 April 2018

Implementation of Name Resolution Protocol Using Java

import java.util.*;
import java.io.*;
import java.net.*;

public class NameResolution
{
public static void main(String arg[])
throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the URL: ");
String name = sc.next();
try
{
InetAddress ip = InetAddress.getByName(name);
System.out.println("IP Address : "+ip.getHostAddress());
}
catch(UnknownHostException e)
{
System.out.println("\n No Such Host Found");
}
}
}

/*
aiktc@aiktc38 ~ $ cd Desktop
aiktc@aiktc38 ~/Desktop $ javac NameResolution.java
aiktc@aiktc38 ~/Desktop $ java NameResolution

Enter the URL:
www.wwe.com
IP Address : 104.80.51.135

aiktc@aiktc38 ~/Desktop $ javac NameResolution.java
aiktc@aiktc38 ~/Desktop $ java NameResolution
Enter the URL:
www.facebook.com 
IP Address : 31.13.78.35

aiktc@aiktc38 ~/Desktop $ javac NameResolution.java
aiktc@aiktc38 ~/Desktop $ java NameResolution
Enter the URL:
aiktc 
No Such Host Found
*/

Monday 26 February 2018

ANALYSIS OF MERGE SORT C PROGRAM

#include<stdio.h>
#include<stdlib.h>
#define MAX 10

void combine(int a[MAX],int low,int mid,int high)
{
int i,j,k;
int temp[MAX];
k=low;             //k AS INDEX FOR ARRAY temp
i=low;   //i AS INDEX FOR LEFT SUBARRAY
j=mid+1;   //j AS INDEX FOR RIGHR SUBARRAY
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)      //COPYING REMAINING ELEMENT OF LEFT SUBARRAY
{
temp[k]=a[i];
i++;
k++;
}
while(j<=high)     //COPYING REMAINING ELEMENT OF LEFT SUBARRAY
{
temp[k]=a[j];
j++;
k++;
}
for(k=low;k<=high;k++)
a[k]=temp[k];
}
void Display(int a[MAX],int n)
{
int i;
printf("THE SORTED ARRAY IS :\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

void MergeSort(int a[MAX],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;          //SPLIT THE LIST AT MID
MergeSort(a,low,mid);    //LEFT SUBARRAY
MergeSort(a,mid+1,high);   //RIGHT SUBARRAY
combine(a,low,mid,high);   //MERGING OF TWO SUBARRAY
}
}

int main()
{
int i,low=0,n;
printf("MERGE SORT :: \n");
printf("ENTER THE LENGTH OF LIST : ");
scanf("%d",&n);
int a[MAX];
printf("ENTER THE ELEMENT OF A LIST :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
MergeSort(a,low,n-1);
Display(a,n);
}

OUTPUT :
------------------------------------
MERGE SORT ::
ENTER THE LENGTH OF LIST : 5
ENTER THE ELEMENT OF A LIST :
85
9
36
45
25
THE SORTED ARRAY IS :
9 25 36 45 85

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

ANALYSIS OF BINARY SEARCH C PROGRAM

#include<stdio.h>
#include<stdlib.h>
#define MAX 10

int binary_search(int a[],int n,int x)
{
int mid=n/2;
int high=n-1,low=0;
while(high>=low)
{
if(a[mid]==x)
return mid;
if(x>a[mid])
low=mid+1;       //SEARCH THE RIGHT SUBARRAY
else
high=mid-1;      //SEARCH THE LEFT SUBARRAY
mid=(low+high)/2;
}
return -1;
}

int main()
{
int i,a[MAX],no,x;
printf("ENTER THE NO OF ELEMENTS :: ");
scanf("%d",&no);
printf("ENTER THE ELEMENTS OF AN ARRAY :: \n");
for(i=0;i<no;i++)
scanf("%d",&a[i]);
printf("THE NO YOU WANT TO SEARCH::");
scanf("%d",&x);
if(binary_search(a,no,x)!=-1)
printf("\nELEMENT FOUND AT %d INDEX IN AN ARRAY",binary_search(a,no,x));
else
printf("\nTHE ELEMENT IS NOT FOUND");
}

OUTPUT :
-------------------------------------------
ENTER THE NO OF ELEMENTS :: 4
ENTER THE ELEMENTS OF AN ARRAY ::
55
85
68
18
THE NO YOU WANT TO SEARCH::18

ELEMENT FOUND AT 3 INDEX IN AN ARRAY

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

Wednesday 7 February 2018

PROGRAM TO IMPLEMENT DECISION MAKING,LOOPING,CONTROL STATEMENTS

import java.util.*;// since we are creating object of scanner class
class Loops
{
public static void main(String args[])
{
int i,j,fact=1,rev=0,r,ch,n;
do{
System.out.println("\n\t ****Menu****");
System.out.println("1. find ood even number(if el)");
System.out.println("2. Factorial of a number(for loop)");
System.out.println("3. print partter of a(right angle triangle inserted for loop)");
System.out.println("4. reverse of number (while loop)");
System.out.println("5. Exit\n");
System.out.print("Enter Choice");
Scanner sc=new Scanner(System.in);
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("enter number ");
n=sc.nextInt();
if(n%2==0)
{
System.out.println("entered no."+n+" is even");
}
else
{
System.out.println("entered no."+n+" is odd");
}
break;


case 2:
System.out.println("enter number ");
n=sc.nextInt();
for (i=2;i<=n;i++)
{
fact=fact*i;
}
System.out.println("FActorial of "+n+";"+fact);
break;

case 3:
for(i=1;i<=4;i++)
{//start outer for loop
for(j=1;j<=i;j++)
{//start outer for loop
System.out.print("*");
}//end of outer for loop
System.out.println(" ");
}//end outer for loop
break;

case 4:
System.out.println("enter number");
n=sc.nextInt();
while(n!=0)
{
r=n%10;
rev=(rev*10)+r;
n=n/10;
}
System.out.println("reverse of given number:" +rev);
break;

case 5:
System.exit(0);
break;

default:
System.out.println("please enter the valid choice");
}//end of while
}while(true);
}//end of main
}//end of class

Output:

      ****Menu****
1. find ood even number(if el)
2. Factorial of a number(for loop)
3. print partter of a(right angle triangle inserted for loop)
4. reverse of number (while loop)
5. Exit

Enter Choice1
enter number
3
entered no.3 is odd

****Menu****
1. find ood even number(if el)
2. Factorial of a number(for loop)
3. print partter of a(right angle triangle inserted for loop)
4. reverse of number (while loop)
5. Exit

Enter Choice2
enter number
5
FActorial of 5;120

****Menu****
1. find ood even number(if el)
2. Factorial of a number(for loop)
3. print partter of a(right angle triangle inserted for loop)
4. reverse of number (while loop)
5. Exit

Enter Choice3
*
**
***
****

****Menu****
1. find ood even number(if el)
2. Factorial of a number(for loop)
3. print partter of a(right angle triangle inserted for loop)
4. reverse of number (while loop)
5. Exit

Enter Choice4
enter number
1234
reverse of given number:4321

****Menu****
1. find ood even number(if el)
2. Factorial of a number(for loop)
3. print partter of a(right angle triangle inserted for loop)
4. reverse of number (while loop)
5. Exit

Enter Choice5


------------------
(program exited with code: 0)
Press return to continue

Java program to perform Circular convolution of periodic sequence (DSP)

import java.util.*;

class ConcentricMatrix
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x1Length,x2Length,i=0,j=0;

// First Sequence
System.out.println("Enter the length of first sequence");
x1Length = sc.nextInt();

int x1[][]=new int[x1Length][x1Length];
int x2[]=new int[x1Length];
int y[]=new int[x1Length];

System.out.println("Enter first sequence");

for(i=0;i<x1Length;i++)
x1[0][i] = sc.nextInt();


// Second Sequence
System.out.println("Enter the length of second sequence");
x2Length = sc.nextInt();


System.out.println("Enter second sequence");

for(i=0;i<x2Length;i++)
x2[i] = sc.nextInt();

// Padding
if(x1Length>x2Length)
{
for(i=x1Length;i<x2Length;i++)
x2[i]=0;
}

// Circular Matrix
for(i=1;i<x1Length;i++)
{
for(j=0;j<x1Length;j++)
{
if(j-1<0)
x1[i][j]=x1[i-1][x1Length-1];
else
x1[i][j]=x1[i-1][j-1];

}
}


// Print Circular Matrix
System.out.println("\nCircular Matrix");
for(i=0;i<x1Length;i++)
{
for(j=0;j<x1Length;j++)
{
System.out.print(x1[j][i] + "\t");
}
System.out.println("");
}


// Perform Circular Matrix
for(i=0;i<x1Length;i++)
{
for(j=0;j<x1Length;j++)
{
y[i]+=(x1[j][i]*x2[j]);
}
}

// Print Output
System.out.println("\nCircular Convolution - y(n)");
for(i=0;i<x1Length;i++)
{
System.out.print(y[i] + "\t");
}

}
}

OUTPUT:

Enter the length of first sequence
4
Enter first sequence
1
2
3
4
Enter the length of second sequence
3
Enter second sequence
7
0
3

Circular Matrix
1 4 3 2
2 1 4 3
3 2 1 4
4 3 2 1

Circular Convolution - y(n)
16 26 24 34

Program to understand Continuebreak Label

class Continuebreak
  {
  public static void main(String args[])
  {
  LOOP1:for(int i=1;i<100;i++)
  {
  System.out.println(" ");
  if(i>=10) break;
  LOOP2:for(int j=1;j<100;j++)
  {
  System.out.print(" * ");
  if(j==i)
  continue LOOP1;
  }
  }
  System.out.println("terminated by break LOOP1");
  }
  }

Output:
 
   *
   *  *
   *  *  *
   *  *  *  *
   *  *  *  *  *
   *  *  *  *  *  *
   *  *  *  *  *  *  *
   *  *  *  *  *  *  *  *
   *  *  *  *  *  *  *  *  *
  terminated by break LOOP1

Program to understand creation of classes,object and method

class Room
{
float length;
float breadth;
void getdata(float a,float b)
{
length=a;
breadth=b;

}

}

class RoomArea
{
public static void main(String args[])
{
float area;
Room R1=new Room();//creating object of class Room
R1.getdata(14,10);//calling method of Room class
area=R1. length*R1.breadth;//calling variables of Room class
System.out.println("Area of Room is:"+area);
}
}

Java Program to accept data through keyboard

import java.util.*;
import java.io.*;

class input 
{
 public static void main (String args[]) throws Exception
 {
   int i;
   Scanner sc=new Scanner(System.in);
   System.out.println("enter a number");
   i=sc.nextInt();
   System.out.println("entered number is:"+i);
 
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   System.out.println("enter a statement");
   String s=br.readLine();
   System.out.println("enter line is:"+s);
}
}

Output:
enter a number
10
entered number is:10
enter a statement
we are engineers
enter line is:we are boys

Monday 8 January 2018

C Program for leftrecursion

#include<stdio.h> 
#include<string.h> 
#define SIZE 10 

int main () { 
char non_terminal; 
char beta,alpha; 
int num; 
char production[10][SIZE]; 
int index=3; /* starting of the string following "->" */ 
printf("Enter Number of Production : "); 
scanf("%d",&num); 
printf("Enter the grammar as E->E-A :\n"); 
for(int i=0;i<num;i++){ 
scanf("%s",production[i]); 

for(int i=0;i<num;i++){ 
printf("\nGRAMMAR : : : %s",production[i]); 
non_terminal=production[i][0]; 
if(non_terminal==production[i][index]) { 
alpha=production[i][index+1]; 
printf(" is left recursive.\n"); 
while(production[i][index]!=0 && production[i][index]!='|') 
index++; 
if(production[i][index]!=0) { 
beta=production[i][index+1]; 
printf("Grammar without left recursion:\n"); 
printf("%c->%c%c\'",non_terminal,beta,non_terminal);     
printf("\n%c\'->%c%c\'|E\n",non_terminal,alpha,non_terminal); 

else 
printf(" can't be reduced\n"); 

else 
printf(" is not left recursive.\n"); 
index=3; 



/*
Output------------------------------------------
aiktc@aiktc11 ~ $ gcc -std=c99 leftrecursion.c
aiktc@aiktc11 ~ $ ./a.out
Enter Number of Production : 2
Enter the grammar as E->E-A :
E->EA|A
A->AT|a

GRAMMAR : : : E->EA|A is left recursive.
Grammar without left recursion:
E->AE'
E'->AE'|E

GRAMMAR : : : A->AT|a is left recursive.
Grammar without left recursion:
A->aA'
A'->TA'|E
aiktc@aiktc11 ~ $
*/

STUDY AND IMPLEMENT WAIT FOR GRAPH IN DEADLOCK (DD)

import java.io.*;
import java.util.*;

public class WaitForGraph {
public static void main(String args[]) {

int n;

Scanner scr=new Scanner(System.in);
System.out.println("Enter the number of transcation : ");
n=scr.nextInt();

int t[][]=new int[n][n];

System.out.println("Enter the Adjency Matrix of ["+n+"]["+n+"]");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
System.out.print("\nT["+i+"]["+j+"]");
t[i][j]=scr.nextInt();
}
System.out.println("You Have Entered the Adjency Matrix of ["+n+"]["+n+"]");
for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
System.out.print(" "+t[i][j]);

System.out.println("");
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{ if(t[i][j]==1)
{ for(int k=0;k<n;k++)
{ if(t[j][k]==1)
{
if(n==2 && i==k && !(i==j))
{
System.out.println("DeadLock Cycle Detected T"+(i+1)+"-->T"+(j+1)+"-->T"+(i+1));
System.exit(0);
}
if(t[k][i]==1 && n!=2)
{
System.out.println("DeadLock Cycle Detected T"+(i+1)+"-->T"+(j+1)+"-->T"+(k+1)+"-->T"+(i+1));
System.exit(0);
}
}
}
}
}
}

System.out.println("No Deadlock Cycle Detected");
}
}

/* OUTPUT :

aiktc@aiktc17 ~ $ javac WaitForGraph.java
aiktc@aiktc17 ~ $ java WaitForGraph
Enter the number of transcation :
2
Enter the Adjency Matrix of [2][2]

T[0][0]1

T[0][1]2

T[1][0]1

T[1][1]1
You Have Entered the Adjency Matrix of [2][2]
1 2
1 1
No Deadlock Cycle Detected
aiktc@aiktc17 ~ $ java WaitForGraph
Enter the number of transcation :
3
Enter the Adjency Matrix of [3][3]

T[0][0]1

T[0][1]2

T[0][2]3

T[1][0]4

T[1][1]5

T[1][2]6

T[2][0]7

T[2][1]8

T[2][2]9
You Have Entered the Adjency Matrix of [3][3]
1 2 3
4 5 6
7 8 9
DeadLock Cycle Detected T1-->T1-->T1-->T1
*/

STUDY AND IMPLEMENT TWO PHASE LOCKING PROTOCOL (DD)

import java.io.*;
import java.util.*;
class Account
{
String name;
int amount,lock;
Account(String name,int amount,int lock)
{
this.name=name;
this.amount=amount;
this.lock=lock;
}
public void deposit(int amt)
{
amount +=amt;
}
public void withdraw(int amt)
{
if((amount-amt)<0)
{
System.out.println("Transaction Cannot proceed : Not Enough Balance in Account"+name);
System.exit(0);
}
amount -=amt;

}
public int balance()
{
return amount;
}
}

class Transaction implements Runnable
{
private Thread t=null;
String id;
Account from,to;
int amount;
Transaction(String id,Account from,Account to,int amount)
{
this.id=id;
this.from=from;
this.to=to;
this.amount=amount;
}

public void acquireLock(Account x,int type)
{
x.lock=type;
}

public void releaseLock(Account x)
{
x.lock=0;
}

public void  run() {
System.out.println("Running Transaction" +  id );
try {
acquireLock(from,2);
acquireLock(to,2);
from.withdraw(amount);
to.deposit(amount);
System.out.println("Transaction "+id+" is completed");
releaseLock(from);
releaseLock(to);
System.out.println("Balance of Account "+from.name+" is "+from.balance());
System.out.println("Balance of Account "+to.name+" is "+to.balance());
// Let the thread sleep for a while.
Thread.sleep(50);

}
catch (InterruptedException e) {
System.out.println("Transaction " +  id + " interrupted.");
}
System.out.println("Transaction " +  id + " exiting.");
}


public void start ()
{
System.out.println("Starting Transaction " +  id );

while(!(from.lock==0 && to.lock==0));

if(t==null)
{
t = new Thread(this,this.id);
t.start ();

}

}
public class twophase
{
public static void main(String args[])
{
Account A=new Account("A",500,0);
Account B=new Account("B",800,0);
Account C=new Account("C",900,0);
Transaction T1 = new Transaction( "T-1",A,B,200);
T1.start();

Transaction T2 = new Transaction( "T-2",C,B,500);
T2.start();

Transaction T3 = new Transaction( "T-3",A,B,400);
T3.start();

}

*******************OUTPUT*********************
aiktc@aiktc17 ~ $ javac twophase.java
aiktc@aiktc17 ~ $ java twophase
Starting Transaction T-1
Starting Transaction T-2
Running TransactionT-1
Starting Transaction T-3
Transaction T-1 is completed
Running TransactionT-2
Balance of Account A is 300
Transaction T-2 is completed
Balance of Account C is 400
Balance of Account B is 1500
Balance of Account B is 1500
Running TransactionT-3
Transaction Cannot proceed : Not Enough Balance in AccountA