Ahmadu Bello University Department of Mathematics First Semester Examinations June 2014 COSC211: Introduction to Object Oriented Programming I

Similar documents
Midterm Examination (MTA)

Programming with Java

Ahmadu Bello University, Zaria Department of Computer Science

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Object Oriented Programming. Java-Lecture 6 - Arrays

CS111: PROGRAMMING LANGUAGE II

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

b. Suppose you enter input from the console, when you run the program. What is the output?

CAT.woa/wa/assignments/eclipse

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Lab Exercise 1. Objectives: Part 1. Introduction

Introduction to Computer Science Unit 2. Notes

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

EXAMINATION FOR THE BSC (HONS) INFORMATION TECHNOLOGY; BSC (HONS) INFORMATION SYSTEMS & BSC (HONS) COMPUTER SCIENCE; YEAR 1

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Controls Structure for Repetition

Chapter 4: Control Structures I

CS141 Programming Assignment #6

Introduction to Computer Science Unit 2. Notes

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Chapter 2. Elementary Programming

Introduction to Programming Using Java (98-388)

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Object Oriented Programming. Java-Lecture 1

CS141 Programming Assignment #5

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Last Name: Circle One: OCW Non-OCW

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

AP CS Unit 3: Control Structures Notes

CS 1302 Chapter 9 (Review) Object & Classes

Introduction to Computer Programming

Software and Programming 1

CEN 414 Java Programming

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Exercise 0.1 (Review from lectures no submission required)

Selected Questions from by Nageshwara Rao

Question: Total Points: Score:

Conditional Execution

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Loops. CSE 114, Computer Science 1 Stony Brook University

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Chapter 10. Object-Oriented Thinking

Exercise 1: Class Employee: public class Employee { private String firstname; private String lastname; private double monthlysalary;

Chapter 02: Using Data

CS Computers & Programming I Review_01 Dr. H. Assadipour

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

CS1083 Week 2: Arrays, ArrayList

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Exceptions Handeling

Chapter 5 Lab Methods

Computational Expression

Chapter 2: Using Data

ESC101 : Fundamental of Computing

Arrays. Eng. Mohammed Abdualal

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Distributed Systems Recitation 1. Tamim Jabban

Assignment 1 due Monday at 11:59pm

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 12 Exception Handling

Fundamentals of Programming Data Types & Methods

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

COMP 401 Spring 2013 Midterm 1

CS 1331 Exam 1 ANSWER KEY

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Oct Decision Structures cont d

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Question: Total Points: Score:

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

AP Computer Science Java Mr. Clausen Program 6A, 6B

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

CPSC 233 Final Exam, Winter 2003 DEPARTMENT OF COMPUTER SCIENCE THE UNIVERSITY OF CALGARY Time: 120 minutes 100 marks total L02, L03, L04

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Question: Total Points: Score:

Chapter 3. Selections

COMP 110 Project 1 Programming Project Warm-Up Exercise

Question 1 [20 points]

MIDTERM REVIEW. midterminformation.htm

Transcription:

Ahmadu Bello University Department of Mathematics First Semester Examinations June 2014 COSC211: Introduction to Object Oriented Programming I Attempt Four questions Time: 120 mins 1. Examine the following code for the class Horse and answer the questions that follow. 1. //Horse.java 2. 3. public class Horse{ 4. private static final double MAX_WT = 500.0; 5. private static final double MIN_WT = 25.0; 6. private static final double MAX_HT = 2.0; 7. private static final double MIN_HT = 0.5; 8. private static final String DEF_NAME = "Horse"; 9. private static final double DEF_WT = 25.0; 10. private static final double DEF_HT = 0.5; 11. 12. private String name; 13. private double weight; //kilograms 14. private double height; //metres 15. 16. //getters 17. public String getname(){ 18. return name; 19. } 20. 21. public double getweight(){ 22. return weight; 23. } 24. 25. public double getheight(){ 26. return height; 27. } 28.

COSC211: Introduction to Object Oriented Programming I 29. //setters 30. public void setname(string name){ 31. this.name = name; 32. } 33. 34. public void setweight(double weight){ 35. if (weight > MAX_WT) weight = MAX_WT; 36. if (weight < MIN_WT) weight = MIN_WT; 37. this.weight = weight; 38. } 39. 40. public void setheight(double height){ 41. if (height > MAX_HT) height = MAX_HT; 42. if (height < MIN_HT) height = MIN_HT; 43. this.height = height; 44. } 45. 46. //constructors 47. public Horse(String name, double weight, double height){ 48. setname(name); 49. setweight(weight); 50. setheight(height); 51. } 52. 53. public Horse(String name){ 54. this(name, DEF_WT, DEF_HT); 55. } 56. 57. public Horse(){ 58. this(def_name); 59. } 60. 61. public String tostring(){ 62. return String.format("Name: %s\nweight: " + "%8.2f\nHeight: %8.2f", name, weight, height); 63. } 64. }//end of class horse

First Semester Examinations June 2014 (a) On lines 4 to 10 fields are declared to be both static and final. Explain the meanings of these two keywords in this context. A field declared to be static is a class field. It is shared by all the instances of the class and is stored once only.. It is accessible even if no instance of the class has been created. It is accessed using the class name rather than the instance name: eg Horse.MAX_WT A field declared to be final is a constant, so that its value, once assigned, cannot be changed. (b) On lines 17 to 27 three getters are defined. What is their purpose? Why are they required? A public getter allows the value of a field to be retrieved by a call made from outside the class containing the field. This is necessary if the field is private. (c) Two of the setter methods perform data validation. What is the purpose of performing data validation? Explain how the data validation in one of these setter methods works. Data validation is performed to ensure that the value of a field is reasonable. The validation for weight ensures that it lies between 25 kg and 500 kg (lines 35-36). (d) Explain the usage of the this keyword on line 31. It serves to distinguish between the field weight and the parameter weight. The first (preceded by this) is the field; the second (on its own) is the parameter. (3 marks) (e) Explain what is meant by constructor overloading. Explain how this is carried out in the Horse class. A constructor is overloaded when more than one is defined (with the same name) but each has a different list of parameter types. The different constructors are

COSC211: Introduction to Object Oriented Programming I distinguished by their parameter lists. The Horse class has three constructors: Horse(String, double, double), Horse(String) and Horse(). (f) There is a tostring() method defined on lines 61 to 63. Explain what it does and how it is used. The tostring() method returns a string representation of an object. Whenever a string representation of an object is required the tostring() method may be automattically inserted by the compiler, as in this example: System.out.println(horse); //becomes horse.tostring() where horse is an instance of Horse. (3 marks)

First Semester Examinations June 2014 2. (a) Create a class named Grade that includes the following. (i) Declarations for two fields named name and score of type string and double respectively. (ii) Definitions of two constructors where the first one should has no parameter while the second contains parameters that initialize the fields declared in (i) above. (iii) Getters and setters of the fields declared in (i) above. (iv) A method called isscorevalid() that will returns true if score is neither greater than 100 nor less than 0, false otherwise. (v) A method called computegrade() that will returns the grade (char) as follows. grade = 'A' if score>=70 grade = 'B' if 60 <= score < 70 grade = 'C' if 50 <= score < 60 grade = 'D' if 45 <= score < 50 grade = 'E' if 40 <= score < 45 grade = 'F' if score < 40 public class Grade{ private String name; private double score; public Grade(){ this("garba", 0); }// end of no-args constructor public Grade(String name, double score){ this.score = score; this.name = name; }// end of constructor public String getname(){ return name; }// end of getname() public double getscore(){ return score; }//end of getscore() public void setscore(double score){

COSC211: Introduction to Object Oriented Programming I this.score = score; }// end of setscore() public void setname(string name){ this.name = name; }// end of setname() public boolean isscorevalid(){ if (score < 0 score > 100) return false; else return true; }// end of isscorevalid() public char computegrade(){ char grade; (4 marks) if (score >= 70) grade = 'A'; else if (score >= 60) grade = 'B'; else if (score >= 50) grade = 'C'; else if (score >= 45) grade = 'D'; else if (score >= 40) grade = 'E'; else grade = 'F'; return grade; }//end of computegrade() }// end of Grade class (b) Create a test class called GradeTest that will enable the user to enter a student's name and score and see the students grade. The output should look like Fati's score is 62 and grade is B or (if the score is more than 100 or less than zero)

First Semester Examinations June 2014 The score is invalid import java.util.scanner; (½ mark) public class GradeTest{ public static void main(string[] args){ Scanner input = new Scanner(System.in); (½ mark) System.out.print("Enter the student's " + "name: "); String name = input.nextline(); System.out.print("Enter the student's " + "score: "); double score = input.nextdouble(); Grade grade = new Grade(name, score); if(grade.isscorevalid()) System.out.printf("%s\'s score is " "%.2f and grade is %c", grade.getname(), grade.getscore, grade.computegrade()); else System.out.println("The score is invalid"); } }//end of GradeTest class

COSC211: Introduction to Object Oriented Programming I 3. Examine the following code and answer the questions that follow. 1. //ProcessMarks 2. 3. import java.util.scanner; 4. 5. public class ProcessMarks{ 6. public static void main(string[] args){ 7. Scanner input = new Scanner(System.in); 8. int sum = 0, num = 0; 9. System.out.print("Enter a student mark " + "(-1 to exit): "); 10. int mark = input.nextint(); 11. 12. while(mark >= 0){ 13. if (mark >= 40){ 14. sum = sum + mark; 15. num++; 16. } 17. System.out.print("Enter a " + "student mark (-1 to exit): "); 18. mark = input.nextint(); 19. } 20. 21. if (num > 0){ 22. double average = (double)sum / num; 23. System.out.printf("The required " + "average is %.1f\n", average); 24. } 25. else 26. System.out.println("The are no " + "marks to average"); 27. }//end of main() 28. }//end of class ProcessMarks (a) What is the purpose of the import statement on line 3? The import statement makes the Scanner class in the package java.util from the Java API available to the program. (3 marks)

First Semester Examinations June 2014 (b) What is the most important difference between a pre-condition loop and a post-condition loop? What type of loop starts on line 12? With a post-conditon loop the loop body will be traversed at least once; while with a pre-condition loop it is possible that the loop body may never be entered. It is a pre-condition loop. (2 + 1 marks) (c) What is the sum that is evaluated on line 14? It is the sum of all those marks that are 40 or more (3 marks) (d) Explain the purpose of (double) on line 22 where average is evaluated. The sum is cast (converted) to a double before the division is performed. If this is not done then integer division will be performed and the resulting value of average will not be correct. (3 marks) (e) When running this program a user enters 45, 56, 34, 68 and then 1 in response to the prompts. Show the resulting output. (average = (45 + 56 + 68) / 3 = 56.333...) The required average is 56.3 (4 marks) (f) When running this program a user enters 20, 34, 39, 15 and then 1 in response to the prompts. Show the resulting output. There are no marks to average (4 marks)

COSC211: Introduction to Object Oriented Programming I 4. Ahmadu Bello University Press wants to know the maximum, minimum, total, and average profit gained from years 2005 to 2014. Besides that, they are interested in knowing the difference between the maximum and minimum profit and those profits that are above average. The profits are as follows. Year Profit(x) 2005 5,000,000.34 2006 2,005.000.00 2007 3,020,000.97 2008 5,057,800.20 2009 4,500,000.67 2010 5,000,000.00 2011 3,048,900.56 2012 4,800,000.50 2013 2,980,000.71 2014 4,909,000.80 (a) Create a class called Profit that has the following members. (i) Two array fields to store the profit and year named profit and year using appropriate data types. (ii) A method called getmaxprofit() that will return the maximum profit. (iii) A method called getminprofit() that will return the minimum profit. (iv) A method called getsumofprofit() that will return the total profit. (v) A method called getaverageprofit() that will return the average profit. (vi) A method called getrange() that will return the difference between the maximum and minimum profits. (vii) A method called showprofitbelowaverage() that will display all profits that are below average. public class Profit{ int[] year = { 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014}; double[] profit = {5000000.34, 2005000.00, 3020000.97, 5057800.20, 4500000.67, 5000000.00, 3048900.56, 4800000.50, 2980000.71, 4909000.80};

First Semester Examinations June 2014 public double getmaxprofit(){ double maxprofit = profit[0]; for(int i = 1; i < profit.length; i++){ if (profit[i] > maxprofit) maxprofit = profit[i]; }// end of for loop return maxprofit; }//end of method getmaxprofit() public double getminprofit(){ double minprofit = profit[0]; for(int i = 1; i < profit.length; i++){ if (profit[i] < minprofit) minprofit = profit[i]; }// end of for loop return minprofit; }// end of method getminprofit() public double getsumofprofit(){ double sum = 0; for(int i = 0; i < profit.length; i++){ sum = sum + profit[i]; }//end of for loop return sum; }//end of method getsumofprofit() public double getaverageprofit(){ (3 marks) return getsumofprofit() / profit.length; }//end of method getaverageprofit public double getrange(){ return getmaxprofit() - getminprofit(); }//end of method getsumofprofit() public void showprofitbelowaverage(){ (3 marks) for(int i = 0; i < profit.length; i++){ if (profit[i] < getaverageprofit()){ System.out.printf("%.2f%s", profit[i], ", ");

COSC211: Introduction to Object Oriented Programming I }// end of if }// end of for loop }//end of method showprofitbelowaverage() }//end of class Profit (b) Create a test class that will instantiate the Profit class and display the required results with suitable headings and labels. public class ProfitTest{ public static void main(string args[]){ Profit profit = new Profit(); System.out.println("Ahmadu Bello " + "University Press"); System.out.printf("The total profits " + "gained is %.2f \n", profit.getsumofprofit()); System.out.print("The profits that " + "are below average are: "); profit.showprofitbelowaverage(); }//end of method main }// end of class ProfitTest

First Semester Examinations June 2014 5. Examine the following code and answer the questions that follow. 1. //Order.java 2. /*An order is placed for a number of items, if 3. *the number is big enough a discount is allowed 4. 5. public class Order{ 6. private static final double UNIT_PRICE = 1000; 7. private static final double DISC_RATE = 0.05; 8. private static final int MIN_DISC_QUANT = 100; 9. 10. private int quantity; 11. 12. public Order(int quantity){ 13. setquantity(quantity) 14. }//end of constructor 15. 16. public getquantity(){ 17. return quantity; 18. }//end of method getquantity() 19. 20. public void setquantity(quantity){ 21. if (quantity < 0); 22. quantity = 0; 23. this.quantity = quantity; 24. }//end of method setquantity() 25. 26. public double calculatecost(){ 27. double totalcost = UNIT_PRICE * quantity; 28. 29. if (quantity >= MIN_DISC_QUANT){ 30. discount = totalcost * DISC_RATE; 31. totalcost -= discount; 32. }//end of selection structure 33. 34. }//end of method calculatecost() 35. }//end of class Order (a) There are eight lines containing errors that would be detected by the Java compiler. Identify them and rewrite the lines with the errors corrected.

COSC211: Introduction to Object Oriented Programming I Line 4: */ Line 6: private static final double UNIT_PRICE = 1000.0; Line 13: setquantity(quantity); Line 16: public int getquantity(); Line 20: public void setquantity(int quantity){ Line 21: if(quantity < 0) Line 30: double discount = totalcost * DISC_RATE; Line 33: return totalcost; (1½ each = 12 marks) (b) Define a tostring() method for the Order class that can be used to display the order details. Public String tostring(){ return String.format("Quantity: %4d\tCost: %,.2f", quantity, calculatecost()); } (c) Write an OrderTest class that will instantiate three objects from this class and display the order details. public class OrderTest( public static void main(string[] args){ Order order1 = new Order(20); Order order2 = new Order(100); Order order3 = new Order(120); System.out.println(order1); System.out.println(order2); System.out.println(order3); }//end of main() }//end of class OrderTest (3 + 3 marks)

First Semester Examinations June 2014 6. (a) Write an application that will prompt user the to enter the first term, common difference, and the number of terms of an arithmetic progression (AP). It should compute the nth term of the series and the sum of the first n terms. Your code should ensure that the number of terms, n, is positive. [Hint: use T n = a + (n 1)d, and S n = n(a + T n ), where a is the first term, n is the number of terms, d is the common difference, T n is the nth term of the series, and S n is the sum of the first n terms.] import java.util.scanner; public class Series{ public static void main(string args[]){ int n; double d; double a; double term; double sum; (½ mark) Scanner input = new Scanner(System.in); (½ mark) do{ System.out.print("Please enter the " + "number of terms: "); n = input.nextint(); }while (n < 0); System.out.print("Enter the first term: "); a = input.nextdouble(); System.out.print("Enter the common " + difference: "); d = input.nextdouble(); term = a + (n - 1) * d; sum = (n * (a + term)) / 2; System.out.printf("The sum of the " + series is : %.2f ", sum); }//end of main method }//end of class Series

COSC211: Introduction to Object Oriented Programming I 2 b b 4ac (b) A quadratic equation of the form ax 2 + bx + c = 0 has roots. 2a Write a fragment of code that efficiently determines the values of the roots (root1 and root2) of the given equation. Assume that all the variables have been declared as type double. Note that the roots are real and distinct, real and equal, or complex according to whether the discriminant (b 2 4ac) is positive, zero or negative, respectively. Format the output in the following ways (where root1 and root2 are the calculated roots of the equation). (i) The roots are real and distinct : root1, root2. (ii) The roots are real and equal: root1. (iii) The roots are complex. Note: the roots should not be displayed if they are complex. import java.util.scanner; public class Quadratic{ public static void main(string[] args){ double a; double b; double c; double root1,root2; (½ mark) Scanner input = new Scanner(System.in); (½ mark) System.out.print("Enter the value of a: "); a = input.nextdouble(); System.out.print("Enter the value of b: "); b = input.nextdouble(); System.out.print("Enter the value of c: "); c = input.nextdouble(); double disc = b * b - 4 * a * c;

First Semester Examinations June 2014 if (disc > 0){ root1 = (-b + Math.sqrt(disc)) / (2 * a); root2 = (-b - Math.sqrt(disc)) / (2 * a); System.out.printf("The roots are real " + "and distinct: %.2f, %.2f \n", root1, root2); }else if (disc == 0){ root1 = -b / (2 * a); System.out.printf("The roots are real " + "and equal: %.2f\n", root1); }else System.out.println("The roots are " + "complex"); }//end of main method }//end of class Quadratic