Thursday, March 10, 2016

BMI Calculator in Java



a. Java Program for the body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations.

It is computed by taking the individual's weight (mass) in kilograms and dividing it by the square of their height in meters.

Write a Java program that reads from the keyboard the wight and the height in kilograms and meters and prints on the screen the BMI of the individual plus using this table gives a verdict:

BMI category
less than 18.5 underweight
18.5 to 24.9 normal weight
25.0 to 29.9 overweight
30.0 or more obese
b. Extend the program at a. to

1. read the name of the person from the keyboard

2. give the choice of the wight to be input either in kilograms or in pounds

3. give the choice of the height to be given either in meters or in feet

Perform the conversions from lb to Kg or from feet to meters and using the table above give the verdict.

Code Solution:

import java.util.Scanner;


public class BMI {

public static void main(String[] args) {
// TODO Auto-generated method stub
final double KILOGRAMS_PER_POUND = 0.453;
    //final double METERS_PER_INCH = 0.026;
        double weight = 0.0;
        double height = 0.0;
        double bmi = 0.0;
String name;
        String weightType = null;
        String heightType =null;

System.out.println("Enter your Name: ");
Scanner readname = new Scanner(System.in);
name = readname.nextLine();

        System.out.println("Press 1 or 2 to choose Weight Type: ");
        System.out.println("1.KILOGRAMS");
        System.out.println("2.POUNDS");
        Scanner readweightType = new Scanner(System.in);
        weightType = readweightType.next().trim();
        if(weightType.equalsIgnoreCase("1"))
        System.out.println("Enter Weight in Kilograms:");
        else if(weightType.equalsIgnoreCase("2"))
        System.out.println("Enter Weight in Pounds:");
        else
        {
        System.out.println("Invalid WeightType Entry");
        System.exit(0);
        }
        Scanner getWeight = new Scanner(System.in);
        weight = getWeight.nextDouble();
     
       if(weightType.equalsIgnoreCase("2"))
        {
        weight = weight* KILOGRAMS_PER_POUND ;
        //convert pounds to KG
        }
        System.out.println("Press 1 or 2 to choose Height Type: ");
        System.out.println("1.METERS");
        System.out.println("2.FEET");
     
        Scanner readHeightType = new Scanner(System.in);
        heightType = readHeightType.next().trim();
     
        if(heightType.equalsIgnoreCase("1"))
         
        System.out.println("Enter Height in Meters:");
        else if(heightType.equalsIgnoreCase("2"))
        System.out.println("Enter Weight in Feet:");
        else
        {
        System.out.println("Invalid HeightType Entry");
        System.exit(0);
        }
     
     
        Scanner readHeight = new Scanner(System.in);
        height = readHeight.nextDouble();
           
        if(heightType.equalsIgnoreCase("2"))
        {
        height = height/3.2808;
        }
     
        bmi = Math.abs((weight)/(height * height));
     
     
System.out.print("\n \t Your Name is " +name);
        System.out.printf("\n \t The BMI is %f", bmi);
        if(bmi < 18.5)
        System.out.print(" belongs to UnderWeight");
        else if(bmi >= 18.5 && bmi < 24.9)
          System.out.print(" belongs to NormalWeight");
        else if(bmi >= 25.0 && bmi <= 29.9)
          System.out.print(" belongs to OverWeight");
        else if(bmi >= 30.0 )
          System.out.print(" belongs to Obese");
     
}

}

Wednesday, March 9, 2016

Prime Factors in Java



 Write a Java program that is reading from the keyboard a value between 100 and 700 and is printing on the screen the divisors of the number.

Your program should use a cycle for validating the input (if the value typed from the keyboard is less than 100 or bigger than 700 to print an error and ask the user to input another value).

Also the program should print the prime factors in the order from smallest to biggest.

For example,

for the value 128 the program should print 128=2*2*2*2*2*2*2

for the value 122 the program should print: 122=2*61

change the program at a. to print one time a divisor but provide the power of that divisor:

for the value 128 the program should print 128=2^7

for the value 122 the program should print: 122=2^1*61^1



Solution Code:

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

public class Divisors {

  /* Java Program that is reading from the keyboard a value between 100 and 700
 and is printing on the screen the prime divisors of the number.  */
 public static void main(String args[]) throws IOException
 {
 List<Integer> resultList = new ArrayList<Integer>();
 Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 StringBuffer result = new StringBuffer();
 int n;
 System.out.print("Enter a Number : ");
 n=Integer.parseInt(br.readLine());
  if(n < 100 || n > 700)
  {
   System.out.println("Invalid Number!! Please enter the valid number in between 100 to 700");
  }
  else
  {
   System.out.print("The Prime Divisors of "+n+" are : ");
   int i=2;
   while(n>1)
   {
     if(n%i == 0)
     {
      resultList.add(i);
      //System.out.print(i+"*");
        n=n/i;
      }
   else
       i++;
   }  
   for(int index = 0; index < resultList.size(); index++)
   {
    if(index != resultList.size()-1)
     System.out.print(resultList.get(index)+"*");
    else 
     System.out.print(resultList.get(index));
    if(resultMap.containsKey(resultList.get(index)))
    {
     Integer value = resultMap.get(resultList.get(index));
     resultMap.put(resultList.get(index), value+1);
    }else
    {
    int initialize = 1;
    resultMap.put(resultList.get(index), initialize);
    }
   }
  System.out.println();
  Set<Integer> resultSet = resultMap.keySet();
  
  for(Integer key: resultSet)
  {
   result.append(key+"^"+resultMap.get(key)+"*");
  }
  
  result.replace(result.length()-1, result.length(), "");
  System.out.println(result);
   }
  }
}

Wednesday, March 2, 2016

Display Robot in Java




Write a small Java program that is printing on the screen a ROBOT. You can print whatever form of the robot you want.




import java.io.*;
import java.lang.*;
import java.util.*;
public class Robot
{
public static void main(String[] args)
    {
            System.out.println("Program for displaying pattern of Robot.\n");
         
System.out.print("      ------- \n");
System.out.print("       -   -  \n");
System.out.print("      ------- \n");
System.out.print("         |    \n");
System.out.print("         |    \n");
System.out.print("       / | \\ \n");
System.out.print("         |    \n");
System.out.print("        / \\  \n");
}
}

Tuesday, March 1, 2016

CLass Registartion System Stereotype Class Diagram







Class Registration System State Chart




State Chart for Class Registration system

Class Registration System Class Diagram




Class Diagram

Class Registration System UseCase Diagram




Use Case Diagram

Help Desk Support System Analysis Report



Analysis Report
Use Case Diagram:
Use case diagram for Help Desk Support System (including only Core functionalities):
Scenarios:
One possible Scenario for Use Case Login:
Help Desk Support System users (Customer, Technician and Administrator) can login to the system for Creating/updating the requests.
1.      At the login page user keys in the username and password, and then click on submit button.
2.      System verifies login info.
3.      System displays the Help Desk Support System main menu.
Possible Alternatives
A.      In case of user account is not active the system will display message “your account is not active. contact your system administrator”
B.      Invalid login message: the system shall display “Please enter a valid username and password”

One possible Scenario for Use Case Manage Requests:
Customer will add/raise a request whenever Customer needs a technician support.
1.      Customer will add a request which needs support.
2.      System displays the added request
Possible Alternatives

A.      Customer mistakenly add the wrong request

Second possible Scenario for Use Case Manage Requests:
Customers can cancel the request that they created whenever they think that the request is no more required. They may also cancel whey they find their own solution.
1.      Customer can delete the request from the list of the requests they raised.
2.      System removes the deleted requests and display the list of existing requests
Possible Alternatives

A.      Customer can mistakenly delete the wrong request.

Third possible Scenario for Use Case Manage Requests:
Customers can view status of all requests that they created to know whether their request is solved or not.
Possible Alternatives

A.      Customers may view the status of other request instead of the request they want to see by wrongly entering the wrong request number.

One possible Scenario for Use Case Update Request Status:
Technician will update the status of the request to fixed whenever they solved the request that are created by the customers.

Possible Alternatives

A.      Technician may update the status of the request wrongly.
Second possible Scenario for Use Case Update Request Status:
Technician will update the status of the request to progress when the request is being solved but not yet solved.
Possible Alternatives

A.      Technicians may forget to update the status to progress when they are busy solving the request.

One possible Scenario for Use Case Manage Users:
Administrator can add the technicians to solve the requests of the customers whenever needed.
Possible Alternatives

A.      Administrator may wrongly add the more technicians for the same request.
Second possible Scenario for Use Case Manage Users:
Administrator delete’s a technician and assign new technician to solve a particular request.
Possible Alternatives

A.      Administrator may delete the wrong technician instead of deleting the technician that they want.
Third possible Scenario for Use Case Manage Users:
Administrator will add the new Customer’s to the system
Possible Alternatives

A.      Administrator may wrongly enter the customer details.

Fourth possible Scenario for Use Case Manage Users:
Administrator will delete the customer details once they are no more their customers.
Possible Alternatives

A.      Administrator may wrongly delete the customer.

One possible Scenario for Use Case Logout:

Help Desk Support System users (Customer, Technician and Administrator) can login to the system and use the system for adding/updating the requests and will logout once work is done on the system.
1.      System has a logout button to logout from the Help Desk Support system.

Possible Alternatives
A.      When users press Logout button mistakenly.

Noun Extraction:

This system is mainly for managing customer requests for technical support from the help desk. Customers are able to request technical support for any issue. There are three types of users who are allowed to log into the system. The first type of users is a regular customer, who is allowed to view the status of all requests they have sent. The second type of users is a technician who is allowed to update the status of a certain request. The third type of users is the system Administrator, who has the ability to add and remove technician and user accounts.

From the above noun extraction we have gathered the long lived entity classes as follows:

Customer, Administrator, Technician, User





Class Diagram:








State Chart Diagram:



Help Desk Support System State Chart




State Chart

Help Desk Support System Sequence Diagrams





Sequence Diagram

Help Desk Support System Class Diagram





Class Diagram

Help Desk Support System Full Use Case Diagram




More Detailed Use Case Diagram

Help Desk Support System Use Case Diagram





Use Case Diagram

Facade Sequence Diagram











Facade Design Pattern Sample Class Diagram with Facade









Class Diagram With Facade

Facade Design Pattern with Sample Class DIagrams




Class Diagram Without Facade



Facade Design Pattern Class Diagram









LEX program that replicates the input on screen but filters out everything that is neither letter nor digit.




%{
/* a simple LEX program that replicates the input
   on screen but filters out everything that is
   neither letter nor digit.
*/
#include <stdio.h>
/* letter and digit counters */
int letters = 0, digits = 0;
%}
letter [a-zA-Z]
digit [0-9]
%%
{letter} { ECHO; letters++; }
{digit} { ECHO; digits++; }
[^{letter}{digit}] ;
%%
int main(int argc, char *argv[]) {
FILE *inFile;
if (argc == 2 && (inFile = fopen(argv[1], "r")))
yyin = inFile;
yylex();
if (inFile) fclose(inFile);
printf("\n\n        Count\nLetters %d\n Digits %d\n", letters, digits);
return 0;
}

LEX program that adds line numbers to lines of text, printing the new text to the standard output




%{
/* a LEX program that adds line numbers
   to lines of text, printing the new text
   to the standard output
*/
#include <stdio.h>
int lineno = 1;
%}
line .*\n
%%
{line} { printf("%5d %s", lineno++, yytext); }
%%
int main() { yylex(); return 0; }

LEX program that changes all numbers from decimal to hexadecimal notation, printing a summary statistic to stderr




%{
/* a LEX program that changes all numbers
   from decimal to hexadecimal notation,
   printing a summary statistic to stderr
*/
#include <stdlib.h>
#include <stdio.h>
int count = 0;
%}
digit [0-9]
number {digit}+
%%
{number} {
int n = atoi(yytext);
printf("%x", n);
if (n > 9) count++;
}
%%
main() {
yylex();
fprintf(stderr, "number of replacements = %d", count);
return 0;
}

LEX Program to Selects only lines that end or begin with the letter 'a'. Deletes everything else.




%{
/* Selects only lines that end or
   begin with the letter 'a'.
   Deletes everything else.
*/
#include <stdio.h>
%}
ends_with_a     .*a\n
begins_with_a   a.*\n
%%
{ends_with_a} ECHO;
{begins_with_a} ECHO;
.*\n ;
%%
main() { yylex(); return 0; }

LEX program to convert uppercase to lowercase except inside comments




%{
/* LEX program to convert uppercase to
   lowercase except inside comments
*/
#include <stdio.h>
#include <stdlib.h>
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
%}
%option noyywrap
%%
[A-Z] {
putchar(tolower(yytext[0]));
/* yytext[0] is the single
  uppercase char found */
}
"/*" {
char c;
int done = FALSE;
ECHO;
do {
while ((c = input()) != '*')
putchar(c);
putchar(c);
while ((c = input()) == '*')
putchar(c);
putchar(c);
if (c == '/') done = TRUE;
} while (!done);
}
%%
int main() { yylex(); return 0; }

Dead Lock and Main Memory OS Assignment


Questions From Text book : Operating Systems Concept by Abraham,Peter and Greg (9th Edition)


7.8
a. No, Deadlock cannot occur because preemption exists.
b. Yes. A process may never acquire all the resources it needs if they are continuously preempted by a series of requests such as those of process p2.
7.22
a.      
b.      

7.23
a.      
b.

c.
8.9   When memory allocated to a process is larger than the requested memory, space at the end of a partition is wasted or unused. This space which is getting wasted within the partition is called internal fragmentation. When enough total memory space exists to satisfy a request, but it is not contiguous storage is fragmented to into a large number of small holes. This wasted space not allocated to any partition is called external fragmentation. Internal Fragmentation occurs when a fixed size memory allocation technique is used. External fragmentation occurs when a dynamic memory allocation technique is used.






8.11
Best fit uses the memory efficiently and then the first fit. Worst fit must wait.
8.13
Contiguous memory allocation suffers from external fragmentation as address spaces are allocated contiguously and holes develop as old processes dies and new processes are initiated. It also does not allow processes to share code , since a processes virtual memory segment is not broken into non-contiguous fine-grained segments. 
Pure segmentation also suffers from external fragmentation as a segment of a process is laid out contiguously in physical memory and fragmentation would occur as segments of dead processes are replaced by segments of new processes. Segmentation however enables processes to share code for instance two different processes could share a code segment but have distinct data segments.
Pure Paging doesn’t not suffer from external fragmentation, but instead it suffers from internal fragmentation. Processes are allocated in page granularity and if a page is not a completely utilized, it results in internal fragmentation and a corresponding wastage of space. Paging also enables processes to share code at granularity of pages.
8.17
Paging requires more memory overhead to maintain the translation structures. Segmentation requires just two registers per segment. One to maintain the base of the segment and the other to maintain the extent of the segment. Paging on the other hand requires one entry per page, and this entry provides the physical address in which page is located.
8.25
a. 100 nanoseconds, 50 ns to access the page table and 50ns to access the word in memory.
b. Effective access time = ( 0.75*50ns) + (0.25*100ns)+2=64.5ns




9.21





9.22
a. Virtual Address to Physical address
·        0xE12C à0x312C
·         0x3A9Dà0xAA9D
·         0xA9D9à0x59D9
·         0x7001à0xF001
·         0xACA1à0x5CA1
Below is the page table updated with reference bit.
Page                                       Page Frame                                      Reference Bit
0                                                          9                                                          0
1                                                          1                                                         0
2                                                          14                                                      0
3                                                          10                                                       1
4                                                          –                                                          0
5                                                          13                                                       0
6                                                          8                                                         0
7                                                          15                                                      1
8                                                          –                                                         0
9                                                          0                                                          0
10                                                       5                                                          1
11                                                       4                                                          0
12                                                       –                                                         0
13                                                       –                                                          0
14                                                       3                                                          1
15                                                       2                                                          0

b. Pages 4,8,12 and 13 result and page fault and their logical address in hexadecimal as follows 0x4… , 0x8… ,0xC… , 0xD…
c. In the above page table which has reference bit 0 those page frames will choose page replacement. They are {9,1,14,13,8,0,4,2}



Sample questions on OS



1. When a process requests for I/O, how many process switches take place?
 Answer:
Two. In the first switch, the process to be switched is taken out and the scheduler starts executing. Then the next process is brought to execution. So there are two process switches.
2. Consider a system consisting of four resources of the same type that are shared by three processes, each of which needs at most two resources. Show that the system is deadlock free.
 Answer:
Suppose the system is deadlocked. This implies that each process is holding one resource and is waiting for one more. Since there are three processes and four resources, one process must be able to obtain two resources. This process requires no more resources and, therefore it will return its resources when done.
3. Explain the sequence of events that happens when a page-fault occurs.
Answer:
When the operating system cannot load the desired page into memory, a page-fault occurs. First, the memory reference is checked for validity. In the case of an invalid request, the program will be terminated. If the request was valid, a free frame is located. A disk operation is then scheduled to read the page into the frame just found, update the page table, restart the instruction that was interrupted because of the page fault, and use the page accordingly.

4. Explain the usefulness of a modify bit.
Answer:
A modify bit is associated with each page frame. If a frame is modified (i.e. written), the modify bit is then set. The modify bit is useful when a page is selected for replacement. If the bit is not set (the page was not modified), the page does not need to be written to disk. If the modify bit is set, the page needs to be written to disk when selected for replacement.
5. If you were creating an operating system to handle files, what would be the six basic file operations that you should implement?
Answer:
 The six basic file operations include: creating a file, writing a file, reading a file, repositioning within a file, deleting a file, and truncating a file. These operations comprise the minimal set of required file operations.