Slect button or select tag with hyper link or link to another page

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<form name=”link”>
<select name=”mylink” OnChange=”location.href=link.mylink.options[selectedIndex].value”>
<option selected>Please Select…
<option value=”ex.com”>Clients
<option value=”ex1.com”>Projects
<option value=”ex2.com”>Consultants
<option value=”ex3.com”>Timecard
</select>
</form>
</body>
</html>

C# notes for MCA 5th sem MCA VTU is available

C# notes for MCA 5th sem MCA VTU is available please mail me at gurugajanan.bhat@gmail.com, for notes in pdf format..

C# .NET Programs MCA 5th sem

.NET Lab Programs

1.Write a Program in C# to Check whether a number is Palindrome or not.
2. Write a Program in C# to demonstrate Command line arguments Processing.
3. Write a Program in C# to find the roots of Quadratic Equation.
4. Write a Program in C# to demonstrate boxing and unBoxing.
5. Write a Program in C# to implement Stack operations.
6. Write a program to demonstrate Operator overloading.
7. Write a Program in C# to find the second largest element in a single
dimensional array.
8. Write a Program in C# to multiply to matrices using Rectangular arrays.
9. Find the sum of all the elements present in a jagged array of 3 inner arrays.
10. Write a program to reverse a given string using C#.
11. Using Try, Catch and Finally blocks write a program in C# to demonstrate
error handling.
12. Design a simple calculator using Switch Statement in C#.
13. Demonstrate Use of Virtual and override key words in C# with a simple
program
14. Implement linked lists in C# using the existing collections name space.
15. Write a program to demonstrate abstract class and abstract methods in C#.
16. Write a program in C# to build a class which implements an interface which
is already existing.
17. Write a program to illustrate the use of different properties in C#.
18. Demonstrate arrays of interface types with a C# program.

1. Write a Program in C# to Check whether a number is Palindrome or not.
using System;
class Pallin
{
public static void Main(String[] args)
{
int d,n,rev,m;
Console.WriteLine(“Enter the number”);
n=int.Parse(Console.ReadLine());
m=n;
rev=0;
while(n!=0){
d=n%10;
rev=rev*10+d;
n=n/10;
}
if(rev==m){
Console.WriteLine(“Entered number “+m+” is pallindrom”);
}
else
{
Console.WriteLine(“Entered number “+m+” is not pallindrom”);
}
}
}

2. Write a Program in C# to demonstrate Command line arguments processing.

using System;
namespace ConsoleApplication1
{
class Commandline
{
static void Main(string[] args)
{
Console.Write(“WELCOME to “);
Console.Write(” ” + args[0]);
Console.Write(” ” + args[1]);
Console.ReadLine();
}
}
}

//another
using System;
class CommandLineArgs {
public static void Main(String[] args) {
double a,b;
if(args.Length==0) {
Console.WriteLine(“No arguments found”);
}
else {
a=double.Parse(args[0]);
b=double.Parse(args[1]);
double sum=0,mul=0,div=0,sub=0;
sum=a+b;
Console.WriteLine(“Sum of “+a+” and “+b+” is “+sum);
sub=a-b;
Console.WriteLine(” Substraction of “+b+” by “+a+” is “+sub);
mul=a*b;
Console.WriteLine(” Multiplication of “+a+” and “+b+” is “+mul);
div=a/b;
Console.WriteLine(” Division of “+a+” by “+b+” is “+div);
}
}
}

3. Write a Program in C# to find the roots of Quadratic Equation.

using System;
using System.Text;
namespace ConsoleApplication1
{
class QuadRK
{   static void Main(string[] args)
{  int a, b, c;
float d, x1, x2;
Console.WriteLine(“\n Enter a,b,c :\n”);
Console.Write(” a = “);
a = Convert.ToInt32(Console.ReadLine());
Console.Write(” b = “);
b = Convert.ToInt32(Console.ReadLine());
Console.Write(” c = “);
c = Convert.ToInt32(Console.ReadLine());
d = b * b – 4 * a * c;
if (d > 0)
{  Console.WriteLine(“\n Equation has two roots.”);
x1 = (float)(-b + Math.Sqrt(d)) / (2 * a);
x2 = (float)(-b – Math.Sqrt(d)) / (2 * a);
Console.WriteLine(“\n The roots are:\n”);
Console.WriteLine(“\n root1 = “+x1+”\n root2 = “+x2);
}
else if (d == 0)
{
Console.WriteLine(“\n Equation has only one root.”);
x1 = (float)-b / (2 * a);
Console.WriteLine(“\n The root is:\n”);
Console.WriteLine(“\n root = ” + x1);
}
else
{
Console.WriteLine(“\n Equation has imaginary roots.”);
x1 = (float)-b / (2 * a);
x2 = (float)Math.Sqrt(-d) / (2 * a);
Console.WriteLine(“\n The roots are:\n”);
Console.WriteLine(“\n root1 = ” + x1 + ” + ” + x2 + ” i \n” + ” root2 = ” + x1 + ” – ” + x2 + ” i “);
}
Console.ReadLine();
}   }   }

4. Write a Program in C# to demonstrate boxing and unBoxing.
using System;
class BoxUnbox {
public static void Main(){
int num;
Console.Write(“Enter the number : “);
num=int.Parse(Console.ReadLine());
Object o=num;
Console.WriteLine(“Value in num= “+num);
Console.WriteLine(“Value in Object 0=”+o);
int n;
n=(int)o;
Console.WriteLine(“Value of n=”+n);
}
}

5. Write a Program in C# to implement Stack operations.
using System;
class Stack
{
public static void Main(String[] args)
{
int top=-1,num,choice,max,rpt=1;
int[] stack=new int[20];
Console.WriteLine(“Enter the maximum limit”);
max=int.Parse(Console.ReadLine());
while(rpt!=0)
{
Console.WriteLine(“Stack Operation”);
Console.WriteLine(“1 . PUSH”);
Console.WriteLine(“2 . POP”);
Console.WriteLine(“3 . DISPLAY”);
Console.WriteLine(“0 . EXIT”);
Console.WriteLine(“Enter your choice:”);
choice=int.Parse(Console.ReadLine());
switch(choice)
{
case 1:
if(top==(max-1)) {
Console.WriteLine(“Stack is full”);
}
else {
Console.WriteLine(“Enter the element to be inserted:”);
num=int.Parse(Console.ReadLine());
stack[++top]=num;
Console.WriteLine(“Element is successfully inserted”);
}
break;
case 2:
if(top==-1)
{
Console.WriteLine(“Stack is Empty”);
}
else {
Console.WriteLine(“Deleted Element is :”+stack[top--]);
}
break;
case 3:
if(top==-1)
{
Console.WriteLine(“Stack is Empty”);
}
else {

Console.WriteLine(“Elements in the stack”);
for(int i=top;i>=0;i–)
{
Console.WriteLine(stack[i]);
}
}
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine(“Worng Entery”);
break;
}
}
}
}

6. Write a program to demonstrate Operator overloading.

using System;

public struct Complex
{
public int real;
public int imaginary;

public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return(String.Format(“{0} + {1}i”, real, imaginary));
}

public static void Main()
{
Complex num1 = new Complex(2,3);
Complex num2 = new Complex(3,4);

// Add two Complex objects (num1 and num2) through the
// overloaded plus operator:
Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString method:
Console.WriteLine(“First complex number:  {0}”,num1);
Console.WriteLine(“Second complex number: {0}”,num2);
Console.WriteLine(“The sum of the two numbers: {0}”,sum);

}
}

7. Write a Program in C# to find the second largest element in a single
dimensional array.
using System;
using System.Collections.Generic;
using System.Text;

namespace secondlargest
{
class Program
{
static void Main(string[] args)
{
int[] arr ={ 0, 5, 7, -2, 9, 12, 4, 8 };
int high, sechigh,temp;
high = sechigh = arr[0];
Console.WriteLine(“Array elements are”);
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i]+”  “);
Console.WriteLine();
for (int i = 0; i < arr.Length; i++)
{
temp = arr[i];
if (temp > high)
{
sechigh = high;
high = temp;
}
else if (temp > sechigh && temp != high)
sechigh = temp;
}
Console.WriteLine(“The second largest number in the array is  ” + sechigh);
Console.ReadLine();
}
}
}

8. Write a Program in C# to multiply to matrices using Rectangular arrays.
using System;
class matrixmul
{
public static void Main(String[] args)
{
int[,] a=new int [5,5];
int[,] b=new int [5,5];
int[,] c=new int [10,10];
int m,n,i,j,p,q,k;
Console.WriteLine(“Enter the order of first matrix”);
m=int.Parse(Console.ReadLine());
n=int.Parse(Console.ReadLine());
Console.WriteLine(“Enter the order of second matrix”);
p=int.Parse(Console.ReadLine());
q=int.Parse(Console.ReadLine());
if(n!=p)
Console.WriteLine(“not possible”);
else
{
Console.WriteLine(“enter array elements of fiorst matrix “);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i,j]=int.Parse(Console.ReadLine());

Console.WriteLine(“enter array elements of second matrix “);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i,j]=int.Parse(Console.ReadLine());

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i,j]=0;
for(k=0;k<n;k++)
c[i,j]=c[i,j]+a[i,k]*b[k,j];
}
}
Console.WriteLine(“\tResult of Multiplication”);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
Console.Write(“\t”+c[i,j]);
Console.WriteLine();
}
}
}
}

9. Find the sum of all the elements present in a jagged array of 3 inner arrays.
using System;
class MyjaggedArr
{
public static void Main()
{
int[][] myjag=new int[3][];

for(int i=0;i<myjag.Length;i++)
{
myjag[i]=new int[i+3];
}

for(int i=0;i<3;i++)
{
Console.WriteLine(“Enter the Elements of row{0}”,i);

for(int j=0;j<myjag[i].Length;j++)
{

myjag[i][j]=int.Parse(Console.ReadLine());
}
}
int sum=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<myjag[i].Length;j++)
{
sum+=myjag[i][j];
}
}
Console.WriteLine(“sum=”+sum);
}
}

10. Write a program to reverse a given string using C#.

using System;
using System.Text;

namespace ConsoleApplication1
{
class ReverseRK
{
static void Main(string[] args)
{
String inv;
String outv=””;
Console.WriteLine(” Enter a string :\n”);
inv=Console.ReadLine();
for(int i=inv.Length-1;i>=0;i–)
{
outv=outv+inv.Substring(i,1);
}
Console.WriteLine(“The reversed string is: “+outv);
Console.ReadLine();
}
}
}

11. Using Try, Catch and Finally blocks write a program in C# to demonstrate error      handling.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Exception
{
static int m = 10;
static int n = 0;
static void Division()
{
try
{
int k = m / n;
}
catch (ArgumentException e)
{
Console.WriteLine(“Exception caught:” + e.Message);
}
finally
{
Console.WriteLine(“Inside division method”);
Console.ReadLine();
}
}
static void Main(string[] args)
{
try
{
Division();
}
catch (DivideByZeroException e)
{
Console.WriteLine(“Exception caught:” + e.Message);
}
finally
{
Console.WriteLine(“inside main method”);
Console.ReadLine();
}
}
} }

12. Design a simple calculator using Switch Statement in C#.
using System;
class Simcalc {
public static void Main(String[] args)
{
double a,b,rpt=1;
int choice;
while(rpt!=0)
{
Console.WriteLine(“Select the operation”);
Console.WriteLine(“1 . Addition”);
Console.WriteLine(“2 . Subtraction”);
Console.WriteLine(“3 . Multiplication”);
Console.WriteLine(“4 . Division”);
Console.WriteLine(“0 . Exit”);
Console.WriteLine(“Enter ur choice :”);
choice=int.Parse(Console.ReadLine());
switch(choice)
{
case 1:
Console.WriteLine(“Enter two numbers:”);
a=double.Parse(Console.ReadLine());
b=double.Parse(Console.ReadLine());
Console.WriteLine(“Result of Addition : “+(a+b));
break;
case 2:
Console.WriteLine(“Enter two numbers:”);
a=double.Parse(Console.ReadLine());
b=double.Parse(Console.ReadLine());
Console.WriteLine(“Result of Subtraction : “+(a-b));
break;
case 3:
Console.WriteLine(“Enter two numbers:”);
a=double.Parse(Console.ReadLine());
b=double.Parse(Console.ReadLine());
Console.WriteLine(“Result of Multiplication : “+(a*b));
break;
case 4:
Console.WriteLine(“Enter two numbers:”);
a=double.Parse(Console.ReadLine());
b=double.Parse(Console.ReadLine());
if(b==0) {
Console.WriteLine(“Division not possible”);
}
else {
Console.WriteLine(“Result of Division : “+(a/b));
}
break;
case 0:
rpt=0;
break;
default:
Console.WriteLine(“Invalid selection”);
break;
}
}
}
}

13. Demonstrate Use of Virtual and override key words in C# with a simple program

using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
public class Customer
{
public virtual void CustomerType()
{
Console.WriteLine(“I am customer”);
}
}
public class CorporateCustomer:Customer
{
public override void CustomerType()
{
Console.WriteLine(“I am Corporate Customer”);
}
}
public class PersonalCustomer:Customer
{
public override void CustomerType()
{
Console.WriteLine(“I am personal customer”);
}
}
class Program
{
static void Main(string[] args)
{
Customer[] c=new Customer[3];
c[0]=new CorporateCustomer();
c[1]=new CorporateCustomer();
c[2]=new Customer();
foreach(Customer customerobject in c)
{
customerobject.CustomerType();
}
Console.ReadLine();
}
}
}

14. Implement linked lists in C# using the existing collections name space.
using System;
using System.Collections.Generic;
using System.Text;

class GenLinkedList
{
public static void Main()
{
Console.WriteLine(“\n**DEMONSTRATION OF LINKED LIST **\n”);
LinkedList<int> ll = new LinkedList<int>();
LinkedListNode<int> node;
int ch,x;
Console.WriteLine(“Initial number of elements:”+ ll.Count);
Console.WriteLine();
do
{
Console.WriteLine(“Linked List Operations\n”);
Console.WriteLine(“1. AddFirst\n2.AddLast\n3.RemoveFirst\n 4.RemoveLast\n5.RemoveSpecified\n6.Display\n7.Exit”);
Console.WriteLine();
Console.WriteLine(“Enter your choice”);
ch = int.Parse(Console.ReadLine());
switch (ch)
{
case 1:Console.WriteLine(“Enter the element toAddFirst”);
x = int.Parse(Console.ReadLine());
ll.AddFirst(x);
Console.WriteLine();
Console.WriteLine(“Number of elements:”+ll.Count);
break;
case 2:Console.WriteLine(“Enter the element to AddLast”);
x = int.Parse(Console.ReadLine());
ll.AddLast(x);
Console.WriteLine();
Console.WriteLine(“Number of elements:”+ll.Count);
break;
case 3:Console.WriteLine(“RemovedFirst element”);
ll.RemoveFirst();
Console.WriteLine();
Console.WriteLine(“Number of elements:”+ll.Count);
break;
case 4:Console.WriteLine(“RemovedLast element”);
ll.RemoveLast();
Console.WriteLine();
Console.WriteLine(“Number of elements:”+ll.Count);
break;

case 5:Console.WriteLine(“Enter the element to Remove”);
x = int.Parse(Console.ReadLine());
ll.Remove(x);
Console.WriteLine();
Console.WriteLine(“Number of elements:”+ll.Count);
break;
case 6:Console.WriteLine(“Number of elements:”+ll.Count);
Console.WriteLine(“Elements are :”);
for (node=ll.First;node != null;node=node.Next)
Console.Write(node.Value + ” “);
Console.WriteLine(“\n”);
break;
case 7:Environment.Exit(0);
break;
default:Console.WriteLine(“Invalid Choice”);
break;
}
Console.ReadLine();
} while(true);
}
}

15. Write a program to demonstrate abstract class and abstract methods in C#.

using System;

abstract class Test {
public int a;
public abstract void A();
}

class Derived1:Test {
public override void A() {
Console.WriteLine(“Derived1 A”);
base.a++;
Console.WriteLine(“a = {0}”,base.a);
}
}
class Derived2:Test {
public override void A() {
Console.WriteLine(“Derived2 A”);
base.a–;
Console.WriteLine(“a = {0}”,base.a);
}
}
class ProgramApp {
static void Main(String[] args) {
Test test1=new Derived1();
test1.A();
Test test2=new Derived2();
test2.A();
}
}

16. Write a program in C# to build a class which implements an interface which  is already existing.
using System;
namespace ConsoleApplication1
{
interface Addition
{
int Add();
}
interface Multiplication
{
int Multiply();
}
class Compute:Addition,Multiplication
{
int x, y;
public Compute(int a, int b)
{
this.x = a;
this.y = b;
}
public int Add()
{
return (x + y);
}
public int Multiply()
{
return (x * y);
}
}
class Interface
{
static void Main(string[] args)
{
int a, b;
Console.Write(“Enter 2 nos:”);
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
Compute ob1=new Compute(a,b);
Console.WriteLine(“Addition is:”+ob1.Add());
Console.WriteLine(“Multiplication is:”+ob1.Multiply());
Console.ReadLine();
}
}
}
17. Write a program to illustrate the use of different properties in C#.
using System;
class Point
{
int x,y;
public Point()
{
}
public Point(int x,int y) {
this.x=x;
this.y=y;
}
public int X
{
set {
this.x=value;
}
get {
return this.x;
}
}
public int Y
{
set {
this.y=value;
}
get {
return this.y;
}
}
}
class PrintApp {
public static void Main(String[] args)
{
Point p=new Point();
p.X=2;
p.Y=5;
Console.WriteLine(“x = “+p.X+” y = “+p.Y);
p.X++;
p.Y+=2;
Console.WriteLine(“After x++ and y+2″);
Console.WriteLine(“x = “+p.X+” y = “+p.Y);
}
}

18. Demonstrate arrays of interface types with a C# program.
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public static void FindMatches(IList<string>iList,object[] ob)
{
Console.WriteLine(“Match array is:”);
foreach(object o in ob)
{
Console.WriteLine(“{0}”,o.ToString());
}
foreach(object o in ob)
{  if(iList.Contains(o.ToString()))
Console.WriteLine(“\niList contains {0} at index{1}”,o,iList.IndexOf(o.ToString()));
}
}

static void Main(string[] args)
{
string[] strings ={ “one”, “two”, “four”, “eight” };
Console.WriteLine(“Strings array values:\n”);
foreach(String s in strings)
{
Console.WriteLine(“{0}”,s);
}
Console.WriteLine(“\n”);
FindMatches(strings,new String[]{“zero”,”one”,”five”,”eight”});
Console.ReadKey();

}
}}

//another
using System;
using System.Collections;
public class ArrayList1
{
public static void Main()
{
ArrayList MyAL=new ArrayList();
MyAL.Add(“hello”);
MyAL.Add(“world”);
MyAL.Add(“!”);
Console.WriteLine(“MY ARRRAY LIST”);
Console.WriteLine(“count {0}”,MyAL.Count);
Console.WriteLine(“values”);
printValues(MyAL);
}
public static void printValues(IList MyList)
{
foreach(Object o in MyList)
Console.WriteLine(“{0}”,o);
}
}

Many notes of MCA 5th semester is available

Dear beloveds,

I am having some resources of MCA 5th semester so i can not upload it here, so if you wish you can send me a text or mail to me. So i will surely respond to you as soon as possible..

my num: 8951210366 (pls call after 9.30pm) and my mail id: gurugajanan.bhat@gmail.com

(if any other MCA notes also if you want you can ask , but if i am having i will send it to you)

Thanks and regards
Gurugajanan Bhat

MCA 4th sem VTU Syllabus java Programs

1.a. Write a Java program to demonstrate constructor overloading and method overloading.

class ovr
{
int l,b;
ovr()
{
l=-1;
b=-1;
}
ovr(int x,int y)
{
l=x;
b=y;
}
ovr(int x)
{
l=x;
b=x;
}
int ar()
{
return(l*b);
}
void show(int a,int b)
{
System.out.println(“a+b= :” +(a+b));
}
void show(int a,double b)
{
System.out.println(“a+b :” +(a+b));
}
void show(double a,double b)
{
System.out.println(“a+b :” +(a+b));
}
}
class lab1a
{
public static void main(String args[])
{
int area;
ovr ob1=new ovr();
area=ob1.ar();
System.out.println(“area :” +area);
ovr ob2=new ovr(5,6);
area=ob2.ar();
System.out.println(“area :” +area);
ovr ob3=new ovr(10);
area=ob3.ar();
System.out.println(“area :” +area);
ob1.show(12,23);
ob1.show(4.5,7.8);
ob1.show(6.7,9.0);
}
}

OUTPUT:

Area 1
Area 30
Area 100
a+b=35
a+b=12.3
a+b=15.7

1.b. Write a Java program to implement Inner class and demonstrate its access protections.
class outer
{
int a[]=new int[10];
int sum=0,i,k=0;
void init()
{
for(i=0;i<10;i++)
{
a[i]=k;
k++;
}
}
void show()
{
inner ob=new inner();
ob.cal();
}
class inner
{
void cal()
{
for(i=0;i<10;i++)
sum+=a[i];
System.out.println("Array Elements");
for(i=0;i<10;i++)
System.out.print(" " +a[i]);
System.out.println("Sum :" +sum);
}
}
}
class lab1b
{
public static void main(String args[])
{
outer ob1=new outer();
ob1.init();
ob1.show();
}
}

OUTPUT:

0 1 2 3 4 5 6 7 8 9

Sum = 45

2a: Write a Java program to implement Inheritance.

class outer
{
int a,b;
outer(int x,int y)
{
a=x;
b=y;
}
void show()
{
System.out.println(“In Super Class”);
System.out.println(“a and b are : ” +a+” “+b);
}
}
class sub extends outer
{
int ans;
int add;
sub(int a,int b,int c)
{
super(a,b);
ans=c;
}
void show()
{
System.out.println(“In Sub class”);
System.out.println(“c :” +ans);
super.show();
add=a+b+ans;
System.out.println(“addition of a,b and ans is :”+add);
}
}
class lab2a
{
public static void main(String args[])
{
sub ob=new sub(4,5,6);
ob.show();
}
}

OUTPUT:

In Sub class
c=6

In super class
a=4 and b=5

Addition of a, b and c= 15

2b:Write a Java program to implement Exceptional handling (using nested try and catch)

class error
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=32/a;
System.out.println(“a :” +a);

try
{
if(a==1)
a=a/(a-a);

if(a==2)
{
int c[]={1};
c[10]=90;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index out of bounds ” +e);
}
}
catch(ArithmeticException e)
{
System.out.println(“Divide by zero :” +e);
}
}
}

OUTPUT:
C :\> java error
Divide by zero

C:\>java error 1 2
Array index out of bounds

3a:Write a Java program to create a interface and implement it in a class.

interface grade
{
final int fail=40;
final int fist=60;
final int dist=75;
void show();
}
class cinfo
{
int rno;
String name,course;
cinfo(int x,String y,String z)
{
rno=x;
name=y;
course=z;
}
}
class test extends cinfo implements grade
{
int s1,s2,s3;
test(int a,String b,String c,int d,int e,int f)
{
super(a,b,c);
s1=d;
s2=e;
s3=f;
}
public void show()
{
int tot;
tot=s1+s2+s3;
System.out.println (“Name:” +name);
System.out.println(“Rno :” +rno);
System.out.println (“Sub1: ” +s1 +”Sub2 “+s2 +” Sub3 :” +s3);
System.out.println (“total:” +tot);
if (tot40 && tot<60)
System.out.println("grade First CLass");
else
System.out.println("grade Distinction");
}
}
class lab3a
{
public static void main(String args[])
{
test ob=new test(12,"Guru","mca",50,60,70);
ob.show();
}
}

OUTPUT:

Name:Guru

Rollno: 12

Subject1:50

Subject2:60

Subject3:70

Total: 180

Grade: distinction

3.b. Write a JAVA program to create a class(extending Thread) and use methods Thread class to change name,priority,of the current Thread and display the name.

class A extends Thread
{
public void run()
{
try
{
Thread t=Thread.currentThread();
System.out.println(“The thread one name and priority:”+t);
for(int i=1;i<5;i++)
{
System .out.println("thread done:"+i);
Thread.sleep(500);
}
}catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("Exiting thread is done");
}
}

class lab3b
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("current thread details are:"+t);
t.setName("mythread");
t.setPriority(4);
System.out.println("The change in thread name and priority:"+t);
System.out.println("The priority is="+t.getPriority());
System.out.println("The name is:"+t.getName());
try
{
Thread.sleep(3000);
}catch(InterruptedException e)
{
System.out.println("Main");
}
A ThreadA=new A();
ThreadA.setName("Thread one");
ThreadA.setPriority(6);
System.out.println("Start the thread one");
ThreadA.start();
System.out.println("Enter main thread");
}
}

OUTPUT:

E:\4th sem\JAVA lab>javac lab3b.java
E:\4th sem\JAVA lab>java lab3b
current thread details are:Thread[main,5,main]
The change in thread name and priority is:Thread[mythread,4,main]
The priority is=4
The name is:mythread
Start the thread one
Enter main thread
The thread one name and priority is:Thread[Thread one,6,main]
thread done:1
thread done:2
thread done:3
thread done:4
Exiting thread is done

4a:Write a Java program to create a scrolling text using java applets

import java.awt.*;
import java.applet.*;
/*

*/
public class banner extends Applet implements Runnable
{
String msg=”PES-Institute of technology”;
Thread t=null;
int state;
boolean flag;
public void init()
{
setBackground(Color.green);
}
public void start()
{
t=new Thread(this);
flag=false;
t.start();
}
public void run()
{
char ch;
for(; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(flag)
break;
}
catch(InterruptedException e){}
}
}
public void stop()
{
flag=true;
t=null;
}
public void paint(Graphics g)
{
g.drawString(msg,50,60);
}
}

//Output is displayed in separate window

4b: Write a Java program to pass parameters to applets and display the same.

import java.awt.*;
import java.applet.*;
/*

*/
public class stdpar extends Applet
{
String s1,s2,s3,s4,s5,res;
int t1,t2,t3;

public void init()
{
s1=getParameter(“name”);
s2=getParameter(“rollno”);
s3=getParameter(“sub1″);
s4=getParameter(“sub2″);
s5=getParameter(“sub3″);
t1=Integer.parseInt(s3);
t2=Integer.parseInt(s4);
t3=Integer.parseInt(s5);
setBackground(Color.green);
}

public void paint(Graphics g)
{
if(t1<40||t2<40||t3<40)
res="fail";
else
res="pass";
g.drawString(s1,20,30);
g.drawString(s2,50,30);
g.drawString(s3,40,45);
g.drawString(s4,50,56);
g.drawString(s5,60,65);
g.drawString(res,80,90);
}
}

6: Write a JAVA Program to implement Client Server (Client requests a file, Server responds to client with contents of that file which is then display on the screen by Client – Socket Programming).

//client
import java.net.*;
import java.io.*;
public class client
{
public static void main(String args[])throws IOException
{
BufferedReader in=null;
OutputStream os;
Socket cs=null;
try
{
cs=new Socket(InetAddress.getLocalHost(),555);
in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
}
catch(Exception e)
{
System.out.println(“do not know about the host”);
System.exit(1);
}
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“enter the file to be opened”);
String s=stdin.readLine();
os=cs.getOutputStream();
byte bt[]=s.getBytes();
os.write(bt);
String UserInput;
try
{
System.out.println(in.readLine());
while((UserInput=in.readLine())!=null)
{
System.out.println();
System.out.println(UserInput);
}
}
catch(Exception e)
{
System.err.println(“Socket Exception”);
System.exit(1);
}
in.close();
cs.close();
}
}

//server

import java.net.*;
import java.io.*;
public class server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
String inputline,outputline;
inputline=new String();
InputStream is;
byte bt[]=new byte[20];
try{
ss=new ServerSocket(555);
}
catch(IOException io)
{
System.out.println(“could not listen”);
System.exit(1);
}
Socket cs=null;
try
{
cs=ss.accept();
is=cs.getInputStream();
is.read(bt);
inputline=new String(bt);
System.out.println(“connected to …..”+cs.toString());
System.out.println(inputline);
}
catch(IOException io)
{
System.out.println(“Accept failed”);
System.exit(1);
}
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
BufferedReader Stdin=new BufferedReader(new InputStreamReader(System.in));
File f=new File(inputline);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(inputline));
String line;
while((line=d.readLine())!=null)
{
if(f.exists())
{
while((line=d.readLine())!=null)
{
out.write(line);
out.flush();
}
d.close();
}
cs.close();
ss.close();
}
}
}
}

OUTPUT:-

C:\Java\jdk1.5.0_04\bin>javac server.java
C:\Java\jdk1.5.0_04\bin>javac client.java

C:\Java\jdk1.5.0_04\bin>java server
connected to …..Socket[addr=/192.168.10.164,port=1132,localport=555]
boxdemo.java
Exception in thread “main” java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:97)
at java.io.BufferedReader.readLine(BufferedReader.java:293)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at server.main(server.java:43)

C:\Java\jdk1.5.0_04\bin>java client
enter the file to be opened
boxdemo.java
{double width,height,depth;}class boxdemo{public static void main(String args[])
{double vol;box mybox= new box();mybox.width=10;mybox.height=20;mybox.depth=30;S
ystem.out.println(“hiiiiiiiiii\n”);vol=mybox.width*mybox.height*mybox.depth;Syst
em.out.println(“the volume is :”+vol);}}

7. PROGRAM NAME: Write a JAVA Program to implement a simple Client Server Application using RMI.

//HelloInterface.java

import java.rmi.*;
import java.rmi.server.*;

public interface HelloInterface extends Remote
{
public String getMessage()throws RemoteException;
public void display()throws RemoteException;
}

//HelloServer.java

import java.rmi.*;
import java.rmi.server.*;

public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
public HelloServer() throws RemoteException
{
}
public String getMessage() throws RemoteException
{
return “Welcome To Guru”;
}
public void display() throws RemoteException
{
System.out.println(“Hello, Whats up?”);
}
public static void main(String arg[])
{
try
{
HelloServer Server = new HelloServer();
Naming.rebind(“rmi://localhost:1099/Server”,Server);
}
catch(Exception e)
{
}
}
}

//HelloClient.java

import java.rmi.*;
public class HelloClient
{
public static void main(String args[])
{
try
{
HelloInterface
Server=(HelloInterface)Naming.lookup(“rmi://localhost:1099/Server”);
String msg=Server.getMessage();
System.out.println(msg);
Server.display();
}
catch(Exception e){}
}
}

OUTPUT:

C:\java\bin>javac HelloInterface.java
C:\java\bin>javac HelloServerImpl.java
C:\java\bin>javac HelloClient.java
C:\java\bin>rmic HelloServerImpl
C:\java\bin>start rmiregistery //opens a new window
C:\java\bin>java HelloServerImpl //run in the new window
C:\java\bin>java HelloClient //run in the new window
Welcome to Guru

8.Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and password should be accepted using HTML and displayed using a Servlet).
************************************************************************

Html file:


Welcome to login page


User name:

Password:

   

Create web.xml file and write this code

servlet1
myservlet

servlet1
/serv1

Java program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class myservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
String uname,pass;
uname=req.getParameter(“txtname”);
pass=req.getParameter(“txtpass”);
res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
out.println(“\n\n”
+”\n”
+”




+”you have been Successfully!!!logged in

+”User name is : “+uname+”
“+”Password is:”+pass+”


+”


\n”);
}
}

YACC programs ( VTU syllabus)

1.Program to test the validity of a simple expression involving operators +,-,* and /.

Lex Specification

…………………………………..

%{

#include “y.tab.h”

%}

%%

[_a-zA-Z][_a-zA-Z0-9]* return ID;

[0-9]+
return NUM;
. return yytext[0];

\n return 0;

%%

………………………………….

Yacc Specification

%{

#include

%}

%token NUM ID

%left ‘+’ ‘-‘

%left ‘*’ ‘/’

%nonassoc UMINUS

%%

exp: exp ‘+’ exp

| exp ‘-‘ exp

| exp ‘/’ exp

| exp ‘*’ exp

| ‘-‘ exp %prec UMINUS

| ‘(‘ exp ‘)’

| NUM

| ID

;

%%

int main()

{

printf(“\n Enter an expression:”);

yyparse();

printf(“\n valid expression”);

return 0;

}

void yyerror(){

printf(“\n Invalid expression”);

exit(0);

}

Output:

…………………………………………..

lex l1.l

yacc -d y1.y

cc lex.yy.c y.tab.c -ll

./a.out

Enter an expression:a+(b-c)/a

valid expression

………………………………………………………………………………………………………….

2.Program to recognise the nested IF control statements and display the number of levels of nesting.

Lex Specification

WS [ \t]*

%{

#include “y.tab.h”

%}

%%

{WS}”if”{WS} {return IF;}

[-+_A-Za-z0-9!=><]+ {return STMT;}

. {return yytext[0];}

\n {return 0;}

%%

…………………………….

Yacc specification

%{

#include

int nlevel=0;

%}

%token IF STMT

%%

start:ifs{printf(“\n valid statement\n”);}

ifs:IF cond st{nlevel++;}

;

st:simpst

|”{“compst”}”

|ifs

;

simpst:STMT”;”

|”;”

;

compst:simpst compst

|ifs compst

|simpst

|ifs

;

cond:”(“STMT”)”

;

%%

int main()

{ printf(“\n enter an expression\n”);

yyparse();

printf(“\n number of levels of nesting=%d\n”,nlevel);

return 0;

}

void yyerror()

{ printf(“\n invalid”);

exit(0);

}

…………………………………..

Output:

lex lfile2.l

yacc -d yfile2.y

cc lex.yy.c y.tab.c -ll

./a.out

enter an expression

if(a==b)a=0;

valid statement

………………………………………………………………………………………………………………..

3.Program to recognize valid arithmatic expression that uses operators+,-,*and /.

Lex Specification

…………………………….

%{

#include “y.tab.h”

%}

%%

([0-9]+|[0-9]*\.[0-9]+) return NUM;
. return yytext[0];

\n return 0;

%%

Yacc Specification

…………………..

%{

#include

%}

%token NUM

%left ‘+’ ‘-‘

%left ‘*’ ‘/’

%nonassoc UMINUS

%%

exp : exp ‘+’ exp

| exp ‘-‘ exp

| exp ‘/’ exp

| ‘-‘ exp %prec UMINUS

| exp ‘*’ exp

| ‘(‘ exp ‘)’

| NUM

;

%%

int main()

{

printf(“\n Enter an arithmatic expression”);

yyparse();

printf(“\n Valid expression”);

return 0;

}

void yyerror(){

printf(“\n Invalid expression”);

return 0;

}

void yyerror(){

printf(“\n Invalid expression”);

exit(0);

}

………………………………….

Output

lex l3.l

yacc -d y3.y

cc lex.yy.c y.tab.c -ll

./a.out

Enter an arithmatic expression1+3*4

Valid expression

………………………………………………………………………………….

4. Program to recognize a valid variable.

Lex Specification

……………………….

%{

#include “y.tab.h”

%}

%%

[a-z][-a-zA-Z0-9]* {return VAR;}

. return yytext[0];

\n return 0;

%%

Yacc Specification

…………………………….

%{

#include

%}

%token VAR

%%

start:VAR

|

;

%%

int main()

{ printf(“\n enter a variable\n”);

yyparse();

printf(“\n valid variable”);

return 0;

}

void yyerror()

{ printf(“\n invalid variable”);

exit(0);

}

Output:

lex lfile4.l

yacc -d yfile4.y

cc lex.yy.c y.tab.c -ll

./a.out

Enter a variable

cn12

valid variable

……………………………………………

5.Evaluate the arithmatic expression +,-,*,/

Lex Specification

…………………………..

%{

#include “y.tab.h”

%}

%%

([0-9]+|[0-9]*\.[0-9]+)+ {yylval.fval=atof(yytext);return NUM;}

. return yytext[0];

\n return 0;

%%

Yacc Specification

…………………………….

%{

#include

%}

%union {float fval;}

%token NUM

%type e

%type start

%left’+”-‘

%left’*”/’

%nonassoc UMINUS

%%

start:e{printf(“=%2.2f”,$$);}

;

e:e’+’e{$$=$1+$3;}

|e’-‘e{$$=$1-$3;}

|e’*’e{$$=$1*$3;}

|e’/’e{if($3==0)

yyerror(“diveded by zero”);

else

$$=$1/$3;

}

|’-‘e %prec UMINUS{$$=-$2;}

|'(‘e’)'{$$=$2;}

|NUM{$$=$1;}

;

%%

int main()

{

printf(“\n enter aritmetic expression\n”);

yyparse();

printf(“\n valid expression\n”);

return 0;

}

void yyerror()

{ printf(“\n invalid expression\n”);

exit(0);

}

…………………………………

Output:

lex lfile5.l

yacc -d yfile.y

cc lex.yy.c y.tab.c -ll

./a.out

Enter aritmetic expression

1+5*4

=21.00

valid expression

……………………………………………………………………………………..

6. Program to recognize the string ‘abbb’,’ab’,’a’ using grammer (a^nb^n,n>=0).

Lex Specification

……………………

%{

#include “y.tab.h”

%}

%%

a return A;

b return B;

. return yytext[0];

\n return 0;

%%

yacc Specification

………………………..

%{

#include

%}

%token A B

%%

start:sa sb

|sa

|sb

;

sa: A sa

| A

;

sb: B sb

|B

;

%%

int main()

{

printf(“\n enter a string of A’s followed by B\n”);

printf(“for the following grammer a^nb^n,n,m>=0\n”);

yyparse();

printf(“valid input\n”);

return 0;

}

void yyerror()

{ printf(“\n invalid input\n”);

exit(0);

}

Output:

……………………….

lex lfile6.l

yacc -d yfile6.y

cc lex.yy.c y.tab.c -ll

./a.out

enter a string of A’s followed by B

for the following grammer a^nb^n,n,m>=0

aabbb

valid input

…………………………………………………………………………………..

7. Program to recognize the grammer(a^b,n>=10).

Lex Specification

…………………………….

%{

#include “y.tab.h”

%}

%%

a return A;

b return B;

. return yytext[0];

\n return 0;

%%

Yacc Specification

…………………

%{

#include

%}

%token A B

%%

start:tena next

;

next: A next

| B

;

tena:A A A A A A A A A A

;

%%

int main()

{

printf(“\n enter a string of A’s followed by B\n”);

printf(“for the following grammer a^nb,n>=10\n”);

yyparse();

printf(“valid input\n”);

return 0;

}

void yyerror()

{ printf(“\n invalid input\n”);

exit(0);

}

Output:

………………

lex lfile7.l

yacc -d yfile7.y

cc lex.yy.c y.tab.c -ll

./a.out

enter a string of A’s followed by B

for the following grammer a^nb,n>=10

aaaaaaaaaaaab

valid input

MCA 2nd sem unix lab programs

1.a. A shell script for non-recursive, which accepts any number of arguments and prints them in the reverse order(for example, if script is named rags, then executing rags A B C should produce C B A on the standard output).

if [ $# -eq 0 ] ; then
echo “argument not found”
exit
else
i=`echo $*|wc -w`
while [ $i -gt 0 ] ; do
s=`echo $*|cut -d ” ” -f $i`
temp=`echo $temp $s`
i=`expr $i – 1`
done
echo “Reversed list : $temp”
fi

OUTPUT:

sh 1a.sh a b c
Reversed list : c b a

1.b. A shell script that accepts two file name as arguments, checks if the permission for these files are identical and if the permissions are identical, output common permissions otherwise output each file name followed by its permissions.

if [ $# -eq 0 ] ; then
echo “No arguments”
exit
elif [ $# -lt 2 ] ; then
echo “Only one arguments”
exit
else
f1=`ls -l $1|cut -c ‘2-10’`
f2=`ls -l $2|cut -c ‘2-10’`
if [ "$f1" == "$f2" ] ; then
echo “File permission are identical”
else
echo “File permission are not identical”
echo “The permission of first file is f1:$f1″
echo “The permission of the second file is f2:$f2″
fi
fi

OUTPUT:

sh 1b.sh 1a.sh bhu.sh
File permission are not identical
The permission of first file is f1:rw-rw-r–
The permission of the second file is f2:rwxrw-r–


2.a. A shell script that takes a valid directory name as an argument and recursively descend all the sub directories, finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output.

echo “Enter Directory name”
read dir
if [ ! -d $dir ] ; then
echo “Invalid directory”
exit
fi
large=0
for file in `find $dir -type f`
do
size=`stat -c %s $file`
echo “size of $file is $large”
if [ $size -gt $large ] ; then
large=$size
fi
done
echo ” File with Maximum size is $large”

OUTPUT:

sh 2a.sh
Enter Directory name
singh
size of singh/1b.sh is 593
size of singh/bhupal is 618
size of singh/bhu.sh is 618
size of singh/1a.sh is 618
File with Maximum size is 618

2.b. A shell script that accepts a path name and creates all the components in that path name as directories. For example, if the script is named mpc, than the command mpc a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.

temp=$IFS
IFS=/
for i in $*
do
if [ -d $i ] ; then
cd $i
else
mkdir $i
cd $i
fi
done
IFS=$temp

OUTPUT:

sh 2.sh a b c d
cd a
ls
b
cd b
ls
c
cd c
ls
d


3.a. A shell script that accepts valid login-in names as arguments and prints there corresponding home directories, if no arguments are specified, print a suitable error message.

if [ $# -eq 0 ] ; then
echo “No arguments”
else
for name in $*
do
if grep $name /etc/passwd >/dev/null
then
echo “Login name:$name”
hdir=`grep $name /etc/passwd | cut -d”:” -f6`
echo “Home Directory :$hdir”
else
echo “$name is not valid Login name”
fi
done
fi

OUTPUT:

sh 3a.sh
No arguments

sh 3a.sh abc
abc is not valid Login name

sh 3a.sh root
Login name:root
Home Directory :/home/root


3.b. A shell script to implement terminal locking (similar to the lock command). It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if match occurs, it must lock the keyboard until a matching password is entered again by the user, note that the script must be return to disregard BREAK, control –D. no time limit need be implemented for the lock duration.

stty -echo
echo “Enter password”
read pass1
echo “Confirm password”
read pass2
if [ "$pass1" = "$pass2" ] ; then
echo “Terminal is locked”
trap ”1 2 15
while true ; do
echo ” Enter password”
read pass3
if [ "$pass3" = "$pass2" ]; then
echo “Terminal Unlocked”
stty echo
exit
else
echo “Try again”
fi
done
else
echo “password do not match”
stty echo
fi

OUTPUT:
sh 3b.sh
Enter password
Confirm password
Terminal is locked
Enter password
Try again
Enter password
Terminal Unlocked

4.a. Creating a script file called file-properties that reads a file name entered and outputs it properties.

echo “Enter a file name”
read file
if [ ! -e $file ] ; then
echo “File does not exit”
exit
else
ftype=`ls -l $file|cut -c 1`
fper=`ls -l $file|cut -c 2-10`
fowner=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f3`
fsize=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f5`
fdate=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f6`
ftime=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f7`
fname=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f8`

fi
echo “The file type is : $ftype”
echo “The file permission is : $fper”
echo “The file owner is : $fowner”
echo “The file size is : $fsize”
echo “The file date is : $fdate”
echo “The file time is : $ftime”
echo “The file name is : $fname”

OUTPUT:

sh 4a.sh
Enter a file name
2.sh
The file type is : -
The file permission is : rw-rw-r–
The file owner is : root
The file size is : 104
The file date is : 2009-04-30
The file time is : 02:31
The file name is : 2.sh

4.b. A shell script that accept one or more file names as arguments and convert all of them to upper case, provided they exist in current directory.

if [ $# -eq 0 ] ; then
echo “No Arguments”
exit
else
for file in $*
do
if [ -e $file ] ; then
fname=`echo $file|tr ‘[a-z]‘ ‘[A-Z]‘`
echo “The $file is converted to $fname “
else
echo “The directory $file does not exit”
fi
done
fi

OUTPUT:

sh 4b.sh dirname
The bhupal is converted to DIRNAME

sh 4b.sh abc
The directory abc does not exit

5.a. A shell script that displays all the links to a file specified as the first argument to the script. The second argument , which is optional, can be used to specify in which the search is to begin, if this second argument is not present, the search is to begin in current working directory. In either case, the starting directory as well as all its subdirectories at all levels must be searched. The script need not include any error checking.

if [ $# -eq 0 ] ; then
echo “No arguments”
exit
fi
if [ $# -eq 2 ] ; then
dir=$2
else
dir=`pwd`
fi
inode=`stat -c %i $1`
count=0
for link in `find $dir -inum $inode`
do
echo $link
count=`expr $count + 1`
done
if [ $count -eq 0 ] ; then
echo “$1 has no link in the directory $dir”
else
echo “$1 has $count links in the directory $dir”
fi

OUTPUT:

sh 5a.sh hi
/home/root/hi
hi has 2 links in the directory /home/root

5.b. A shell script that accepts as file-name as argument and display its creation time if file exist and if it does not send output error message.

if [ $# -eq 0 ] ; then
echo “No Arguments”
else
for file in $*
do
if [ -f $file ] ; then
fdate=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f6`
ftime=`ls -l $file|tr -s ‘ ‘|cut -d ” ” -f7`
else
echo “$file does not exit”
fi
done
fi
echo “File modified on $fdate at $ftime”

OUTPUT:

sh 5b.sh 2.sh
File modified on 2009-04-30 at 02:31

6.a. A shell script to display the calendar for the current month with current date
Replace by * or ** depending on whether the date has one digit or two digits.

dt=`date +%d`
cal > f3.lst
if [ $dt -lt 10 ] ; then
dt=`echo $dt|cut -c 2`
ln=`sed -n ‘3,$p’ f3.lst | nl | grep “$dt” | head -1 | cut -f1`
ln=`expr $ln + 2`
sed $ln’s/’$dt’/*/’ f3.lst
else
sed ‘s/’$dt’/**/’ f3.lst
fi

OUTPUT:

sh 6a.sh
May 2009
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 **
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

sh 6a.sh
May 2009
Su Mo Tu We Th Fr Sa
* 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

6.b. A shell script to find smallest of three numbers that are read from keyboard.

echo “Enter the three numbers”
read a b c
if [ $a -lt $b -a $a -lt $c ] ; then
echo “$a is sma llest”
elif [ $b -lt $c ] ; then
echo “$b is smallest”
else
echo “$c is smallest”
fi

OUTPUT:

sh 6b.sh
Enter the three numbers
5 12 3
3 is smallest

sh 6b.sh
Enter the three numbers
1 2 3
1 is sma llest

sh 6b.sh
Enter the three numbers
10 6 20
6 is smallest

7.a. A shell script using expr command to read in a string and display a suitable message if it does not have at least 10 characters.

echo “Enter the string”
read str
if [ -z str ] ; then
echo “null character”
else
len=`expr “$str” : ‘.*’`
if [ $len -ge 10 ] ; then
echo “$str has $len character”
else
echo “$str has less than 10 character”
fi
fi

OUTPUT:

sh 7a.sh
Enter the string
nittemeenakshi
nittemeenakshi has 14 character

sh 7a.sh
Enter the string
hello
hello has less than 10 character

7.b. A shell script to compute the sum of number passed to it has argument on command line and display the result.

echo “To compute the sum”
num=$1
sum=0
while [ $num -gt 0 ] ; do
rem=`expr $num % 10`
num=`expr $num / 10`
sum=`expr $rem + $sum`
done
echo “The result is $sum”

OUTPUT:

sh 7b.sh 245
To compute the sum
The result is 11

sh 7b.sh 123
To compute the sum
The result is 6

8.a. A shell script that compute gross-salary for an employee, according to the rule given below.
If basic salary is = 15000 than HRA=500 of basic and DA=98% of basic.

echo “Enter the basic salary”
read basic
if [ $basic -lt 15000 ] ; then
hra=`expr $basic \* 10 / 100`
da=`expr $basic \* 90 / 100`
else
hra=`expr $basic \* 50 / 100`
da=`expr $basic \* 98 / 100`
fi
gross=`expr $basic + $hra + $da`
echo “Gross salary is $gross”

OUTPUT:

sh 8a.sh
Enter the basic salary
23456
Gross salary is 58170

sh 8a.sh
Enter the basic salary
1234
Gross salary is 2467

8.b. A shell script that delete all lines containing a specific word in one or more file supplied as argument to it.

if [ $# -eq 0 ] ; then
echo “No arguments”
else
pattern=$1
shift
for fname in $*
do
if [ -f $fname ] ; then
echo “Deleting $pattern from $file”
sed ‘/’$pattern’/d’ $fname
else
echo “$fname not found”
fi
done
fi

OUTPUT:

cat > hello
hi this is singh here
studying in nmit college

sh 8b.sh singh hello
Deleting singh from
studying in nmit college


9.a. A shell script that gets executed displace the message either “Good Morning ” or “Good Afternoon” or “Good Evening” depending upon time at which the user logs-in.

time=`who am I | tr -s ‘ ‘ | cut -d ” ” -f 4 | cut -c 1,2`
if [ $time -le 12 ] ; then
echo “Good Morning $LOGNAME”
elif [ $time -gt 12 -a $time -lt 16 ] ; then
echo “Good Afternoon $LOGNAME”
else
echo “Good Evenini $LOGNAME”
fi

OUTPUT:

sh 9a.sh
Good Morning root

sh 9a.sh
Good Afternoon root

9.b. A shell script that accept a list of file names as its arguments, count and report occurrence of each word that is present in the first argument file on other argument files.

if [ $# -eq 0 ] ; then
echo “No Arguments”
elif [ $# -eq 1 ] ; then
echo “Only one Arguments”
else
pat=$1
if [ ! -e $1 ] ; then
echo “$1 does not exist”
exit
fi
shift
for file in $*
do
if [ -e $fie ] ; then
echo $file
for pattern in `cat $pat`
do
echo “$pattern occurs `grep -c “$pattern” $file` times”
done
else
echo “$file does not exist”
fi
done
fi

OUTPUT:
sh 9b.sh hello hi
hi
hi occurs 1 times
this occurs 1 times
is occurs 1 times
singh occurs 1 times
here occurs 0 times
studying occurs 1 times
in occurs 2 times
nmit occurs 0 times

if [ $# -eq 0 ] ; then
echo “No Arguments”
exit
fi
if who | grep “$1″ ; then
uhtime=`who | grep $1 tr -s ‘ ‘ | cut -d ” ” -f4 | cut -c 1,2`
umtime=`who | grep $1 tr -s ‘ ‘ | cut -d ” ” -f4 | cut -c 4,5`
hh=`$uhtime | cut -d ” ” -f1`
mm=`$umtime | cut -d ” ” -f1`
shtime=`date +%H`
smtime=`date +%M`
timeh=`expr $shtime – $hh`
timem=`expr $smtime – $mm`

echo “System time is $shtime hr and $smtime min”
echo “Time in which is working $timeh hr and $timem min”
else
echo “No Valid login name”
fi

10.b. A shell script that reports the logging in of a specified user with in one minute after he/she login. The script automatically terminates if specified user does not login during a specified period of time.

interval=5
name=$1
who | awk ‘{printf $1}’ | grep “$name” > /dev/null
if test $? = 0 ; then
loggedin=true
echo “$name logged in”
else
loggedin=false
echo “$name not logged in”
fi
sleep $interval
while true ; do
who | awk ‘{printf $1}’ | grep “$name” > /dev/null
if test $? = 0 ; then
if loggedin=false ; then
loggedin=true
echo “$name logged in”
exit
fi
else
if loggedin=true ; then
loggedin=false
echo “$name not logged in”
exit
fi
fi
done

OUTPUT:

sh 10b.sh root
root logged in

root logged in


11.a. A shell script that accepts two integers as its arguments and compute the value of first number raised to the power of second number.

x=$1
y=$2
z=$x
i=1
if [ $# -eq 0 ] ; then
echo “No Arguments”
else
while [ $i -lt $y ] ; do
z=`expr $z \* $x`
i=`expr $i + 1`
done
echo “Value of 1st number raised to the power of 2nd number : $z”
fi

OUTPUT:

sh 11a.sh 3 4
Value of 1st number raised to the power of 2nd number : 81

11.b. A shell script that accept the file name, starting and ending line number as an argument and display all the lines between the given line number.

if [ $# -eq 0 ] ; then
echo “No argument”
elif [ $# -eq 1 ] ; then
echo “Only one argument”
elif [ $# -eq 2 ] ; then
echo “only two argument”
else
if [ ! -e $1 ] ; then
echo “File does not exist”
else
sed -n ”$2′,’$3’p’ $1
fi
fi

OUTPUT:

sh 11b.sh 11a.sh 3 6
z=$x
i=1
if [ $# -eq 0 ] ; then
echo “No Arguments”

sh 11b.sh 11a.sh 3 5
z=$x
i=1
if [ $# -eq 0 ] ; then

12.aWrite a shell script that folds long lines into 40 columns. Thus any line that exceeds 40 characters must be broken after 40th, a “\” is to be appended as the indication of folding and the processing is to be continued with the residue. The input is to be supplied through a text file created by the user
BEGIN {
printf”Begin of a file”;
}
{
x1=length($0);
if(x1 text.txt

after tracing the process of establishment and growth of operational research
we consider it has source of other new science literally the
word operation may be defined as some action that we applied to some problem.

awk -f 12a.awk text.txt
Begin of a file

after tracing the process of establishme \
nt and growth of operational research
we consider it has source of other new s \
cience literally the
word operation may be defined as some ac \
tion that we applied to some problem.End of file


12.b Write an awk script that accepts date argument in the form of mm-dd-yy and displays it in the form if day, month, and year. The script should check the validity of the argument and in case of error, display a suitable message.

clear
BEGIN { printf “date validation” }

{
if ( ( $1==2 && $2>29 ) || ( $2 > 31 ) || ( $1==4 || $1==6 || $1==9 || $1==11 && $2>30 )
|| ( $3%4!=0 && $1==2 && $2>28 )||($1 > 12) )
printf “invalid date”
else
printf “\n%d:%d:%d\n”,$2,$1,$3
}
END {“date conversion”}

OUTPUT:

awk -f san12b.awk
date validation14 17 09
invalid date

awk -f san12b.awk
date validation12 18 09

18:12:9


13.a Write an awk script to delete duplicated line from a text file. The order of the original lines must remain unchanged.

clear
BEGIN { printf “script to delete duplicate line ” }
{ a[n++]=$0 }
END {
for(i=0;i<n;i++)
{
flag=0
for(j=0;j aaa
bhu
singh
anand
bhu

awk -f san13a.awk aaa
script to delete duplicate line bhu

13 .b .Write an awk script to find out total number of books sold in each discipline as well as total book sold using associate array down table as given below.
i. Electrical 34 ii. Mechanical 67 iii. Electrical 80
iv. Computer Science 43 v. Mechanical 65 vi. Civil 198
vii. Computer Science 64

BEGIN { printf “total no. of book sold in each category” }
{ books[$1]+=$2 }
END { for(item in books)
{ printf(“\n\t%-17s%1s%-5d”,item,”=”,books[item])
total+=books[item]
}
printf(“%-17s%1s%-5d\n”,”total books sold”,”=”,total)
}

OUTPUT:

cat >book.txt
mechanical 67
electrical 34
electrical 80
computers 43
mechanical 65
civil 198
computers 64

awk -f san13b.awk book.txt
total no. of book sold in each category
computer =107
electrical =114
civil =198
mechanical =132 total books sold =551

14. Write an awk script to compute gross salary of an employee accordingly to the rule given below:
If basic salary = 10,000 then HRA=20% of basic and DA=50% of basic.

BEGIN { printf “enter the basic pay: Rs”
getline bp <"/dev/tty"
if(bp<10000)
{
hra=.15*bp
da=.45*bp
}
else
{
hra=.2*bp
da=.5*bp
}
gs=bp + hra + da
printf "gross salary = Rs. %.2f\n",gs
}

OUTPUT:

awk -f san14.awk
enter the basic pay: Rs7000
gross salary = Rs. 11200.00

awk -f san14.awk
enter the basic pay: Rs12000
gross salary = Rs. 20400.00

Follow

Get every new post delivered to your Inbox.