Tuesday 23 February 2016

Is there any way for a function that is called by main to examine the command-line arguments without (a) passing argc and argv as arguments from main to the function or (b) having main copy argc and argv into global variables?

On most UNIX systems, there is no way to do this. Copies of 'argc' and 'argv' are not kept in global variables like environ is.

When is the output from the printfs in Figure 7.3 actually output?

When the program is run interactively, standard output is usually line buffered, so the actual output occurs when each newline is output. If standard output were directed to a file, however, it would probably be fully buffered, and the actual output wouldn’t occur until the standard I/O cleanup is performed.

Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.

An existing file descriptor is duplicated by either of the following functions:
#include <unistd.h>
int dup(int fd);
int dup2(int fd, int fd2);
Both return: new file descriptor if OK, −1 on error
The new file descriptor returned by dup is guaranteed to be the lowest-numbered
available file descriptor. With dup2, we specify the value of the new descriptor with the
fd2 argument. If fd2 is already open, it is first closed. If fd equals fd2, then dup2 returns
fd2 without closing it. Otherwise, the FD_CLOEXEC file descriptor flag is cleared for fd2,
so that fd2 is left open if the process calls exec.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include    <stdio.h>
#include <unistd.h>

char arr[] = "my name is mydup\n";

int main()
{
    int fd1, fd2;

    char pidstr[128] = "\0";
    fd1 = open ("~/test/file_for_dup", O_CREAT|O_RDWR);
    if (fd1 < 0) {
        perror ("open");
        exit(-1);
    }

    sprintf (pidstr, "/proc/self/fd/%d", fd1);
    printf ("pidstr: %d %s\n", fd1, pidstr);
    write (fd1, arr, sizeof(arr));
    fd2 = open (pidstr, O_RDWR);
    if (fd2 < 0) {
        perror ("open");
        exit(-1);
    }
    lseek (fd2, sizeof (arr), SEEK_SET);
    write (fd2, arr, sizeof(arr));
    close (fd2);
    close (fd1);

}

Assume that a process executes the following three function calls: fd1= open(pathname, oflags); fd2 = dup(fd1); fd3 = open(pathname, oflags); Draw the resulting picture, similar to Figure 3.8. Which descriptors are affected by an fcntl on fd1 with a command of F_SETFD? Which descriptors are affected by an fcntl on fd1 with a command of F_SETFL?

 Each call to open gives us a new file table entry. But since both opens reference the same file, both file table entries point to the same v-node table entry. The call to dup references the existing file table entry. We show this in Figure C.2. An F_SETFD on fd1 affects only the file descriptor flags for fd1. But an F_SETFL on fd1 affects the file table entry that both fd1 and fd2 point to.
Figure C.2. Result of dup and open






The following sequence of code has been observed in various programs: dup2(fd,0); dup2(fd,1); dup2(fd,2); if (fd > 2) close(fd); To see why the if test is needed, assume that fd is 1 and draw a picture of what happens to the three descriptor entries and the corresponding file table entry with each call to dup2. Then assume that fd is 3 and draw the same picture.

If fd is 1, then the dup2(fd, 1) returns 1 without closing descriptor 1. (Remember our discussion of this in Section 3.12.) After the three calls to dup2, all three descriptors point to the same file table entry. Nothing needs to be closed.
If fd is 3, however, after the three calls to dup2, four descriptors are pointing to the same file table entry. In this case, we need to close descriptor 3.

The Bourne shell, Bourne-again shell, and Korn shell notation digit1>&digit2 says to redirect descriptor digit1 to the same file as descriptor digit2. What is the difference between the two commands ./a.out > outfile 2>&1 ./a.out 2>&1 > outfile

Since the shells process their command line from left to right, the command
./a.out > outfile 2>&1
first sets standard output to outfile and then dups standard output onto descriptor 2 (standard error). The result is that standard output and standard error are set to the same file. Descriptors 1 and 2 both point to the same file table entry. With
./a.out 2>&1 > outfile
however, the dup is executed first, causing descriptor 2 to be the terminal (assuming that the command is run interactively). Then standard output is redirected to the file outfile. The result is that descriptor 1 points to the file table entry for outfile, and descriptor 2 points to the file table entry for the terminal

On an Intel x86 system under Linux, if we execute the program that prints ‘‘hello, world’’ and do not call exit or return, the termination status of the program — which we can examine with the shell—is 13. Why?

It appears that the return value from printf (the number of characters output) becomes the return value of main. To verify this theory, change the length of the string printed and see if the new length matches the return value. Note that not all systems exhibit this property. Also note that if you enable the ISO C  extensions in gcc, then the return value is always 0, as required by the standard.


When reading or writing a disk file, are the functions described in this chapter really unbuffered? Explain.

All disk I/O goes through the kernel's block buffers (also called the kernel's buffer cache). The exception to this is I/O on a raw disk device, which we aren't considering. Chapter 3 of Bach [1986] describes the operation of this buffer cache. Since the data that we read or write is buffered by the kernel, the term unbuffered I/O refers to the lack of automatic buffering in the user process with these two functions. Each read or write invokes a single system call

Update the program in Figure 2.16 to avoid the needless processing that occurs when sysconf returns LONG_MAX as the limit for OPEN_MAX.

If OPEN_MAX is indeterminite or ridiculously large (i.e., equal to LONG_MAX), we can use geTRlimit to get the per process maximum for open file descriptors. Since the per process limit can be modified, we can't cache the value obtained from the previous call


#include "apue.h"
#include <limits.h>
#include <sys/resource.h>

#define OPEN_MAX_GUESS 256

long
open_max(void)
{
    long openmax;
    struct rlimit rl;

    if ((openmax = sysconf(_SC_OPEN_MAX)) < 0 ||
      openmax == LONG_MAX) {
        if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
            err_sys("can't get file limit");
        if (rl.rlim_max == RLIM_INFINITY)
            openmax = OPEN_MAX_GUESS;
        else
            openmax = rl.rlim_max;
    }
    return(openmax);

}

Examine your system's headers and list the actual data types used to implement the primitive system data types.

The header <sys/types.h> defines some implementation-dependent data types,
called the primitive system data types. More of these data types are defined in other
headers as well. These data types are defined in the headers with the C typedef
facility. Most end in _t.

We mentioned in Section 2.8 that some of the primitive system data types are defined in more than one header. For example, on FreeBSD 5.2.1, size_t is defined in 26 different headers. Because all 26 headers could be included in a program and because ISO C does not allow multiple typedefs for the same name, how must the headers be written?

#ifndef _MACHINE__TYPES_H_
#define _MACHINE__TYPES_H_
typedef int __int32_t;
typedef unsigned int __uint32_t;
...
typedef __uint32_t __size_t;
...
#endif /* _MACHINE__TYPES_H_ */
In each of the headers that can define the size_t primitive system data type, we have the sequence
#ifndef _SIZE_T_DECLARED
typedef __size_t size_t;
#define _SIZE_T_DECLARED
#endif
This way, the typedef for size_t is executed only once.

Given functions f(g) = g^t and u(c) = c^g, and t>=1 and and c>1 are constants. Find the asymptotic relationship between the functions?




Explain the kind of growth the following functions would have and why? a. f(p) = 5^p b. f(q) = q^3


  •  As the value of p increases the function f(p) is also increases exponentially.
  •  for positive values of p the growth of f(p) is high.
  •  for negative values of p the growth of f(p) is low.  
      
     








b) As the value of q increases the function f(q) is also increases exponentially





Write the algorithm for bubble sort and explain its worst, best and average cases, precisely?

Bubble Sort:-
In bubble sort method the list is divided into two sub-lists sorted and unsorted. The smallest element is bubbled from unsorted sub-list. After moving the smallest element the imaginary wall moves one element ahead. The bubble sort was originally written to bubble up the highest element in the list. But there is no difference whether highest / lowest element is bubbled. This method is easy to understand but time consuming. In this type, two successive elements are compared and swapping is done. Thus, step-by-step entire array elements are checked. Given a list of ‘n’ elements the bubble sort requires up to n-1 passes to sort the data
Algorithm for Bubble Sort:-
Bubble_Sort ( A [ ] , N )
Step 1 : Repeat For P = 1 to N – 1 Begin
Step 2 : Repeat For J = 1 to N – P Begin
Step 3 : If ( A [ J ] < A [ J – 1 ] )
Swap ( A [ J ] , A [ J – 1 ] ) End For
End For
Step 4 : Exit
Time Complexity of Bubble Sort : -
  •  For an array of size n, in the worst case:
  • 1st passage through the inner loop: n-1 comparisons and n-1 swaps
  • (n-1)st passage through the inner loop: one comparison and one swap.
  •  All together: c ((n-1) + (n-2) + ... + 1), where c is the time required to do one comparison,one swap, check the inner loop condition and increment j.
  •  We also spend constant time k declaring i,j,temp and initialising i. Outer loop is executed
n-1 times, suppose the cost of checking the loop condition and decrementing i is c1.
c ((n-1) + (n-2) + ... + 1) + k + c1
(n-1) (n-1) + (n-2) + ... + 1 = n(n-1)/2
so our function equals
c n*(n-1)/2 + k + c1(n-1) = 1/2c (n2-n) + c(n-1) + k
Complexity O(n2)
Best case : O (n2)
Average case : O (n2)
Worst case : O (n2)

Wednesday 10 February 2016

cs java programs


1. {50 points}Design a new Triangle class that extends the abstract class GeometricObject class. Write a test program that prompts the user to enter the 3 sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter,color and true or false to indicate whether it is filled or not. (s=side) Area of a triangle = Square-root of ((s*(s-1)*(s-2)*(s-3)).


Program:

GeometricObject  class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public abstract class GeometricObject
{
           
            private String color = "white";
            private boolean filled;
           
           
            protected GeometricObject()
            {
                       
            }
           
            public String getColor()
            {
                        return color;
            }
           
            public void setColor(String color)
            {
                        this.color = color;
            }
           
            public boolean isFilled()
            {
                        return filled;
            }
           
            public void setFilled(boolean filled)
            {
                        this.filled = filled;
            }
           
           
           
            public String toString()
            {
                        return  " Color: " + color + " and filled: " + filled;
            }
           
            public abstract double getArea();
           
            public abstract double getPerimeter();             
}



Triangle class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class Triangle extends GeometricObject {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public Triangle() {
    }

    public Triangle(double side1, double side2, double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }
    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }
    public void setSide1(double side1) {
        this.side1 = side1;
    }

    public void setSide2(double side2) {
        this.side2 = side2;
    }

    public void setSide3(double side3) {
        this.side3 = side2;
    }
    public double getArea() {
        double p = getPerimeter() / 2;
        return Math.sqrt(p * ((p - side1) * (p - side2) * (p - side3)));
    }
    public double getPerimeter() {
        return side1 + side2 + side3;
    }

    public String toString() {
    return " Triangle: Side 1 = " + side1 + " Side 2 = " + side2
           + " Side 3 = " + side3;
    }
}

TestTriangle class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
import java.util.Scanner;

public class TestTriangle  {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter three sides of the Triangle");
        double side1 = input.nextDouble();
        double side2 = input.nextDouble();
        double side3 = input.nextDouble();
        Triangle triangle = new Triangle(side1, side2, side3);
        System.out.println("Enter the color of the Triangle");
        String color = input.next();
        triangle.setColor(color);

        System.out.println(" Is the Triangle filled? Reply with 'True' or 'False' ");

        String filled = input.next();
  
    Triangle triangle1 = new Triangle(side1, side2, side3);
    System.out.println("The Triangle Sides are \n side 1: "
                   + triangle1.getSide1() + "\n Side 2: " + triangle1.getSide2()
                   + "\n Side 3: " + triangle1.getSide3());

            System.out.println("The Triangle's Area is " + triangle1.getArea());

            System.out.println("The Triangle's Perimeter is " + triangle1.getPerimeter());

            System.out.println("The Triangle's Color is " + triangle1.getColor());
            System.out.println("Is the Triangle filled? " + triangle1.isFilled());
    }
}
   

OutPut:

run:
Enter three sides of the Triangle
5
6
8
Enter the color of the Triangle
white
 Is the Triangle filled? Reply with 'True' or 'False'
t
The Triangle Sides are
 side 1: 5.0
 Side 2: 6.0
 Side 3: 8.0
The Triangle's Area is 14.981238266578634
The Triangle's Perimeter is 19.0
The Triangle's Color is white
Is the Triangle filled? false
BUILD SUCCESSFUL (total time: 14 seconds)




 2. {50 points} Write a class named Octagon that extends GeometricObject and implements Comparable and Cloneable  interfaces. Assume that all eight sides of the octagon are equal.
Write a test program that creates an Octagon object with side value 5 and displays its area and perimeter. Create a new object using the clone method and compare the objects using the
compareTo method. Area of a regular octagon = (2+4/sqrt(2)) * side*side.

Program:

GeometricObject  class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public abstract class GeometricObject
{
           
            private String color = "white";
            private boolean filled;
           
            //default constructor
            protected GeometricObject()
            {
                       
            }
           
            public String getColor()
            {
                        return color;
            }
           
            public void setColor(String color)
            {
                        this.color = color;
            }
           
            public boolean isFilled()
            {
                        return filled;
            }
           
            public void setFilled(boolean filled)
            {
                        this.filled = filled;
            }
           
           
           
            public String toString()
            {
                        return  " Color: " + color + " and filled: " + filled;
            }
           
            public abstract double getArea();
           
            public abstract double getPerimeter();             
}


Octagon class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class Octagon extends GeometricObject implements Comparable<Octagon>
{
            private double side = 1.0;
            protected native Object clone() throws CloneNotSupportedException;

                       
            public Octagon()
            {
            }
           
            public Octagon(double side)
            {
                        super();
                        this.side = side;
            }
           
                       
           
            public void setSide(double side)
            {
                        this.side = side;
            }         
           
            public double getSide(double side)
            {
                        return side;
            }
           
            public double getArea()
            {
                        return (2 + 4 / (Math.sqrt(2)) * side * side);
            }
           
            public double getPerimeter()
            {
                        return side * 8;
            }                     
           
            public String toString()
            {
                        return "The length of each side is: " + side;
            }
           
            public int compareTo(Octagon octagon1)
            {
                        if (getArea() >= octagon1.getArea())
                                    return 1;
                       
                        else if (getArea() < octagon1.getArea())
                                    return -1;
                       
                        else
                                    return 0;
            }                     
           
            public interface Cloneable
            {
            }
           
}


OctagonTester class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class OctagonTester
{
            public static void main(String[] args) throws CloneNotSupportedException

            {
                        Octagon octagon = new Octagon();
                        Octagon octagon1 = new Octagon(5.0);
                       
                        System.out.println("The area of the octagon is: " + octagon1.getArea());
                        System.out.println("The perimeter of the octagon is: " + octagon1.getPerimeter());
                        System.out.println("When you compare the two objects, they return: " + octagon.compareTo(octagon1));
            }
}
Output:
run:
The area of the octagon is: 72.71067811865474
The perimeter of the octagon is: 40.0
When you compare the two objects, they return: -1
BUILD SUCCESSFUL (total time: 0 seconds)





1. {50 points}Design a new Triangle class that extends the abstract class GeometricObject class. Write a test program that prompts the user to enter the 3 sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter,color and true or false to indicate whether it is filled or not. (s=side) Area of a triangle = Square-root of ((s*(s-1)*(s-2)*(s-3)).


Program:

GeometricObject  class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public abstract class GeometricObject
{
           
            private String color = "white";
            private boolean filled;
           
           
            protected GeometricObject()
            {
                       
            }
           
            public String getColor()
            {
                        return color;
            }
           
            public void setColor(String color)
            {
                        this.color = color;
            }
           
            public boolean isFilled()
            {
                        return filled;
            }
           
            public void setFilled(boolean filled)
            {
                        this.filled = filled;
            }
           
           
           
            public String toString()
            {
                        return  " Color: " + color + " and filled: " + filled;
            }
           
            public abstract double getArea();
           
            public abstract double getPerimeter();             
}



Triangle class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class Triangle extends GeometricObject {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public Triangle() {
    }

    public Triangle(double side1, double side2, double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }
    public double getSide1() {
        return side1;
    }

    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }
    public void setSide1(double side1) {
        this.side1 = side1;
    }

    public void setSide2(double side2) {
        this.side2 = side2;
    }

    public void setSide3(double side3) {
        this.side3 = side2;
    }
    public double getArea() {
        double p = getPerimeter() / 2;
        return Math.sqrt(p * ((p - side1) * (p - side2) * (p - side3)));
    }
    public double getPerimeter() {
        return side1 + side2 + side3;
    }

    public String toString() {
    return " Triangle: Side 1 = " + side1 + " Side 2 = " + side2
           + " Side 3 = " + side3;
    }
}

TestTriangle class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
import java.util.Scanner;

public class TestTriangle  {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter three sides of the Triangle");
        double side1 = input.nextDouble();
        double side2 = input.nextDouble();
        double side3 = input.nextDouble();
        Triangle triangle = new Triangle(side1, side2, side3);
        System.out.println("Enter the color of the Triangle");
        String color = input.next();
        triangle.setColor(color);

        System.out.println(" Is the Triangle filled? Reply with 'True' or 'False' ");

        String filled = input.next();
  
    Triangle triangle1 = new Triangle(side1, side2, side3);
    System.out.println("The Triangle Sides are \n side 1: "
                   + triangle1.getSide1() + "\n Side 2: " + triangle1.getSide2()
                   + "\n Side 3: " + triangle1.getSide3());

            System.out.println("The Triangle's Area is " + triangle1.getArea());

            System.out.println("The Triangle's Perimeter is " + triangle1.getPerimeter());

            System.out.println("The Triangle's Color is " + triangle1.getColor());
            System.out.println("Is the Triangle filled? " + triangle1.isFilled());
    }
}
   

OutPut:

run:
Enter three sides of the Triangle
5
6
8
Enter the color of the Triangle
white
 Is the Triangle filled? Reply with 'True' or 'False'
t
The Triangle Sides are
 side 1: 5.0
 Side 2: 6.0
 Side 3: 8.0
The Triangle's Area is 14.981238266578634
The Triangle's Perimeter is 19.0
The Triangle's Color is white
Is the Triangle filled? false
BUILD SUCCESSFUL (total time: 14 seconds)




 2. {50 points} Write a class named Octagon that extends GeometricObject and implements Comparable and Cloneable  interfaces. Assume that all eight sides of the octagon are equal.
Write a test program that creates an Octagon object with side value 5 and displays its area and perimeter. Create a new object using the clone method and compare the objects using the
compareTo method. Area of a regular octagon = (2+4/sqrt(2)) * side*side.

Program:

GeometricObject  class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public abstract class GeometricObject
{
           
            private String color = "white";
            private boolean filled;
           
            //default constructor
            protected GeometricObject()
            {
                       
            }
           
            public String getColor()
            {
                        return color;
            }
           
            public void setColor(String color)
            {
                        this.color = color;
            }
           
            public boolean isFilled()
            {
                        return filled;
            }
           
            public void setFilled(boolean filled)
            {
                        this.filled = filled;
            }
           
           
           
            public String toString()
            {
                        return  " Color: " + color + " and filled: " + filled;
            }
           
            public abstract double getArea();
           
            public abstract double getPerimeter();             
}


Octagon class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class Octagon extends GeometricObject implements Comparable<Octagon>
{
            private double side = 1.0;
            protected native Object clone() throws CloneNotSupportedException;

                       
            public Octagon()
            {
            }
           
            public Octagon(double side)
            {
                        super();
                        this.side = side;
            }
           
                       
           
            public void setSide(double side)
            {
                        this.side = side;
            }         
           
            public double getSide(double side)
            {
                        return side;
            }
           
            public double getArea()
            {
                        return (2 + 4 / (Math.sqrt(2)) * side * side);
            }
           
            public double getPerimeter()
            {
                        return side * 8;
            }                     
           
            public String toString()
            {
                        return "The length of each side is: " + side;
            }
           
            public int compareTo(Octagon octagon1)
            {
                        if (getArea() >= octagon1.getArea())
                                    return 1;
                       
                        else if (getArea() < octagon1.getArea())
                                    return -1;
                       
                        else
                                    return 0;
            }                     
           
            public interface Cloneable
            {
            }
           
}


OctagonTester class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package week11;

/**
 *
 * @author kishore
 */
public class OctagonTester
{
            public static void main(String[] args) throws CloneNotSupportedException

            {
                        Octagon octagon = new Octagon();
                        Octagon octagon1 = new Octagon(5.0);
                       
                        System.out.println("The area of the octagon is: " + octagon1.getArea());
                        System.out.println("The perimeter of the octagon is: " + octagon1.getPerimeter());
                        System.out.println("When you compare the two objects, they return: " + octagon.compareTo(octagon1));
            }
}
Output:
run:
The area of the octagon is: 72.71067811865474
The perimeter of the octagon is: 40.0
When you compare the two objects, they return: -1
BUILD SUCCESSFUL (total time: 0 seconds)