Monday, September 9, 2013

HOW JAVA IS PLATFORM INDEPENDENT

HOW JAVA IS PLATFORM INDEPENDENT ?

The developers of java have made compilers and java virtual machines(also known as JVM). The function of compiler is to convert the program written by the programmer in the syntax of java into byte-code. Though the programmers don't have to do anything with the byte-codes so produced by the compilers, but for the sake of general knowledge, the programmer must know that it is the compilers which are platform dependent. You must have noticed while downloading java-sdk kit from the oracle website. The website provides different kinds of compilers for different platforms such as windows, LINUX, UNIX, Machintosh. So, this means java developers bore this extra responsibility of writing different compilers for different platforms, so that you can both write and run a java program on any platform. All you need to worry about is just learning the syntax of java. 

2nd PHASE AFTER BYTE-CODE FORMATION

When compilers perform their part of converting a program written in java to the byte-code, then this byte-code is fed to JVM(Java Virtual Machine) whose function is work on the byte-code and to convert it into such a form which can be understood by the computer hardware or the underlying machine. This form is referred as machine language. Java developers also take care to develop different JVM for different machines. So that your program written in java could run on any hardware. Your computer manufacturer could be any company such as Sony, Samsung, Lenovo, ASUS, etc. So there are JVMs available for all different machines.
The appropriate compilers and JVMs makes life easier for the programmers who write code in java and want their code to run everywhere irrespective of different platforms.
These striking features of java made the founders of java to raise the slogan :
                   "Write once run anywhere"

Friday, September 6, 2013

ACCESS MODIFIERS IN JAVA

WHAT ARE ACCESS MODIFIERS IN JAVA ?

Access modifiers are the special keywords which when applied provide different types of access to the content of the class. By content I mean, the data members/ fields and methods defined in the class. There might come situations where we don't want other classes to access the fields or methods or the class and some situations where we want all the elements of the class to be accessed by any other class.
Therefore, to provide different kinds of access for different kind of situations, Java has Access Modifiers, there are 3 kind of Access Modifiers :
1. public
2. private
3. protected

WHEN 'public' ACCESS MODIFIER IS USED :





DIFFERENCE BETWEEN METHOD OVERRIDING AND METHOD HIDING

METHOD OVERRIDING

When an instance method is written again with the same name, same number and type of parameters and same return type, in the sub-class as that of the parent-class/super-class, then this phenomenon is called as method overriding.

METHOD HIDING

It occurs in case of class-methods( also popularly known as static methods ). When any static-method is written again with the same name, same number and type of parameters and same return type, in the sub-class as that of the parent / super-class, then this phenomenon is called as method hiding.


Thursday, September 5, 2013

INTRODUCTION TO INHERITANCE IN JAVA

INHERITANCE

The concept of inheritance much more similar as in the real world itself. Inheritance means the passing of similar traits and features from older ones to younger ones. This same concept is taken from the real life and applied in the object oriented principles of programming languages too.
Necessity is the mother of invention fits better here, as in the earlier days of programming when there was no inheritance at all, programmers have to rewrite whole of the complex methods again and again which they wrote earlier in some other programme. They felt very exhausted writing these common but complex methods again and again whenever they have to write new code. They started to think of ways :
1. what if they introduce some way , by which they could be able to use previously written methods from previously written codes.
2. what if they find a solution to introduce a link among different piece of codes.
These necessities gave birth to the concept of inheritance.
With the advent of inheritance , the above problems found solutions. Now, if some code has to re-use the previously written methods and fields in some other code, it just inherits all of them by just writing a keyword 'extends'.

The programming life has become much easier with the introduction of inheritance. Java allows only single inheritance, though some other programming languages allow multiple inheritance too(e.g. C++ ).

Single inheritance

when a class can inherit only one other class i.e. having only one parent class. This kind inheritance is called Single inheritance.

Multiple inheritance

when a class inherits more than one class i.e. having multiple parent classes. This kind of inheritance is calles Multiple inheritance.

e.g.

public class Vehicle {
int numOfWheels;
int topSpeed;
int engineCapacity;
int gears;
void shiftGear(int gear) {
/ / / / /
/ / /
}
void speedUpBy(int mark){
/ / / / /
 / / /
}
}

public class Motorbike extends Vehicle{
int seats;
int mileage;
void start() {
/ / / /
/ / /
}
void stop() {
/ / / /
/ / /
}
}

We can clearly see in above example, that Motorbike class extends Vehicle class in its first statement, by doing this, the Motorbike class is able to inherit all the features of Vehicle class, without having it to write all those methods again. This is how inheritance makes the coding easier than before.
Here the Motorbike class is called subclass. 
The Vehicle class is called superclass.


SUB-CLASS

The class that is derived from the another class is called as sub-class (also called as child-class, derived class or extended class).

SUPER-CLASS

The class from which sub-class is derived is called as super-class ( also called as a base-class or a parent class ).


NOTE : there exist

DIFFERENCES AND SIMILARITIES BETWEEN INTERFACES AND ABSTRACT CLASSES

DIFFERENCES BETWEEN INTERFACES AND ABSTRACT CLASSES

Here I have compiled the points of both interfaces and abstract classes, and presented them in the image form . So, that anybody can save it and make it as his/her wallpaper, which enables to see it regularly and revise it.


Wednesday, September 4, 2013

SOLVING ANY PROBLEM FROM THE OBJECT ORIENTED POINT OF VIEW

 Objective: Analysis of the following Case Study from the perspective of Object Oriented Approach


Problem Description: Course Registration System



A Course Registration System needs to be developed for an engineering college. The college wants an automated system to replace its manual system for the purpose of registration of students to branches and calculation of fees for each year. The engineering college provides graduation courses in various branches of engineering.
The system will be used by the admin staff to register students, admitted to the college to the branches, at the time of joining the college and also to calculate the yearly fees for the students. The student has to register every year for the next academic year. The Admin takes care of the yearly registration of the students and the calculation of yearly fees. The system needs to be authenticated with a login id and password.
Registration of a student to a branch is based on the qualifying exam marks and the entrance counseling. For every branch, a yearly branch fee is applicable. Discounts are given to the branch fees of the first year based on the qualifying exam marks. In addition to this, there is a registration fee which is applicable to the first year students. Students can opt to be a day scholar or hostelite. Annual bus fee is applicable to the day scholars based on the distance they travel. Annual hostel fee is applicable for all the hostelites. Annual infrastructure fees and library fee is also applicable to all the students. Admin calculates the yearly college fees for each student and the college fees include all the fees specified earlier based on the type of student. Admin will provide a printed receipt of the fees to the students once the annual college fees have been paid. At the time of registration, student has to provide the permanent address and in case the student is opting to be a day scholar, he/she has to provide the residential address also.

SOLUTION :

Now, after thorough reading the above problem, we need to extract some crucial points, without writing them into sentences again, because those points will take us closer to the object oriented design phase. 
Lets get started :

Step 1 :
First of all we need to extract the purpose from the whole description  given above in just few points, as it will enable us to have a clear cut target. So the purpose of above long description is as follows :

1.  Registration of the students to the available branches.
2. Calculation of annual fees.


Step 2 :
Since, we are seeing the problem from the object oriented point of view, therefore, we need to make out what kind of actors / entities / objects are involved in our problem.

The whole problem revolves around one important object and i.e. 'Student'.

So, 'Student' can be seen as an actor or entity  or an object .

Tuesday, September 3, 2013

TOPIC 3 : INTRODUCTION TO DATA STRUCTURES

3.1 Data structures - Stack

Assignment 3.1.1: Application of Stack Data Structure


Objective: To understand how to apply Stack Data Structure.


Problem Description: Write a pseudo code to find the binary value of a given integer and 
display it.
Hint: Consider the integer 5. To convert 5 to binary, the following procedure needs to be 
adopted.



               2|_5____

               2|_2_-_1_

                   _1__- 0_





Each time, store the remainder in an appropriate data structure and use LIFO to get the 

binary value.

TOPIC 2: LOGIC BUILDING USING PSEUDO CODE part-3

2.3 Iteration Control Structures

Assignment 2.3.1 Pseudo code - Iterational pattern (1)


Objective: Write pseudo code for iterational pattern problems.

Problem 1 :

The problem given in Assignment 2.1.2 is extended to check whether 
the Number of Hours accepted from the user is less than or equal to 0. If so display an error 

message. Reenter the data the Number of Hours until valid data is entered.




Step 1: Write the following Pseudo code

CALC_GROSS_PAY
1. input No_of_Hours, Pay_Rate
2. while(------------) do
3. display "---------------------"
4. -------------------------------------
5. end while
6. Gross_Pay =  No_of_Hours * Pay_Rate
7. display " The gross pay is equal to : ", Gross_Pay
8. end

Step 2 : Fill in the missing (------) parts in the Pseudo code
We need to put a condition in the parenthesis of while ( ) loop, which could test the validity of the data input by the user for the number of hours. We need to keep the loop running displaying a message as long as the condition in the parenthesis remains true. Therefore the complete form the above pseudocode is given as :



CALC_GROSS_PAY
1. input No_of_Hours, Pay_Rate
2. while(No_of_Hours < = 0) do
3. display "Invalid Entry, Enter Valid Number of hours. "
4. input No_of_Hours
5. end while
6. Gross_Pay =  No_of_Hours * Pay_Rate
7. display " The gross pay is equal to : ", Gross_Pay
8. end


Problem 2 :
Write a pseudo code to calculate the Loan Balance, where a person borrows an amount A and in return he/she agrees to make N payments per year, each of amount P. While the person is repaying the loan, interest will accumulate at an annual percentage rate of R, and this interest will be compounded N times a year (along with each payment). Therefore, the person must continue paying these installments of amount P until the original amount and any accumulated interest is repaid.

NOTE: The formula to calculate the amount that the person needs to repay after T years is :

Balance amount after T years = 

TOPIC 2: LOGIC BUILDING USING PSEUDO CODE

2.2 Selection Control Structures


Assignment 2.2.1: Pseudo code - Selectional pattern (1)


Objective: Write pseudo code for selectional pattern problems

Problem Description: The problem given in Assignment 2.1.2 should be extended to check whether the Number of Hours accepted from the user is less than or equal to 0. If so an appropriate error message should be displayed.

The problem given in assignment 2.1.2 is here.
The pseudo-code with required changes can be written again as :


Calculate-Gross-Pay

1. input No_of_Hours, Pay_Rate

2. if  No_of_Hours < = 0 then
3. Display " The Number of hours are invalid."
4. else
5. Gross_Pay = No_of_Hours * Pay_Rate
6. Display "Gross Pay is : ", Gross_Pay
7. end



Assignment 2.2.2: Selectional pattern (2)

Objective: To develop pseudo code writing skills for a given problem using certain logic.

Case study: An institution offers several programs. Each program has several courses. There 
are students who have opted for these courses. There are Educators who offer these courses.



Problem 1:
At a given point of time we need to allocate a course to an educator for a given
period. Before allocating a course to an educator the following conditions are to be checked.
1. Enough number of students have registered for the course
AND
2. The course is added into the educator’s skill set
AND
3. Educator’s calendar is free for the given period
AND
4. Educator is not on leave for the given period
And
5. Educator has not yet completed his delivery targets Or There is no other alternative

SOLUTION :

COURSE_ALLOCATION
1. input course
2. input num_of_students
3. input educator's_skill_set, spare_time, is_on_leave, delivered_targets, allocation
4. if ( (num_of_students > min_number_students) && (educator's_skill_set = course) && (spare_time = true ) && (is_on_leave = false) && (delivered_targets = true ) ) then
5. set allocation = true
6. end if
7. display "Course is allocated. "
8. end


Problem 2: For a student, following is the course qualifying criteria.
1. Student has registered for the course
2. Attended at-least 80% of the classes
or attended at-least 60% of the classes and submitted medically unfit certificate
3. Submitted all the assignments
4. Completed project
5. Scored 80% marks in the test or the retest

QUALIFYING_STUDENT
1. input classes_attended, min_score
2. input course_reg, medical_certificate, submitted_assignments, completed_project
3. if ( ( course_reg = true ) &&(classes_attended >= 80 || (classes_attended >= 60 && medical_certificate = true ) ) && (submitted_assignments = true ) && (completed_project = true) && ( min_score >= 80)) then
4. set course_qualification = true
5. end if
6. display "Congratulations, course has been qualified. "
7. end 



Assignment 2.2.3: Selectional pattern (3)


Objective: To use the problem solving techniques learnt so far in a real life application.

Problem 1: Take marks of a trainee in a module as input and calculate the grade and
grade points. The grade table is given below:




SOLUTION :

CALC_GRADE
1. input marks_obtained
2. if ( marks_obtained >= 80 ) then
3. grade_point = 5
4. grade = A
5. elseif ( marks_obtained >= 73 && marks_obtained <=79 ) then
6. grade_point = 4.5
7.  grade = B+
8. elseif ( marks_obtained >= 65 && marks_obtained <=72 ) then
9. grade_point = 4
10. grade = B
11. elseif ( marks_obtained >= 55 && marks_obtained <=64 ) then
12. grade_point = 3
13. grade = C
14. elseif ( marks_obtained >= 0 && marks_obtained <=54 ) then
15. grade_point = 2
16. grade = D
17. end if
18. display " The grade points obtained are equal to: ", grade_point
19. display " The grade awarded is : ", grade
20. end


Problem 2 :
Take marks of a trainee in all generic modules (listed below)as input and calculate the
Generic GPA. The method for calculating Generic GPA is as follows:


Grade points for marks are given in previous problem and credit points are as follows:





SOLUTION :

CALC_GPA
1. input marks_obtained
2. if ( marks_obtained >= 80 ) then
3. grade_point = 5
4. grade = A
5. elseif ( marks_obtained >= 73 && marks_obtained <=79 ) then
6. grade_point = 4.5
7.  grade = B+
8. elseif ( marks_obtained >= 65 && marks_obtained <=72 ) then
9. grade_point = 4
10. grade = B
11. elseif ( marks_obtained >= 55 && marks_obtained <=64 ) then
12. grade_point = 3
13. grade = C
14. elseif ( marks_obtained >= 0 && marks_obtained <=54 ) then
15. grade_point = 2
16. grade = D
17. end if
18 GPA = ( marks_obtained * grade_point ) / marks_obtained
19. display " The grade points are : ", grade_point
20. display " The GPA obtained : ", GPA
21. end

PSEUDO-CODES IN PROGRAMMING

WHAT ARE PSEUDO-CODES ?

The pseudo- code is step by step representation written in plain english of an algorithm, which can be perceived as the initial stage of formal coding. Instead of directly digging upon the proper code, it is preferred to write pseudocode to get an essence of the logic applied in the algorithm.

Some of the conventions, keywords etc. followed while writing a pseudo-code are as follows :
1. 'input' keyword is used to take the input from the user.
2. 'display' keyword is used to show the result.
3. Mathematical expressions are used as we do normally.
4. For decision making constructs, 'if' , 'then', 'else' , 'else if' keywords are used.
5. When some statements are to be repeated for a known number of times, 'for', 'to', 'do', 'end for' keywords are used.
6. When some statements are to be repeated as long as some condition remains true then , 'while', 'end while' keywords are used.


TYPES OF PSEUDO-CODES

1. SEQUENTIAL PATTERN ( the statements are executed in the same order as it is written)

2. SELECTIONAL PATTERN ( they involve decision making situations )

3. ITERATIONAL PATTERN ( they involve repitition of the statements )


Monday, September 2, 2013

TOPIC 2: LOGIC BUILDING USING PSEUDO CODE

2.1 Flowchart and Pseudo Code


Assignment 2.1.2: Pseudo code- Sequential pattern


Objective: Writing pseudo code for sequence pattern problems

Problem Description: The finance department of a company wants to calculate the gross pay of an employee in the company. The number of hours worked by the employee and the pay rate should be accepted from the user and the gross pay should be calculated as the below formula.

Calculate-Gross-Pay
1. input No_of_Hours, Pay_Rate
2. Gross_Pay = No_of_Hours * Pay_Rate
3. Display "Gross Pay is : ", Gross_Pay

The above given set of statements represents a pseudo code, which can be perceived as the initial stage of formal coding. It represents a step by step approach to solve any problem in plain english, instead of formal syntax used in any particular programming language. 

There are few conventions which are followed while writing a pseudo code as :
1. use of keyword 'input', whenever data is retrieved from the user
2. use of keyword 'display', whenever result is to be displayed
3. Mathematical expressions are used as it is, as we normally use them.
4. if, then, else, end if keywords are used for decision making situations
5. for, to , do , end for keywords are used when  certain steps are to repeated for a known number of times.
6.while, end while keywords are used when some of the steps are to repeated as long as certain condition remains true.


Assignment 2.1.3: Understanding Variables & Constants


Problem 1 :

Write a pseudo code to take the height of the building in variable 
“Building_Height” and display the same.





SOLUTION :

DISP_HEIGHT
1. input Building_Height
2.display "The height of the building is : ", Buildiing_height
3. end


Problem 2 :
Write a pseudo code to take the constant value 3.142 in a variable “pi” and
display the same.

SOLUTION :

DISP_PI
1. input pi = 3.142
2. display "The value assigned to pi is : " pi
3. end


Assignment 2.1.4: Understanding Operators


Problem 1 : 
Write a pseudo code to take two numbers as input in variables a and b and display
i. Product of the two numbers a and b
ii. Sum of the two numbers a and b
iii. Values of a-b and b-a
iv. Quotient and remainder for a/b and b/a

SOLUTION :

i ) 
PROD_OF_TWO_NUM
1. input a, b
2. Product = a * b
3. Display " The product of 'a' and 'b' is: ", Product
4. end

ii)
SUM_OF_TWO_NUM
1. input a, b
2. Sum = a  + b
3. Display " The sum of 'a' and 'b' is : ", Sum
4. end

iii)
DIFFERENCE_BETWEEN
1. input a, b
2. Diff_A_and_B = a - b
3. Diff_B_and_A = b-a
4. Display "the difference of 'a' and 'b' is : ", Diff_A_and_B
5. Display "the difference of 'a' and 'b' is : ", Diff_B_and_A
6. end

iv) 
QUOTIENT_REM
1. input a, b
2. Quo_A_by_B = a / b
3. Rem_A_by_B = a % b
4. Quo_B_by_A = b / a
5. Rem_B_by_A = b % a
6. Display "the quotient of 'a' by 'b' is : ", Quo_A_by_B
7. Display "the quotient of 'b' by 'a' is : ", Quo_B_by_A
8. Display "the remainder from 'a' by 'b' is : ", Rem_A_by_B
9. Display "the remainder from 'b' by 'a' is : ", Rem_B_by_A
10. end


Problem 2:

Write a pseudo code to take the height and width of a rectangle in variables

height and width respectively and display the rectangle's area and perimeter.

SOLUTION :

RECTANGLE_AREA_PERIMETER
1. input height, width
2. Area = height * width
3. Perimeter = 2*(height +width)
4. Display "The area of rectangle is : ", Area
5. Display "The perimeter of rectangle is : ", Perimeter
6. end


Problem 3:
Write a pseudo code to take the radius of a circle in variable radius and display

its area and perimeter.

SOLUTION :

CIRCLE_AREA_PERIMETER
1. input radius
2. Area = 22/7(radius * radius)
3. Perimeter = 2 *( 22/7) * radius
4. Display "The area of circle is : ", Area
5. Display "The perimeter of circle is : ", Perimeter
6. end


Problem 4:
Write a pseudo code to take the starting value, common difference and the
number of terms of an arithmetic progression in variables a, d and n respectively and display its nth term and sum of n terms.

SOLUTION :

ARITHMETIC_PROGRESSION
1. input a, d, n
2. Nth_term = a+((n-1)*d)
3. Sum_of_terms = (n/2)*((2*a)+((n-1)*d))
4. Display " The nth term is : ", Nth_term
5. Display "The sum of terms is : ", Sum_of_terms
6. end


Problem 5:
Write a pseudo code to take the radius of the sphere in variable radius and

display the volume of the sphere.

SOLUTION :

VOLUME_OF_SPHERE
1. input radius
2. Volume = (4/3)*3.14*(radius*radius*radius)
3. Display " The volume of the sphere is  : ", Volume
4. end




FLOWCHARTS IN PROGRAMMING

WHAT ARE FLOWCHARTS ?

Flowcharts are graphical means of representing the logic to solve any computational problem.
It is a pictorial way and hence give more intense understanding of the solution for the problem at hand.It consist of some symbols which forms its tools to make a complete structure for any problem.

These symbols are : 
 
Flowchart Symbols


An example to show a perfect flowchart :


Flowchart to check whether a number is prime or not


Wednesday, August 28, 2013

TOPIC 2: LOGIC BUILDING USING PSEUDO CODE

2.1 Flowchart and Pseudo Code

Assignment 2.1.1: Problem Solving through flowchart

Problem Description: Draw a flowchart for the following problems:

1. Add first N even numbers

SOLUTION : 


flowchart to show addition of first 'n' even numbers


2.   Add first n odd numbers

SOLUTION :


Flowchart showing addition of first 'n' odd numbers


3.  Find maximum of three numbers

SOLUTION :


Flowchart showing maximum of three numbers


4. Determine whether a year s leap year or not

SOLUTION :


Flowchart showing whether a year is leap year or not

5. Input a number and check whether it is prime or not

SOLUTION :


Flowchart showing whether a number is prime or not


6. Input a number and check whether it can be expressed as some positive integer power of 2. For example 2,4,8,16,32… etc. can expressed as some positive integer power of 2 like 2^1,2^2,2^3,2^4, and 2^5……..

SOLUTION : 


Flowchart expressing a number as power of 2

Monday, August 26, 2013

INFOSYS FOUNDATION TRAINING PROGRAM (FTP) SOLUTION FOR LAB-GUIDE ASSIGNMENT PROBLEM SOLVING AND LOGIC BUILDING- part-2

TOPIC 1 : COMPUTATIONAL PROBLEM SOLVING

1.1 COMPUTATIONAL PROBLEM SOLVING AND ALGORITHM

ASSIGNMENT 1.1.1 : PROBLEM SOLVING EXERCISES ( part-b )


1. In an objective type programming contest, following are the rules

a. It will have multiple rounds.

b. In each round, every participant will get a set of 10 question out of which
one question is marked as star question (The toughest one).
c. The participant will get the next set, only if 50% of the questions are
marked correctly in the previous round or he attempted the star question
correctly. Otherwise he will be out of the contest.
It is found that in each round 50% of the participants are not able to attempt 50%
of the questions correctly but one out of those 50% participants, attempts the
star question correctly.
If only 4 participants are left for the 5th round what was the number of
participants in the first round?

SOLUTION :

Let the students appeared for 1st round be = x

Students appearing for the 2nd round :
Since half of them made for the 2nd round, which constitute = x / 2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are = x/ 2 + 1 = (x + 2)/ 2

Students appearing for the 3rd round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 2)/ 2 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 2)/ 4 ) + 1 = (x + 6)/ 4

Students appearing for 4th round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 6)/ 4 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 6)/ 8 ) + 1 = (x + 14)/ 8

Students appearing for 5th round :
Since half of the previous round students made for the 3rd round, which constitute = ( (x + 14)/ 8 )/2
and 1 candidate who attempted star question
So, total students who made for the 2nd round are =  ( (x + 14)/ 16 ) + 1 = (x + 30)/ 16


Since it is given that the number of students appeared for the 5th round are =  4

This implies the expression we got for the 5th round i.e. (x + 30)/ 16 becomes = 4
i.e.                                                   (x + 30)/ 16 = 4
                                                         (x + 30 ) = 64
                                                            x = 64 - 30
                                                               x = 34

Since we assumed ' x ' to be the number of students present during the 1st round, which came out to be = 34. It means there were total of 34 students present in the 1st round.


2. A farmer had a lazy son. The farmer wanted his son to work in the farm. So he offered that the son will work for 50 days, for each day the son works, he will get 10 rupees, for each day he will not work, he need to pay back 15 rupees to his father. At the end of 50 days, when the son counted his income, it turned out that he had not got anything. How many days did the son actually worked?

SOLUTION :

Let the son worked for =  x days
money earned for x days = 10x

No. of days on which he didn't work = (50 - x)
Money he lost for days he didn't work = 15 ( 50 - x )

It is given in that the money he earned balances the money he paid back, which means :

                                                      10x = 15 ( 50 - x )
                                                       10x = 750 - 15x
                                                            25x = 750
                                                           x = 750/25
                                                              x = 30
Since we assumed ' x ' to be the number of days for which son worked, which came out to be = 30 days. Therefore, Son worked for 30 days.

INFOSYS FOUNDATION TRAINING PROGRAM (FTP) SOLUTION FOR LAB-GUIDE ASSIGNMENT PROBLEM SOLVING AND LOGIC BUILDING

TOPIC 1 : COMPUTATIONAL PROBLEM SOLVING

1.1 COMPUTATIONAL PROBLEM SOLVING AND ALGORITHM

ASSIGNMENT 1.1.1 : PROBLEM SOLVING EXERCISES

1 . The King ordered his servants to fill up his treasury. Each of the 3 servants, had to go to the treasury, count how much gold coins there was at that moment, and then triple it and leave. But then the King felt sorry for them and thought that he should probably reward the servants in some way, so he let each of them take 1 gold coin out before leaving. Once again the King had a good luck. He collected exactly 500 gold coins in the treasury. How much gold coins did he have before the order.

SOLUTION

Let initially coins be = x
a servant has to make thrice of them, which means, coins should be = 3x
and a servant is allowed to take 1 coin, which leave the total coins to =  ( 3x - 1 )

Next servant comes and does the same thing of making the count of coins to 3-times, which makes the present count to =                      3 ( 3x - 1 )
and when he take 1-coin out , then the present count becomes =  ( 3 ( 3x - 1 ) - 1 )

Finally the 3rd servant comes and make the present count to thrice again making it = 
3 ( 3 ( 3x - 1 ) - 1 )
and when he also takes 1-coin out, the total count becomes = ( 3 ( 3 ( 3x - 1 ) - 1 ) -1 )

At last, it was found that the total count of the coins = 500

which means our expression 3 ( 3 ( 3x - 1 ) - 1 ) -1 ) = 500

solving this expression step by step :
                                                  ( 3 ( 9x - 3 - 1) - 1 ) = 500
                                                    27x  - 12 - 1  = 500
                                                           27x -13 = 500
                                                             27x = 513
                                                             x = 513 / 27
                                                                x = 19
since ' x ' is the number of coins initially present in the treasury. It means 19 coins were initially present in the treasury.
                                                    

2. John decided to start working. He was hired on the following terms: during 30 days, for each day John works, he gets 6 dollars, for each day he doesn't work,he pays back 9 dollars. At the end of the month, when they counted his wages, it turned out that he had not got anything. How many days did John actually work?


SOLUTION :

Let the number of days for which Jhon worked be = x
This implies, the number days for which Jhon didn't work = 30 - x

Jhon gets 6 $ for each day he works
therefore, his total wages for his working days become = 6x

Jhon has to pay back 9 $ for the day he don't work
therefore, he has to pay back total of = 9( 30 - x )

Since Jhon gets nothing at the end of the month as the money he has to pay back balances the money he earned, which means : 

                                                              6x = 9( 30 - x )
                                                              6x = 270 - 9x
                                                                15x = 270
                                                                x = 270 / 15
                                                                   x = 18
Since, we assumed ' x ' to be the number of days for which Jhon worked, and it comes out to be 18 days for which Jhon worked for the company.
                                 


3. Smith's boss proposed to pay him in the following way: "See, there is some money in the purse. Every day I'll add 5 dollars to it, and then you'll take out half of what's in it”. Three days later it turned out that there were6 dollars left in the purse. How much did Smith get for three days' work ?

SOLUTION :

Let the amount of money present in the purse initially be = x
1st day The boss added 5 $ to the purse and the total amount becomes = x + 5
The employee took half of the total amount , which means, he took = ( x+ 5 ) / 2.............(i)
Money left behind in the purse = (x + 5 ) - ( x + 5 ) /2

2nd day The boss added 5 $ again to the purse, which makes the total amount present in the purse to   = 5 + ( x + 5 )/ 2  =  (10 + x + 5) / 2 =   ( x + 15 )/ 2
The employee took half of the amount present in the purse , which means, for this time, he took-
( x + 15 )/ 2*2 = ( x + 15 )/ 4................................(ii)
Money left behind in the purse = ( x + 15 )/ 2 -  ( x + 15 )/ 4 = ( x + 15 )/ 4

3rd day The boss added 5 $ again to the purse, which makes the total amount present in the purse to  = 5 + ( x + 15 )/ 4 = ( x + 35 ) / 4
The employee took half of the amount present in the purse , which means, for this time, he took-
( x + 35 ) / 4 *2 = ( x + 35 ) / 8..............................(iii)
Money left behind in the purse =  ( x + 35 ) / 4 - ( x + 35 ) / 8 = ( x + 35 ) / 8

Since money left in the purse on 3rd day = ( x + 35 ) / 8
and it is given that on 3rd day money present in the purse = 6 $
which means :
                                                           ( x + 35 ) / 8 = 6
                                                               x + 35 = 48
                                                                    x = 13

Since, we assumed ' x ' as the money present in the purse initially, which means there were 13 $ present in the purse initially.

We've to find out the amount earned by the employee on 3rd day, which we can calculate by adding (i), (ii) and (iii) expressions above  as :

                           ( ( x+ 5 ) / 2 )   +   ( ( x + 15 )/ 4 )      +    ( ( x + 35 ) / 8 )
Putting 13 in place of x, we get the expression as :
                           ( ( 13 + 5 ) / 2 ) +  ( ( 13 + 15 ) / 4)   +   ( ( 13 + 35 ) / 8) 
                                       ( 18/ 2 )   +      (28 / 4 )    +     (48 / 8 )
                                                             9 +  7 +  6
                                                                   22


This implies the total of 22 $ earned by the employee. and If we see the amount only for 3rd day, it comes out to be : ( x + 35 ) / 8 =  ( 13 + 35 ) / 8  =    (48 / 8 )  =    6


4. Two friends who have an eight-quart jug of water wish to share it evenly. They also have two empty jars, one holding five quarts, the other three. How can they each measure exactly 4 quarts of water ?

SOLUTION : 

Step-1:
First of all water from 8-quart jug is poured into 3-quart jar, so now the values are :
8-quart jug = 5-quart water
3-quart jar = 3-quart water
5-quart jar = 0-quart water

Step-2 :
Now, water from 3-quart jar is poured into 5-quart jar, so now the values are :
8-quart jug = 5-quart water
3-quart jar = 0-quart water
5-quart jar = 3-quart water

Step-3:
Now again, water from 8 quart jug is poured into 3-quart jar, so now the values are :
8-quart jug = 2-quart water
3-quart jar = 3-quart water
5-quart jar = 3-quart water

Step-4:
Now, water from 3-quart jar is poured into 5-quart jar, Notice this time, since the 5-quart jar is left with only 2-quarts of capacity, therefore, 3-quart jar will be able to pour only 2-quarts of water, leaving 1-quart behind. So now the values are :
8-quart jug = 2-quart water
3-quart jar = 1-quart water
5-quart jar = 5-quart water

Step-5:
Now, the whole of water from 5-quart jar is poured back into 8-quart jug, which will set the values to :
8-quart jug = 7-quart water
3-quart jar = 1-quart water
5-quart jar = 0-quart water

Step-6:
Now, pour the water from 3-quart jar into 5-quart jar, making the values to :
8-quart jug = 7-quart water
3-quart jar = 0-quart water
5-quart jar = 1-quart water

Step-7:
Now again, fill the 3-quart jar by pouring water from 8-quart jug, making the values to :
8-quart jug = 4-quart water
3-quart jar = 3-quart water
5-quart jar = 1-quart water

Step-8:
Now, fill this 3-quart of water from 3-quart jar to 5-quart jar, and see it yourself that we have successfully divided  8-quarts of water into equal halves, so that both friends can get exactly 4-quarts of water. And the values can finally be seen as :
8-quart jug = 1-quart water
3-quart jar = 3-quart water
5-quart jar = 4-quart water 


5. The bin packing problem is an example of a wide set of problems. The task is to find how many set sized bins are required to hold a number of differently sized boxes. How many bins (10 units high) are required to contain the following boxes (1,3,4 and 5 units high) ?

SOLUTION :

Since, we've to put 1,3,4 and 5 units high boxes into 10 units high bins.
As can be seen, we can put 
1.)      1,4 and 5 units high boxes into 10 units high bin( all these boxes completely fit into bin w/o leaving any space behind )
2.)   Now we're left with only 3 unit high  box, which we've to put it into another 10 unit high bin, as we've no other option.

Friday, August 23, 2013

PACKAGES IN JAVA

WHAT ARE PACKAGES IN JAVA ?

When making any project in java, the project may constitute large number of classes and interfaces which are assigned to different development teams to code them. They place classes and interfaces having same category into packages. Packages are nothing but named directory /folder, where programmers keep classes and interfaces of same functionality.
e.g.
Suppose, you've made different classes such as :
Lion
Tiger
Peacock
Vulture
Car
Bus
We can easily sense some kind of similarities among certain classes, such as:
Lion and Tiger are ANIMALS
Peacock and Vulture are BIRDS 
Car and Bus are VEHICLES
Instead of keeping all these classes together, we would surely like to categorize classes of similar types together for well organization.
Therefore, we would put classes Lion and Tiger in ANIMAL PACKAGE.
Peacock and Vulture in BIRDS PACKAGE
Car and Bus in VEHICLES PACKAGE


HOW DO WE CREATE PACKAGE IN JAVA ?

When we create a class, we start by writing e.g.

public class <name_of_class> {
Data Members
/ / / / / / / / / / 
/ / / / / / / / / 
Methods
/ / / / / / / / / 
 / / / / / / / 
}

So, we want the above class to belong to some package, we just have to write the 'package' keyword with a appropriate name given to that package as the first line of the program.

e.g.

package  <name_of_package>;
public class <name_of_class> {
Data Members
/ / / / / / / / / / 
/ / / / / / / / / 
Methods
/ / / / / / / / / 
 / / / / / / / 
}

NOTE : if we want our class to belong to some package, then we must begin our program with the package keyword and the name of the package as 1st line of the program.
By doing this, a directory / folder gets created of the same name as that of package, in which our class get stored.

WHAT ARE SUB-PACKAGES IN JAVA ?

As name itself indicates, it is just another package inside the package.Lets take a scenario to understand the concept of sub-packages. Suppose we created a package called ANIMALS
and we have made classes such as :
Lion
Tiger
Peacock
Eagle
Salmon
Shark
It is absolutely clear that all the above classes are animals, but, if we look further, then we can sense that:
Lion and Tiger are NON-FLYING ANIMALS
Peacock and Eagle are FLYING ANIMALS
Salmon and Shark are SEA ANIMALS
Therefore, there arises a need to categorize them further. In-order to deal with this situation we need to put them in packages further, and all these newly formed packages will go into ANIMAL PACKAGE.

Now, ANIMAL PACKAGE Contains 3 SUB-PACKAGES namely :
NON-FLYING ANIMALS ( containing classes : Lion and Tiger )
FLYING ANIMALS ( containing classes : Peacock and Eagle )
SEA ANIMALS ( containing classes : Salmon and Shark )

HOW DO WE CREATE SUB-PACKAGES IN JAVA ?

Suppose we have classes Tiger and Eagle. We know that both of these are animals, but at the same time both belong to a different category. Tiger belongs to Non flying category and Eagle belongs to Flying category. So, we need to put these classes into different sub-packages, and to do that, we begin the class code with 'package' keyword then name of the package then period(a dot) then the name of the sub-package. 
e.g.

package animals.non_flying_animals;
public class Tiger {
/ / / / /
 / / / 
}
By doing so, the class Tiger will get stored in directory / folder structure:  animals / flying_animals

To put Eagle class in another sub-package, we would insert tha package statement as :

package animals.flying_animals;
public class Eagle {
/ / / / /
 / / / 
}

By doing so, the class Eagle will get stored in directory / folder structure as :
animals / flying_animals

NOTE : i) the name of the package should start with a small case.
ii) the name must not contain blank spaces in between as in 'non flying animals', rather it should be written as 'non_flying_animals'.