Quick viewing(Text Mode)

5D47e9af2f12a4ca1cbd111b5a9

5D47e9af2f12a4ca1cbd111b5a9

https://www.arundeepselfhelp.info

Contents

1. Revision of Class IX Syllabus 1—83

Unit I : Introduction to Object Oriented Programming Concepts 1–4

Unit II : Elementary Concept of Objects and Classes 4–6

Unit III : Values and Data Types 7–10

Unit IV : Operators in Java 11–17

Unit V (a) : Introduction to Java 17–20

Unit V (b) : Input in Java 20–26

Unit VI : Mathematical Library Methods 27–31

Unit VII : Conditional Statements in Java 31–46

Unit VIII : Iterative Constructs in Java 47–67

Unit IX : Nested Loop 67–83

2. Library Classes 84—95

3. Arrays (Single Dimensional and Double Dimensional) 96—121

4. String Handling 122—160

5. User- Defined Methods 161—193

6. Class as the Basis of all Computation 194—223 (Objects and Classes) https://www.arundeepselfhelp.info

7. Constructors 224—245

8. Encapsulation and Inheritance 246—256

Specimen Paper 2020 (Solved) 257—267

ICSE Board Paper 2019 (Solved) 268—276 https://www.arundeepselfhelp.info

Revision of Class IX syllabus Chapter 1 UNIT 1 Unit I : Introduction to Object Oriented Programming Concepts

EXERCISES I. Tick the correct option: 1. In object oriented programming, the stress is given on: (a) procedure (b) methods (c) class (d) data 2. Which of the following principle does not allow to access directly from outside the class premises: (a) data hiding (b) encapsulation (c) abstraction (d) all of the above 3. The process of combining data and functions that enables them to be together as a single entity is called: (a) inheritance (b) encapsulation (c) classification (d) attributes 4. The process by which a class acquires the properties from another class is called: (a) polymorphism (b) inheritance (c) abstraction (d) object 5. In procedural programming, the stress is laid on: (a) class (b) function (c) data (d) object 6. A ...... is a set of objects that has common attributes and common behavior. (a) abstraction (b) encapsulation (c) class (d) function 7. Which of the following is not an object oriented programming language? (a) C++ (b) Simula (c) BASIC (d) Java 8. The process of restricting the free flow of data from the outside world is known as: (a) encapsulation (b) inheritance (c) function (d) class Ans. 1. data 2. all of the above 3. encapsulation 4. inheritance 5. function 6. class 7. BASIC 8. encapsulation II. Fill in the blanks : 1...... is the fundamental concept in object oriented programming language. 2. Objects can communicate with each other through ...... in object oriented programming language. 3. Using a function for multiple operations is called as ...... 4...... is an act of representing essential features without including background details.

CHAPTER-1 1 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

5. Feature of wrapping ...... and ...... as a single unit is called encapsulation. 6...... principle of object oriented programming promotes reusability feature. Ans. 1. Object 2. function 3. polymorphism 4. data abstraction 5. data and function 6. inheritance III. Write short answers: 1. What is Object Oriented Programming? Name two Object Oriented Programming languages. Ans. (i) OOP is a modular approach which allows the data to be applied within stipulated program area. Under this system, the emphasis is on data rather than on functions to develop productive logic. (ii) Java,Python 2. Name four basic principles of Object OrientedProgramming. Ans. Data abstraction, Polymorphism, Inheritance, Encapsulation. 3. Why do we prefer Object Oriented approach in complex programming? Explain. Ans. OOP does not allow data to flow freely from one function to another. In this system, the complete problem is divided into a number of entities called objects. Each object includes a set of data items and related functions. The data values of an object are applicable only within the functions associated with that object. The resident data can never be handled by external functions. In this way, the data are protected and secured from being hampered by external sources and this allows Object Oriented feature to be a powerful tool for programming. 4. What is meant by a base class and a derived class? Ans. (i) The class from which other classes are derived through the process of inheritance is called base class or superclass. (ii) The class that inherits properties from a base class is called a derived class. 5. Mention two limitations of Procedure Oriented Programming approach. Ans. (i) No restriction on data values. (ii) Causes problems for the programmers while debugging. 6. What is meant by encapsulation? [ICSE 2006] Ans. Encapsulation is the wrapping of data and functions of a class together so that they can be applied as a single unit to perform any operation.

CHAPTER-1 2 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

7. Define the following with an example each. (a)Inheritance (b) Polymorphism [ICSE 2008] Ans. (a) Inheritance – It is an OOP principle according to which one class acquires the features of another class.With the help of inheritance, the components in the Base class can be reused to perform some other task in the Derived class (reusability). Example: A Car class(subclass) inherits the attributes and methods from the Vehicle class (superclass) (b) Polymorphism – Polymorphism is the process of using a function for more than one purpose. It allows the use of different internal structures of the object by keeping the same external interface. Example: Suppose you have a smartphone for communication. The communication mode that you choose can be anything. It can be a call, a text message , a picture message, an email etc. So the goal is common i.e. communication but the approach is different. This is called polymorphism. 8. In what way is Data Hiding related to Data Abstraction? Ans. The insulation of data that does not allow it to be accessed directly outside the class premises although it is available in the same program is known as data hiding. Data abstraction refers to an act of representing the essential features without including the background details. 9. Give an example to explain Data Abstraction. [ICSE 2018] Ans. We need not know the detailed internal mechanism in order to use a device. For example, in a switch board we only have to press certain switches according to our requirement. We do not need to know the working of the internal circuit etc. Likewise, data abstraction allows us to use the essential features by hiding the background details. 10. What is meant by Data Hiding? Ans. Data hiding refers to the insulation of data that does not allow it to be accessed directly outside the class premises although it is available in the same program. 11. Which of the Object-Oriented programming principles explain the following illustrations? Justify. (a) The variables and methods are put together in a Class.

CHAPTER-1 3 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(b) A man withdrawing money from ATM.

Ans. Fig a- Encapsulation – Since the variables and methods are put together (wrapped) as a single unit. Fig b- Data abstraction – Since the details of internal operation of the ATM is hidden from the user. Unit II : Elementary Concept of Objects and Classes

EXERCISES I. Fill in the blanks : 1. Creating ...... is the fundamental concept in object oriented programming language. 2. A class is also considered as an ...... factory. 3. A real world object deals with characteristics and ...... 4. The ...... of a class differs on various characteristics. 5. The characteristics of the...... objects are considered to be the data members of the ...... objects. 6. An object of a class is created by using a keyword ...... 7. Class is a ...... of the objects. 8...... keyword is used for dynamic allocation of an object. 9. The living things are considered as...... objects. 10. The different ...... of a class have common behaviours. Answer. 1. object 2. object 3. behaviours 4. object 5. real world, software 6. new 7. blueprint 8. new 9. realworld 10. objects II. Answer the following questions : 1. How will you define a software object? Ans. An object is a unique entity that contains data and functions together in an Object-Oriented Programming language.

CHAPTER-1 4 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

2. Define class and object with an example. Ans. Class – It is a blueprint or prototype of an object. It is known as the ‘Object factory’ because it produces the objects of similar type. Object - It is a unique entity having some characteristics and behaviours. It is known as the ‘Instance of a Class’. Example- For example if we define a class called ‘Fruits’, then different types of fruits (Banana, Apple, Pear) are referred as Objects under that Category. It means that the different types of fruits are similar objects belonging to the class ‘Fruits’. 3. What does the following statement mean? [ICSE 2008] Employee staff = new Employee ( ); Ans. The above statement means that ‘staff’ is an object of the ‘Employee’ class. 4. A class is also referred to as ‘Object Factory’. Comment. [ICSE-2009] Ans.  A factory has a blue print of the article based on which it creates replicas of the article.  Similarly, a class is the blue print from which the individual objects are created.  Class is composed of three things – name, attribute, operations  Each object belonging to a specific class contains the attributes and functions mentioned within the class.  Since a class produces objects of similar type, it is referred to as an object factory. 5. Why is a class known as composite data type? Ans. Users can create a data type with the help of a class. It may contain data values of various types such as String, , float, double, boolean etc. That is why a class is said to be a composite data type. 6. A statement is given as: ‘Study_Table’ is an object of the class ‘Furniture’. Write down Java statement for the same. Ans. Furniture Study_table =new Furniture(); 7. Class and Objects are inter-related. Explain. Ans. A class is used to create various objects that possess different characteristics and common behaviours. Each object follows all the features defined within the class. That is why, a class is also referred to as a blue print or a prototype of an object. This way we can say they are inter- related. 8. Why is an Object called an ‘Instance’ of a class? Explain. [ICSE-2010] Ans. Having defined a class, you can create as many objects as needed. These objects are known as the ‘instances’ of the class. All these ‘instances’ created with the given class will have the same structure and behaviour. CHAPTER-1 5 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

9. Write a statement to create an object ‘Keyboard’ of the class ‘Computer’. Ans. Computer Keyboard=new Computer(); 10. Mention three characteristics and two methods for the following Classes: (a) Class Mobile Phone (b) Class Bike (c) Class Fruits (d) Class Pen Ans. Mobile Phone – (i) Characteristics- Storage capacity, Colour, Features (ii) Method – clickPicture(), sendSms() Bike – (i) Characteristics – Fuel capacity, Colour, Model (ii) Methods – quality(), performanceAnalyzer() Fruits – (i) Characterics – Smell, taste(), Shape (ii) Methods – nutritionFacts(), availability() Pen – (i) Characteristics – Colour, Size, Type (ii) Methods – Quality(), CostEffectiveness() 11. Design a class program to calculate the discount given to a customer on purchasing LED Television. The program also displays the amount paid by the customer after discount. The details are given as: Class name : Television Data members : int cost, int discount, int amount Member functions : Accept( ) : to input the cost of Television Calculate( ) : to calculate the discount Display( ) : to show the discount and the amount paid after discount Ans. public class Television{ int cost, discount, amount; public void Accept() { } public void Calculate() { } public void Display() { }}

CHAPTER-1 6 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Unit III : Values and Data Types

EXERCISES I. State whether the following statements are ‘True’ or ‘False’: 1. There are 128 set of different characters used in a Java program. 2. The ASCII codes of upper case letters range from 97 to 122. 3. A variable gives the exact representation of data. 4. The data types int, float, char are called non-primitive types. 5. A String literal is assigned to a String variable. 6. A character literal is always enclosed in double quotes. 7. String constant can be written by using a set of alphanumeric characters. 8. An object is said to be a non-primitive data. 9. The data type int stores fractional values. 10. Boolean type data is used to test a condition and results in either true or false. Answer. 1. true 2. false 3. true 4. false 5. true 6. false 7. true 8. true 9. false 10. true II. Write short answers: 1. What is meant by data type? Name two types of data type. Ans. Data types specify the size and type of values that can be stored. The two main data types are primitive and non-primitive . 2. Why is it necessary to define data type in Java programming? Ans. In java programming, it becomes necessary to select an appropriate data type according to the kind of data used so that the system may structure the memory location for its proper storage. 3. Define the following with an example : (a) variable (b) constant (c) boolean data type (d) coercion (e) primitive data type (f) non-primitive data type Ans. (a) variable- A variable is a named memory location which holds a data value of a particular data type. Example: int x; (b) constants - The quantities which remain fixed throughout the discussion of the program are called literals or constants. Example:- integer literal : 14,3,100 (c) boolean data type - It is a special data type in which a variable contains a constant as either true or false. These are non-figurative constants. The default value of a boolean variable is false. Example:boolean flag=false ;

CHAPTER-1Ans. Token – (i) It can be defined as an individual 7 component ofArundeep’s a java statement Computer that Applications-10 carries some meaning and takes part in the effective execution of the program. https://www.arundeepselfhelp.info

(d) Coercion - In a mixed expression, the data type of the result gets automatically converted into the higher most type available in the expression, without any intervention of the user. This system of type conversion is known as implicit type conversion/ coercion. Example: int a; long b,c; c=a+b; In this example a is automatically converted to long data type. (e) Primitive data types -The data types which are independent of any other data type are known as primitive data types. They are also called basic data types or predefined or built in data types. Example : byte, short, int, long, float, double, char (f) Non-primitive data types - They are basically defined as derived data types and are directly or indirectly dependent on primitive data types.They store data values with reference to the addresses or locations. So, they are also called ‘Reference Data type’. Example:- classes, arrays, interfaces etc. 4. What is a token? Name different types of tokens. Ans. (i) Token can be defined as an individual component of a java statement that carries some meaning and takes part in the program. (ii) Various types of tokens are keywords, identifiers, literals, operators and separators. 5. Explain the term type casting. [ICSE 2007] Ans. It is another way of type conversion in which one data type gets converted to another data type depending on the user’s choice. This means that the user demands the system to get the result in the desired data type. Example: int a,b; float x= (float) a+b; 6. Assign the following to a variable with suitable data type. (a) m=22/7 (b) p = 1.4142135 (value of square root of 2) (c) k = 0.00004545 (d) n= 24.50 Ans. (a) double m=22/7 (b) double p = 1.4142135 (c) double k = 0.00004545 (d) float n= 24.50 7. Distinguish between: (a) Token and Identifier [ICSE 2008]

CHAPTER-1 8 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(ii) Example: literals, punctuators, operators, keywords etc. Identifiers – (i) They are also called variables in Java. A variable is a named memory location which holds a data value of a particular data type. (ii) Example: int x; In the above statement, x is the variable. (b) Character and Boolean literal [ICSE 2009] Ans. Character Literal - (i) The constants which are alphanumeric in nature are called character literals. (ii) It is enclosed within single quotes. Example: ‘a’, ‘D’, ‘3’ Boolean Literal – (i) They are special literals which can be applied in a Java program to check whether a given logical condition is satisfied or not. (ii) They are never enclosed within quotes. Example: true, false. 8. Explain the term type conversion. How is implicit conversion different from explicit conversion? [ICSE 2010] Ans. In a mixed expression, the result can be obtained in any one form of its data types. Hence, it is needed to convert the various data types into a single data type. Such conversion is termed Type Conversion. In Java, type conversion can be implicit or explicit. Implicit - In a mixed expression, the data type of the result gets automatically converted into the higher most type available in the expression, without any intervention of the user. This system of type conversion is known as implicit type conversion/ coercion. Example: int a; long b,c; c=a+b; In this example a is automatically converted to long data type. Explicit - It is another way of type conversion in which one data type gets converted to another data type depending on the user’s choice. This means that the user demands the system to get the result in the desired data type. Example: int a,b; float x= (float) a+b; 9. Classify the following as primitive or non-primitive data types. (a) char (b) arrays (c) int (d) classes [ICSE 2018]

CHAPTER-1 9 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Ans. (a) primitive (b) non-primitive (c) primitive (d) non-primitive 10. In what way is static initialization of data type different from dynamic initialization?  This process uses direct assignment of a constant to a defined variable. The variable is initialized at the time of its declaration (ie) before its actual use in the programming logic. Examples:- int a=0; float f=0.0; double d=0.0;  When a variable gets initialized at run time (ie) during the execution of the programming logic, it is termed as dynamic initialization. Under this situation, a variable is assigned with the outcome of any arithmetical operation or logical function. Examples:- int a,b,c; c=a+b; String s1,s2,s3; s3=s1+s2; 11. Predict the return data type of ‘r’ and ‘n’ from the snippet: (a) int p; (b) float m; r = p+m; n = m/3*(Math.pow(4,3)); System.out.println(r); System.out.println(n); Ans. Return type of r is float Return type of n is double 12. Give reason whether the following assignments are correct or not: (a) int m =155; (b) float f =0.002654132; (c) String str = ‘Computer’; (d) boolean p = false; (e) String b = “true”; (f) char ch = “apps”; (g) String st = “Application”; (h) double n= 455.29044125; Ans. (a) correct (b) Incorrect.double should be used (c) Incorrect.Single quotes cannot be used for String (d) correct (e) correct. but true will be considered as a String and not as a boolean literal (f) Incorrect. double quotes cannot be used for char. Single char is only allowed. (g) correct (h) correct

CHAPTER-1 10 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Unit IV : Operators in Java

EXERCISES I. State whether the following statements are ‘True’ or ‘False’: 1. The precedence of operators in Java follows BODMAS. 2. The output of a++ will be 1, if int a = –1. 3. The relational operators always result in terms of ‘True’ or ‘False’. 4. Given: int m=5; m*=5 then the value stored in m results in 55. 5. The statement (a>b)&&(a>c) uses a logical operator. 6. If int a=27, b=4, c=0; then c = a%b; results in 3. 7. The statement p+=5 means p=p*5. 8. In the precedence of logical operators; NOT is followed by AND. Answer. 1. false 2. false 3. true 4. false 5. true 6. true 7. false 8. true II. Write the Java expressions for the following:

a2 b 2 1. z = 5x3 + 2yx + y [ICSE 2011] 2. m  ()a b

1 uv 3. s ut  at2 [ICSE 2013] 4. f  2 ()u v

3x x2 5. d  [ICSE 2018] 6. p = a2 + b2 + 2ab [ICSE 2015] a b a b 7. y = 2 (lb + bh + lh) 8. p   b2 a 2

y 1 3 9. z x3  y 3  [ICSE 2006] 10. q   z3 a b c2 Answer. 1. z=5*x*x*x + 2*y*x + y 2. m=a*a + b*b /(a+b) 3. s=u*t + (1.0/2)*a*t*t 4. f=u*v/ (u+v) 5. d=Math.sqrt(3*x + x*x) / (a + b) 6. p=a*a + b*b +2*a*b 7. y=2*(l*b + b*h +l*h) 8. p=a/(b*b) + b/(a*a) 9. z=Math.pow(x,3)+Math.pow(y,3) – y/ Math.pow(z,3) 10. q=1/Math.sqrt(a+b) + 3/(c*c)

CHAPTER-1 11 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

III. Predict the output : 1. int c = (3<4)? 3*4:3+4; 2. int a = 14, b=4; boolean x = (a>b)? true: false; 3. int x = 90; char c = (x<=90)? ‘Z’:’I’; 4. int a = 18; int b = 12; boolean t = (a>20&& b< 15)? true:false; 5. c = (val + 550 < 1700)? 200: 400; if: (a) val = 1000 (b) val = 1500 Answer. 1. 12 2. true 3. Z 4. false 5. (a) 200 (b) 400 IV. Answer the following questions: 1. What is an operator? What are the three main types of operators? Name them. Ans. An operator is basically a symbol or token, which performs arithmetical or logical operations and gives meaningful result. The three main types of operators in Java are:-  Arithmetical operators  Relational operators  Logical operators 2. How is Java expression different from statement? Ans. Java Expression - It is a set of variables, constants and arithmetical operators. In other words, it is a combination of operators and operands. Example a*b+8 Java statement – When an expression is assigned to a variable, the complete set is referred to as an arithmetical statement. Example m=a*b + 8; 3. Explain the following with one example each. (a) Arithmetic operator (b) Relational operator (c) Logical operator (d) Ternary operator Ans. (a) Arithmetic operator - The operators which are applied to perform arithmetical calculations in a program. An arithmetic operator applied to a single operand is known as a Unary operator (may be prefix / postfix) whereas an arithmetic operator which deals with two operands is known as Binary operator. Binary operators are also used in shorthand binary operations. Example: +, -, ++, — , * , / , & , % sum+=b; //shorthand int c= num % 2 ; (b) Relational operator – These operators are used to show the relationship between the operands. Relational operators (<, <=, >, >=, == , != ) compare the values of the variables and result in terms of ‘True’ or ‘False’. CHAPTER-1 12 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Example: if( a ==b) System.out.println(“Equal”); (c) Logical operator – Java uses logical operators ( &&, ||, ! ) which yield true or false depending on the outcome of different expressions. Logical operators Symbol Example AND && boolean b = (x >y ) && (x>z) OR || boolean p = (x<=y) || (x <=z) NOT ! boolean t = !(m==n) (d) Ternary operator – Ternary operators deal with three operands. They are also called conditional assignment because the value assigned to a variable depends upon a logical expression. Syntax:- variable = (test expression) ? Expression1 : Expression2 4. Distinguish between: (a) Unary & Binary arithmetic operator (b) Postfix increment and Prefix increment (c) Postfix decrement and Prefix decrement (d) (p! = q) and !(p = = q) Ans. (a) Unary operator - An arithmetical operator which is applied to a single operand. Example: x++; Binary operator -An arithmetic operator which deals with two operands. Example: x=x+1; (b) Prefix increment - This operator works on the principle ‘CHANGE BEFORE ACTION’ . Example: d=10; t =5 * (++d) // t = 5* 11 = 55 Postfix increment - This operator works on the principle ‘CHANGE AFTER ACTION’ . Example: d=10; t= 5 * (d++) // t = 5 *10 =50 (c) Postfix decrement –This operator works on the principle ‘CHANGE AFTER ACTION’ . Example: d=10; t= 5 * (d--) // t = 5 *10 =50 Prefix decrement - This operator works on the principle ‘CHANGE BEFORE ACTION’ . Example: d=10; t =5 * (--d) // t = 5* 9 = 45 (d) (p! = q)Only when p and q are not equal, this condition becomes true. Example: p=20 ; q= 21; boolean r = (p!=q )// r = true

CHAPTER-1 13 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

!(p = = q)Even if p and q are equal, false is returned because of the (NOT !) operator Example: p=20 ; q= 20; boolean r = (p==q )// r = false 5. What is the difference between (a) / and % operator? (b) = and = =? [ICSE 2011] Ans. (a) Division (/) Example: int c= 26; b = c/5 returns 5 (quotient) Mod (%) Returns the remainder after the division. Example: int c= 26; b= c/5 returns 1 (remainder) (b) Assignment ( =) This is an assignment operator. Example: a=b; // assigns the value of b to a Equals (==) This is relational operator. Example: boolean w= (a==b) // w =true if a and b are equal, otherwise w=false. 6. What will be the output of the following code? (a) int k=5, j=9; k+= k++ – ++j + k; System.out.println(“k=”+k); System.out.println(“j=”+j); [ICSE 2011] Ans. k=6 j=10 working: k = k + (k++ – ++j + k) = 5+ ( 5 - 10 + 6) = 5+ (1) = 6 (b) If int y =10 then find int z = (++y*(y+++5)); [ICSE 2015] Ans. 176 Working z = (++y*(y+++5)) = 11 * (11 + 5) = 11 * 16 = 176 CHAPTER-1 14 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(c) Give the output of the following expression: [ICSE 2016] a+= a++ + ++a + - -a + a- -; when a = 7; Ans. 39 Working a+= a++ + ++a + - -a + a- -; a = a + (a++ + ++a + - -a + a- -) = 7 + (7 + 9 + 8 +8) = 7 + (32) = 39 (d) What is the value of y after the execution? [ICSE 2018] y+= ++y + y- - + - -y; when int y=8 Ans. 33 Working y+= ++y + y- -+ - -y y = y + (++y + y- - + - -y) = 8 + (9 + 9 +7) = 8+ 25 = 33 7. Rewrite the following program segment using if-else statements instead of the ternary operator. (a) String grade = (marks>=90)?"A": (mark>=80)? "B": "C"; [ICSE 2014] Ans. String grade; if(marks>=90) grade="A"; else if(marks>=80) grade= "B"; else grade="C"; (b) commission = (sale > 5000) ? sale*10/100 : 0; Ans. double commission; if(sale>5000) commission=sale*10/100; else commission=0; (c) net = (salary > 10000) ? salary – (8.33/100)*salary : salary - (5/100)*salary; Ans. double net; if(salary>10000) net=salary – (8.33/100)*salary; else net=salary - (5/100)*salary; CHAPTER-1 15 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(d) s= (a+b= ‘A’ && x<= ‘Z’) ? “Upper Case Letter” : “Lower Case Letter”; Ans. String c; if(x >= ‘A’ && x<= ‘Z’) c=”Upper Case Letter”; else c=”Lower Case Letter”; 8. Rewrite the following using ternary operator. (a) if (x%2 = = 0) [ICSE 2016] System.out.println(“Even”); else System.out.println(“Odd”); Ans. String s=(x%2==0)? “Even”: “Odd”; (b) if (bill>10000) [ICSE 2018] discount=bill*10.0/100; else discount=bill*5.0/100; Ans. double discount= (bill>10000)?bill*10.0/100: bill*5.0/100; (c) if(income< 10000) tax = 0; else tax = 12; Ans. int tax=(income<10000)?0:12; (d) if(a>b) { if(a>c) g=a; else g=c; } if(b>c) g=b; else g=c; Ans. g=(a>b)?(a>c?a:c) : (b>c?b:c); CHAPTER-1 16 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(e) if(p>=4750) k=p*5/100; else k=p*10/100; Ans. double k=(p>=4750)?p*5/100: p*10/100;

Unit V (a) : Introduction to Java

EXERCISES I. Tick the correct answer: 1. A Java program developed and executed by the users without using web browser is known as: (a) application (b) applet (c) object (d) none 2. Who developed Java? (a) James Gosling (b) Robert James (c) Bjarne Stroustrup (d) None 3. Java Virtual Machine (JVM) is an: (a) interpreter (b) compiler (c) machine code (d) byte code 4. Java is a case sensitive language. Which is the most appropriate statement with respect to this context? (a) Upper and lower case letters are distinguished. (b) Upper and lower case letters are ignored. (c) Only lower case letters are distinguished. (d) None. 5. Which of the following package is needed to find the square root of a number? (a) java.text (b) java.math (c) java.lang (d) None 6. Which of the following is not a Java reserved word? (a) private (b) public (c) break (d) total 7. The most suitable statement for BlueJ is: (a) It is a window based platform. (b) It is a DOS based platform. (c) It is a window based and DOS based platform. (d) None. Answer. 1. application 2. James Gosling 3. interpreter 4. Upper and lower case letters are distinguished 5. java.lang 6. total 7. It is a window based and DOS based platform

CHAPTER-1 17 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

II. Fill in the blanks: 1. The initial name of Java was ...... 2...... converts source code to byte code. 3. JVM is used to convert ...... into machine code. 4. Java is ...... independent language. 5. Windows based Java platform is known as ...... 6. Reserved words are also called ...... 7...... package is used for mathematical functions in Java. Ans. 1. Oak 2. compiler 3. byte code 4. platform 5. BlueJ 6. keywords 7. java.lang III. Predict the output of the following snippets: 1. System.out.println(“My name is”); System.out.print(“Kunal Kishore”); System.out.println(“I am a student of Class X”); Ans. My name is Kunal KishoreI am a student of Class X 2. System.out.println(“This is my first Java program”); System.out.print(“Display the message:”); System.out.print(“Have fun!!!”); Ans. This is my first Java program Display the message:Have fun!!! 3. System.out.println(“India got independence”); System.out.println(“on”); System.out.println(“15th August,1947”); Ans. India got independence on 15th August, 1947 4. System.out.print(“The of 5 is”); System.out.println(“120”); Ans. The factorial of 5 is120 IV. Write short answers: 1. Name a Java package which is imported by default. Ans. java.lang 2. Explain the significance of the following Java library packages. (a) java.lang (b) java.io (c) java.math Ans. (a) java.lang - To support classes containing String /Character, Math, Integer, Thread etc (b) java.io - To support classes to deal with input and output statements (c) java.math - contains classes for mathematical operation. 3. (a) Java interpreter is called Java Virtual machine. Explain. CHAPTER-1 18 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Ans. JVM acts as a virtual processor (A software referred to as the interpreter), which processes the byte code in to machine code instructions for various platforms. Hence, it is known as a machine. (b) Name two ways of writing Java programs. Ans. Java application (Standalone system) Java applet 4. Define the terms : (a) Source code (b) Machine code (c) Byte code [ICSE 2010] Ans. (a) Source code – The high level language is referred to as the source code. (b) Machine code – The binary code (low level language) which the machine can understand is known as the machine code. (c) Byte code – Programs written in Java are compiled for conversion to an intermediate code called Byte code. When this Byte code is to be run on any system, an interpreter, known as Java Virtual Machine (JVM) translates the byte code into machine code. 5. What is BlueJ? What are the features of BlueJ? Ans. BlueJ is a menu-based platform on Windows environment to write and execute Java programs. It requires the user to install JDK 1.3 before installing BlueJ.  The compilation as well as the execution process is easier than JDK1.3  It is based on a menu driven approach and hence easier to work with.  As soon as the user defines a class, a sample program appears on the screen.  After compilation it either displays No errors/ the errors, if any, present in the program.  It can also be used to download/ share programs on the internet. 6. Write down the syntax of output statement in Java with an example. Ans. Suppose if we want to print an output statement Hello World, the following syntax must be used. Syntax:-System.out.println(“Hello World “); 7. What is meant by Java reserved words ? Name five Java reserved words which are commonly used in Java programming. [ICSE 2011] Ans.  Java keywords are reserved words which carry special meaning to the system compiler. Hence, these words cannot be used for naming variables in the program.  Some of the keywords used in Java are :- switch, case, break, default, if, else, for, do, while, public, int, double etc.  Some reserved words that are currently not in use are goto, const .  Reserved literals are true, false, null. 8. Differentiate between the output statements System.out.print( ) and System.out.println(). Ans.  Both the above statements are output statements. CHAPTER-1 19 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

 System.out.print() : When you use this statement, the cursor remains in the same line on the screen after producing the result.  System.out.println() : This statement is used to pass the cursor to the next line of the screen after producing the result. 9. A Java program uses a Compiler as well as an Interpreter. Explain. Ans.  Java compiler is a software that converts the source code into the intermediate binary form called the byte code.  The Java interpreter (JVM) accepts the byte code and converts it into machine code suitable to the specific platform.  Hence, a Java program uses a Compiler as well as an Interpreter. 10. Write a package that is used for input/output operation in Java. Ans. java.io Unit V (b) : Input in Java

I. Fill in the blanks : 1. The package needed to import StreamReader class is ...... 2...... function accepts an integer by using scanner object. 3. The package needed to import Scanner class is ...... 4. The keyword ...... is used to include a package in a program. 5. Division by a variable that contains a value zero is called ...... error. 6...... statement is used to accept value at run time. 7...... function accepts a string by using scanner object. 8...... keyword refers to a non-returnable type function. 9. Scanner ob = ...... Scanner (...... ). 10. The command line argument accepts the data value as an ...... of Strings. Answer. 1. java.io.* 2. nextInt() 3. java.util.* 4. import 5. runtime error 6. input 7. next() 8. void 9. Scanner ob=new Scanner(System.in); 10. array II. Explain the following functions: 1. Integer.parseInt(in.readLine( )); Ans. The function readLine() is used to read the input as a String and Integer.parseInt() is used to convert the input into an integer Syntax: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int x= Integer.parseInt(in.readLine( )); CHAPTER-1 20 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

2. (char)(in.read( )); Ans. This function is used to input a character Syntax: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); char c= (char)(in.read( )); 3. next( ); Ans. When a line of text is input into the Scanner object, the next() method will receive the first token only. Syntax: Scanner ob=new Scanner(System.in); String s= ob.next(); 4. nextlnt( ); Ans. This function is used to receive the next token from Scanner object which can be expressed as an integer and stored in an integer type value. Syntax: Scanner ob=new Scanner(System.in); int num= ob.nextInt(); 5. nextLine( ); Ans. When a line of text is input into the Scanner object, the nextLine() method is used to read the entire line of text. It accepts the String including spaces. Syntax: Scanner ob=new Scanner(System.in); String s=ob.nextLine(); III. Answer the following: 1. What are the different ways to give input in a Java Program? Ans. (a) Using function argument (b) Using InputStreamReader class (c) Using Scanner class (d) Using Command Line argument 2. What is a package? Give an example. Ans. A package in Java is a collection of logically related classes. Each package includes related built- in functions which may be used while developing programming logic. Example: java.math, java.lang, java.io , java.util, etc

3. What is the use of the keyword ‘import’ in Java programming? Ans. A class created by the user is known as a user defined class. But, there are some packages (group of classes) available within the Java system(JDK). These packages can be imported and used in any program, by using the ‘import’ keyword. The availability of the built-in classes and functions in these packages provides an effective support to the programmers, thus making Java a powerful language. CHAPTER-1 21 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

4. What is a Run Time error? Explain with an example. Ans. It is a type of error that occurs at runtime when the compiler does not respond properly while executing a statement. Example: Dividing a number by zero. 5. What are the different types of errors that take place during the execution of a program? Name them. Ans. (i) Syntax errors (ii) Logical errors and (iii) Run time errors 6. Give two differences between Syntax error and Logical error. Ans. Syntax error  These errors occur when the rules or the grammar of the programming language are not followed  All syntax errors must be identified and corrected. Otherwise the program will not execute.  Example: x=a+b In the above statement, syntax error is generated because of lack of semicolon at the end of the statement Logical error  These errors occur when there is an error in planning the logic of the program.  The computer does not know that an error has been made. The program executes but the output may not be correct.  To print numbers from 1 to 10, for(int x=1;x>=10;x++) System.out.println(x); The above snippet of code has a logical error, since the condition was supposed to be x<=10 to get the specific output that was expected. IV. (Unsolved) Java Programming: 1. In an election, there are candidates X and Y. On the election day, 80% of the voters go for polling, out of which 60% vote for X.Write a program to take the number of voters as input and calculate: (i) number of votes X get (ii)number of votes Y get Solution: import java.util.*; class U5_Q1{ public static void main(String args[]) {Scanner obj=new Scanner(System.in); System.out.println(“Enter the number of voters”); long v1; double v2,x,y; v1=obj.nextInt(); //Input - eligible voters v2= (80.0/100)* v1; //80% of voters who polled x=(60.0/100)*v2; //60% of votes

CHAPTER-1 22 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

y=v2-x; //remaining votes System.out.println(“No. of votes secured by x :”+(long)x); System.out.println(“No. of votes secured by y :”+(long)y); }} 2. A shopkeeper offers 10% discount on the printed price of a mobile phone. However, a customer has to pay 9% GST on the remaining amount. Write a program in Java to calculate the amount to be paid by the customer taking printed price as an input. Solution: import java.util.*; public class U5_Q2{ public static void main(String args[]) { Scanner obj=new Scanner(System.in); double price,dprice,gst,amt; System.out.println(“Enter the printed price of the mobile”); price=obj.nextDouble(); //printed price dprice=price - 10.0/100 * price; //discounted price gst=9.0/100 * dprice; //gst amt=dprice+gst; //discounted price+gst System.out.println(“Discounted price :”+dprice); //optional statement System.out.println(“Amount payable including gst:”+amt); }} 1 1 1 3. A man spends of his salary on food, on rent, on miscellaneous. Rest of the 2 15 10 salary is his saving. Write a program to calculate and display the following : (i) money spent on food (ii) money spent on rent (iii) money spent on miscellaneous (iv) money saved Take the salary as an input. Solution: import java.util.*; public class U5_Q3{ public static void main(String args[]) { Scanner obj=new Scanner(System.in); double sal,food,rent,misc,save; System.out.println(“Enter the salary”); sal=obj.nextDouble(); CHAPTER-1 23 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

food=1.0/2 * sal; rent=1.0/15 * sal; misc=1.0/10 * sal; save=sal- (food+rent+misc); System.out.println(“Money spent on food : ”+food); System.out.println(“Money spent on rent : ”+rent); System.out.println(“Money spent on misc : ”+misc); System.out.println(“Money saved : ”+save ); }} 4. Write a program to input time in seconds. Display the time after converting them into hours, minutes and seconds. Sample Input: Time in seconds: 5420 Sample Output: 1 Hour 30 Minutes 20 Seconds Solution: import java.util.*; public class U5_Q4 { public static void main(String ag[]) {Scanner obj=new Scanner(System.in); int tsec,hr,min,sec,rem; System.out.println(“Enter the time in seconds”); tsec=obj.nextInt(); hr=tsec/3600; rem=tsec%3600; // % gives remainder of tsec/3600 min=rem/60; sec=rem%60; System.out.println(hr+ “ Hour(s),” +min+” Minute(s),”+sec+ “ Second(s)”); }} 5. The driver took a drive to a town 240 km at a speed of 60 km/h. Later in the evening, he drove back at 20 km/h less than the usual speed. Write a program to calculate: (i) the total time taken by the driver (ii) the average speed during the whole journey Solution: public class U5_Q5 {public static void main(String ag[]) { double dist=240,t1,t2,tot,spd=60,avgspeed; t1=dist/spd; //time= distance/ speed CHAPTER-1 24 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

t2=dist/(spd-20); // since speed was decreased by 20km/h tot=t1+t2; avgspeed= (2*dist)/tot; //avg speed= total dist/total time System.out.println(“The total time for the journey: ”+tot); System.out.println(“The average speed for the journey: ”+ avgspeed); }} 6. Write a program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable. Sample Input: a = 76, b = 65 Sample Output: a = 65, b = 76 Solution: import java.util.*; public class U5_Q6 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int a,b; System.out.println(“Enter the two numbers”); a=in.nextInt(); b=in.nextInt(); System.out.println(“Before Swapping \n a=”+a+” b=”+b); a=a+b; b=a-b; a=a-b; System.out.println(“After Swapping \n a=”+a+” b=”+b); }} 7. A certain amount of money is invested for 3 years at the rate of 6%, 8% and 10% per annum compounded annually. Write a program to calculate: (i) the amount after 3 years. (ii) the compound interest after 3 years. Accept certain amount of money (Principal) as an input. Solution: import java.util.*; public class U5_Q7 {public static void main(String args[]) { Scanner in=new Scanner(System.in);

CHAPTER-1 25 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

double P,T=3.0,CI=0.0,A=0.0,R1=6.0,R2=8.0,R3=10.0; System.out.println(“Enter the principal”); P=in.nextDouble(); A=P* Math.pow((1+R1/100.0),T)* Math.pow((1+R2/100.0),T)* Math.pow((1+R3/100.0),T); CI=A-P; System.out.println(“Amount after 3 years=”+A); System.out.println(“Compound Interest after 3 years=”+CI); }} 8. The co-ordinates of two points A and B on a straight line are given as (x1, y1) and (x2, y2). Write a program to calculate the slope (m) of the line by using formula :

y2 y 1  Slope =   x2 x 1  Take the co-ordinates (x1, y1) and (x2, y2) as input. Solution: import java.util.*; public class U5_Q8 {public static void main(String args[]) {Scanner obj=new Scanner(System.in); double y2,y1,x2,x1,slope; System.out.println(“Enter the values of the co-ordinates”); System.out.print(“Enter y2 :”); y2=obj.nextInt(); System.out.print(“Enter y1 :”); y1=obj.nextInt(); System.out.print(“Enter x2 :”); x2=obj.nextInt(); System.out.print(“Enter x1 :”); x1=obj.nextInt(); slope=(y2-y1)/(x2-x1); System.out.println(“Slope =”+slope); } }

CHAPTER-1 26 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Unit VI : Mathematical Library Methods

EXERCISES I. State whether the following statements are ‘True’ or ‘False’: 1. The return data type of Math.log( ) is double. 2. Java.Math class is used for different mathematical functions. 3. The output of Math.abs(-99.99) is 100.00. 4. Math.sqrt(-225) can’t be defined. 5. The output of Math.cbrt(-3) will be -27. 6. Math.round( ) returns the value in float data type. Answer. 1. true 2. true 3. false 4. true 5. false 6. false II. Predict the output: 1. System.out.println(Math.floor(-4.7)); [ICSE 2018] Ans. - 5.0 2 System.out.println(Math.rint(-9.4)+Math.sqrt(9.0)); Ans. - 6.0 3. System.out.println(Math.max(Math.ceil(14.55),15.5)); Ans. 15.5 4. System.out.println(Math.sqrt(Math.min(42.5,42.25))); Ans. 6.5 5. System.out.println(Math.ceil(3.4)+Math.pow(2,3)); [ICSE 2018] Ans. 12.0 III. Write down the syntax for the following functions: 1. To find the natural log of q. Ans. Math.log(q) 2. To find the root of a number m. Ans. Math.cbrt(m) 3. To find the round-off of a number k. Ans. Math.round(k) 4. To find the absolute value of a number y. Ans. Math.abs(y) 5. To find the exponent of a number p. Ans. Math.exp(p) IV. Explain the following functions; 1. Math.random( ) Ans. It returns a random number between 0 and 1 in a double data type value. 2. Math.pow( ) Ans. This method is used to find the power raised to a given base value. It always returns a double type value.

CHAPTER-1 27 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

3. Math.cbrt( ) Ans. It is used to find the cube root of a positive or a negative number. It always returns a double type value. 4. Math.log( ) Ans. It is used to find the natural logarithmic value of a given argument. It always returns a double type value. V. Distinguish between: 1. Math.ceil( ) and Math.floor( ) Ans. (i) Math.ceil() returns the whole number greater than or equal to the number. Example :Math.ceil(8.5) returns 9.0 (ii) Math.floor() returns the rounded value down to the nearest integer. Example: Math.floor(8.5) returns 8.0 2. Math.rint( ) and Math.round( ) Ans. (i) Math.rint() return the truncated value of a number. The returns type of Math.rint() is double. (ii) Math.round() return the rounded value upto the nearest integer. The return type of Math.round() is int or long VI. Unsolved Programs: 1. Write a program to calculate the value of the given expression: 1 2 3   . a2 b 2 c 2 Take the values of a, b and c as input from the console. Finally, display the result of the expression to its nearest whole number. Solution: import java.util.*; public class Q1 {public static void main(String args[]) {Scanner in=new Scanner(System.in); int a,b,c; long s; double x;

System.out.println(“Enter the three numbers”); a=in.nextInt(); b=in.nextInt(); c=in.nextInt();

x=1/Math.pow(a,2)+2/Math.pow(b,2)+3/Math.pow(c,2);

s=Math.round(x); CHAPTER-1 28 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println(s); }} 2. For every m>l; 2m, m2–1 and m2+l form a Pythagorean triplet. Write a program to input the value of ‘m’ through console to display a ‘Pythagorean Triplet’. Sample Input: 3 Then 2m=6, m2–l=8 and m2+l=10 Thus 6, 8, 10 form a ‘Pythagorean Triplet’. Solution: import java.util.*; public class Q2 {public static void main(String args[]) { Scanner in=new Scanner(System.in); int m,x,y,z; System.out.println(“Enter a natural number”); m=in.nextInt(); x=2*m; y=m*m-1; z=m*m+1; System.out.println(x+","+y+" and "+z+" are Pythagorean triplets"); }} 3. Write a program to input a number. Calculate its square root and cube root. Finally, display the result by rounding it off. Sample Input: 5 Square root of 5 = 2.2360679 Rounded form = 2 Cube root of 5 = 1.7099759 Rounded form = 2 Solution: import java.util.*; public class Q3 { public static void main(String args[]) { Scanner in= new Scanner(System.in); long x,cb,sq; System.out.println(“Enter a number”); x=in.nextInt(); CHAPTER-1 29 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

sq=Math.round(Math.sqrt(x)); cb=Math.round(Math.cbrt(x)); System.out.println(“Square root=”+sq); System.out.println(“Cube root=”+cb); }} 4. The volume of a sphere is calculated by using formula: 4 22 v ** r3 3 7 Write a program to calculate the radius of a sphere by taking its volume as an input. Solution: import java.util.*; public class Q4 {public static void main(String args[]) {Scanner in=new Scanner(System.in); double vol,r; System.out.println(“Enter the volume of the sphere”); vol=in.nextDouble(); r=Math.cbrt(vol*3/4*7/22); System.out.println(“Radius=”+r); }} 5. A trigonometrical expression is given as: Tan A Tan B 1 Tan A * Tan B Write a program to calculate the value of the given expression by taking the values of angles A and B (in degrees) as input. Solution: import java.util.*; public class Q5 { public static void main(String BM[]) {Scanner ob=new Scanner(System.in); double x,y,z,A=0,B=0,C=0,result; System.out.println(“Enter the values of a,b,c”); A=ob.nextDouble(); B=ob.nextDouble(); C=ob.nextDouble();

//convert A,B,C from degrees to radians A=(22.0/(7.0*180.0))*A; B=(22.0/(7.0*180.0))*B; C=(22.0/(7.0*180.0))*C; CHAPTER-1 30 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

result=(Math.tan(A)-Math.tan(B))/(1+Math.tan(A)+Math.tan(B)); System.out.println(result); }} 6. The standard form of quadratic equation is represented as: ax2 + bx + c = 0 where d = b2 – 4ac, known as ‘Discriminant’ of the equation. Write a program to input the values of a, b and c. Calculate the value of discriminant and display the output to the nearest whole number. Solution: import java.util.*; public class Q6 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int a,b,c; long d; System.out.println(“Enter the values for a,b and c”); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); d=Math.round(Math.pow(b,2)-4*a*c); System.out.println(“Discriminant(d)=”+d); }}

Unit VII : Conditional Statements in Java

EXERCISES

I. State whether the following statements are ‘True’ or ‘False’: 1. if statement is also called as a conditional statement. 2. A conditional statement is essentially formed by using relational operators. 3. An if-else construct accomplishes ‘fall through’. 4. In a switch case, when the switch value does not match with any case then the execution transfers to the default case. 5. The break statement mayn’t be used in a switch statement. Answer. 1. true 2. true 3. false 4. true 5. false II. Tick the correct answer: 1. If m, n, p are the three , then which of the following holds true, if (m==n)&&(n!=p) ?

CHAPTER-1 31 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(a) ‘m’ and ‘n’ are equal (b) ‘n’ and ‘p’ are equal (c) ‘m’ and ‘p’ are equal (d) none Ans. (a) 'm' and 'n' are equal 2. A compound statement can be stated as: (a) p=in.nextlnt(); (b) m=++a; q=in.nextlnt(); n=--b; (c) if(a>b) (d) none {a++;b--;} Ans. (c) if(a>b) { a++; b--;} 3. If((p>q)&&(q>r)) then (a) q is the smallest number (b) q is the greatest number (c) p is the greatest number (d) none (where p, q and r are three integer numbers) Ans. (c) p is the greatest number 4. if(a

3 4 1 1. 3  2. p q  r ab cd 2

3 b  b2  4 ac 0.05 2y 3. 4. [ICSE 2007] 2a ()x y

3 2 5. mn3 () m  n 6. ()a b ab 4 5

CHAPTER-1 32 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

3 2 3 7. ()b c 8. 32  3 8 a b c

a b2  c 3 3x x2 9. 10. [ICSE 2018] 3 ()a b Ans. 1. Math.cbrt(a*b + c*d) 2. Math.pow(p,3) + Math.pow(q,4) - 1/2 * r 3. (-b * Math.sqrt(b*b - 4*a*c))/(2*a) 4. (0.05 -2 * Math.pow(y,3))/(x-y) 5. Math.sqrt(m*n)+Math.cbrt(m+n) 6. 3/4 * (a+b)- 2/5 *(a*b) 7. 3/8 * Math.sqrt(b*b + c*c*c) 8. Math.cbrt(a)+b*b + Math.cbrt(c) 9. Math.sqrt(a+b*b +c*c*c)/3 10. Math.sqrt(3*x + x*x)/(a+b) IV. Predict the output : 1. int m=3,n=5,p=4; if(m==n)&&(n!=p) { System.out.println(m*n); System.out.println(n%p); } if((m!=n) | | (n==p)) { System.out.println(m+n); System.out.println(m-n); } Ans. 8 -2 2. (i) p = 1 (ii) p = 3 int a=l,b=2,c=3; switch(p) { case 1: a++; case 2: ++b; break; case 3: c--; } System.out.println(a + “,” + b + “,” +c); Ans. (i) 2,3,3 (ii) 1,2,2 V. Convert the following constructs as directed : 1. switch case construct into if-else-if :

CHAPTER-1 33 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

switch(n) { case 1: s=a+b; System.out.println(“Sum=” +s); break; case 2: d=a-b; System.out.println(“Difference=” +d); break: case 3: p=a*b; System.out.println(“Product=” +p); break; default: System.out.println(“Wrong Choice!”); } Ans. if(n==1) {s=a+b; System.out.println("Sum="+s); } else if(n==2) {d=a-b; System.out.println("Difference="+d); } else if(n==3) {p=a*b; System.out.println("Product="+p); } else System.out.println("Wrong Choice"); } 2. if-else-if construct into switch case : if(var==1) System.out.println(“Distinction”); else if (var==2) System.out.println(“First Division”); else if(var==3) System.out.println(“Second Division”);

CHAPTER-1 34 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

else System.out.println(“invalid”) ; [ICSE 2018] Ans. switch(var) {case 1:System.out.println("Distinction");break; case 2:System.out.println("First Division");break; case 3:System.out.println("Second Division");break; default:System.out.println("invalid"); } VI. Answer the following questions: 1. What is meant by 'conditional' statement? Explain. Ans. During the course of programming, we may want to execute particular blocks of statements and ignore other blocks based on a given condition. Since the control is diverted based on a condition, the statements which use keywords like if, switch, while etc are referred to as conditional statements.Thus, conditional statements are used to direct the flow of control to perform a particular task. 2. What is the significance of System.exit(0)? Ans. The function System.exit(0) is used when you want to terminate execution at any instance of the program. As soon as System.exit(0) is invoked, it terminates the execution, ignoring the rest of the statements of the program. 3. Is it necessary to include 'default' case in a switch statement? Justify. Ans. Yes. It is necessary to include 'default' case in a switch case statement so that if no case is available for the given value of the switch variable, the default case is used to display a message to the user to indicate that he/she has opted for the wrong choice. 4. What will happen if 'break' statement is not used in a switch case? Explain. Ans. In a switch statement, the break statement terminates the block. If the break is not used, the control will keep on executing other cases under the switch block. (fall through occurs) 5. When does Fall through' occur in a switch statement? Explain. Ans.  In a switch block, where multiple cases are available, the control needs to execute a specific case block for a given switch value.  If break is not applied at the end of the case block, the control enters the next case block for execution.  This unusual execution of more than one case for a given value of switch is termed as 'fall through'. 6. What is a compound statement? Give an example. Ans. A compound statement is a statement that includes multiple statements within curly brackets. Example: if(a>b) { sum=a+b; pdt= a*b; } In the above example, if the condition is true, the statements within the curly braces are executed.

CHAPTER-1 35 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

7. Explain if-else-if construct with an example. Ans. Sometimes if a given condition is false, we may want to specify a new condition to test and based on that, execute another block of code. In such a situation , if () - else-if' is useful. In the example given below, the resultant grade of the student that is printed depends on one of the conditions resulting in true. Example if(marks>=75) System.out.println("Distinction"); else if(marks>=60) System.out.println(" First Division"); else if (marks>=50) System.out.println("Second Division"); else System.out.println("Third Division"); 8. Give two differences between the switch statement and the if-else statement. [ICSE 2014] Ans. if-else  The if-else statement results in a boolean type value (true/false) based on which one of the two blocks of statements are executed.  if-else does not include a default block of statements to be executed switch - case  The switch-case statement does not result in a boolean type value. The block of statements executed will depend on the value of the control variable used in the switch statement, since switch only perform tests for equality.  The switch statement applies the default case when there is no matching case for the given value of the control variable. VII. Unsolved Java Programs : 1. Write a program to input three numbers (positive or negative). If they are unequal then display the greatest number otherwise, display they are equal. The program also displays whether the numbers entered by the user are 'All positive', 'All negative' or 'Mixed numbers'. Sample Input: 56, -15, 12 Sample Output: The greatest number is 56 Entered numbers are mixed numbers. Solution: import java.util.*; public class Q1 {public static void main(String args[]) {Scanner in=new Scanner(System.in); CHAPTER-1 36 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

int a,b,c,max; System.out.println("Enter the three numbers"); System.out.println("Enter positive/negative numbers only"); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); if(a==b&&b==c) System.out.println("The numbers are equal"); else {max=(a>b && a>c)?a:(b>c?b:c); System.out.println("The numbers are unequal, the greatest number is "+max);

if(a<0&&b<0&&c<0) System.out.println("All negative"); else if(a>0&&b>0&&c>0) System.out.println("All positive"); else System.out.println("The combination of positive and negative numbers"); } }} 2. A triangle is said to be an 'Equable Triangle', if the area of the triangle is equal to its perimeter. Write a program to enter three sides of a triangle. Check and print whether the triangle is equable or not. For example, a right angled triangle with sides 5, 12 and 13 has its area and perimeter both equal to 30. Solution: import java.util.*; public class Q2 {public static void main(String args[]) { Scanner in=new Scanner(System.in); int a,b,c,sp,peri; //sp-->semi perimeter double area; System.out.println("Enter the three sides of the triangle"); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); peri=a+b+c; sp=peri/2; area=Math.sqrt(sp*(sp-a)*(sp-b)*(sp-c)); //Heron's formula if(peri==area)

CHAPTER-1 37 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("The triangle is Equable"); else System.out.println("The triangle is not Equable"); }} 3. A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result is equal to the original two-digit number. Example: Consider the number 59. Sum of digits = 5 + 9 = 14 Product of digits = 5 * 9 = 45 Total of the sum of digits and product of digits = 14 + 45 = 59 Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value is equal to the number input, display the message "Special 2 - digit number" otherwise, display the message "Not a special two-digit number' [ICSE 2014] Solution: import java.util.*; public class Q3 {public static void main(String args[]) {Scanner ob=new Scanner(System.in); int num,rd,ld,pdt,sum=0; System.out.println("Enter a two digit number"); num=ob.nextInt(); rd=num%10; ld=num/10; pdt=rd *ld; sum=rd+ld; if(num==(sum+pdt)) System.out.println("It is a special 2 digit number"); else System.out.println("It is not a special 2 digit number"); }} 4. The standard form of quadratic equation is given by: ax2 + bx + c = 0, where d = b2 - 4ac, is known as discriminant that determines the nature of the roots of the equation as: Condition Nature if d>= 0 Roots are real if d< 0 Roots are imaginary Write a program to determine the nature and the roots of a quadratic equation, taking a, b, c as input. If d = b2 - 4ac is greater than or equal to zero, then display 'Roots are real', otherwise display 'Roots are imaginary'.

CHAPTER-1 38 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

The roots are determined by the formula as:

b  b2 4 ac  b  b2  4 ac r1  , r2  2a 2a Solution: import java.util.*; public class Q4 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int a,b,c; long d; System.out.println("Enter the values for a,b and c"); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); d=Math.round(Math.pow(b,2)-4*a*c); System.out.println("Discriminant(d)="+d); if(d>=0) System.out.println("Roots are real"); else System.out.println("Roots are imaginary"); } } 5. An air-conditioned bus charges fare from the passengers based on the distance travelled as per the tariff given below: Distance Travelled Fare Up to 10 km Fixed charge ` 80 11 km to 20 km ` 6/km 21 km to 30 km ` 5/km 31 km and above ` 4/km Design a program to input distance travelled by the passenger. Calculate and display the fare to be paid. Solution: import java.util.*; public class Q5 { public static void main(String args[]) {Scanner in= new Scanner(System.in);

CHAPTER-1 39 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

double dist,chrg=0.0; System.out.println("Enter the distance travelled"); dist=in.nextDouble(); if(dist<=10) chrg=80; else if (dist>10 &&dist<21) chrg=80+(dist-10)*6; else if (dist>20 &&dist<31) chrg=80+10*6+(dist-20)*5; else if (dist>31) chrg=80+10*6+10*5+(dist-30)*4;

System.out.println("Fare to be paid="+chrg); } } 6. An ICSE school displays a notice on the school notice board regarding admission in Class XI for choosing stream according to marks obtained in English, Maths and Science in Class 10 Council Examination. Marks obtained in different subjects Stream Eng, Maths and Science >= 80% Pure Science Eng and Science >= 80%, Maths >= 60% Bio Science Eng, Maths and Science >= 60% Commerce Print the appropriate stream allotted to a candidate. Write a program to accept marks in English, Maths and Science from the console. Solution: import java.util.*; public class Q6 { public static void main(String args[]) { inte,m,s; //eng,maths,sci marks Scanner ob=new Scanner(System.in); System.out.println("Enter English Mark:"); e=ob.nextInt(); System.out.println("Enter Math Mark:"); m=ob.nextInt(); System.out.println("Enter Science Mark:"); s=ob.nextInt(); System.out.print("Stream Allotted:"); if(e>=80 && m>=80 && s>=80) System.out.print("Pure Science"); else if(e>=80 && m>=60 && s>=80) System.out.print("Bio Science"); else if(e>=60 && m>=60 && s>=60) System.out.print("Commerce"); }}

CHAPTER-1 40 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

7. A bank announces new rates for Term Deposit Schemes for their customers and Senior Citizens as given below: Term Rate of Interest (General) Rate of Interest (Senior Citizen) Up to 1 year 7.5% 8.0% Up to 2 years 8.5% 9.0% Up to 3 years 9.5% 10.0% More than 3 years 10.0% 11.0% The 'senior citizen' rates are applicable to the customers whose age is 60 years or more. Write a program to accept the sum (p) in term deposit scheme, age of the customer and the term. The program displays the information in the following format: Amount Deposited Term Age Interest earned Amount Paid ××× ××× ××× ××× ××× Solution: import java.util.*; public class Q7 {public static void main(String args[]) { intage,term; double rate=0.0, intr, amt,p; Scanner sn=new Scanner(System.in); System.out.println("Enter the age, principal and term"); age=sn.nextInt(); p=sn.nextDouble(); term=sn.nextInt(); if(term<=1) if(age<=60) rate=7.5/100; else rate=8.0/100;

else if(term>1 && term<=2) if(age<=60) rate=8.5; else rate=9.0;

else if(term>2 && term<=3) if(age<=60) rate=9.5; else rate=10.0;

else if(term>3) if(age<=60) rate=10.0; else rate=11.0; intr=(p*rate*term)/100; amt=p+intr;

CHAPTER-1 41 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Amt deposited \t Term \t Age \t Interest \t Amt Paid"); System.out.println(p+"\t\t"+term+"\t"+age+"\t\t"+intr+"\t\t"+amt); }} 8. A courier company charges differently for 'Ordinary' booking and 'Express' booking based on the weight of the parcel as per the tariff given below: Weight of parcel Ordinary booking Express booking Up to 100 gm ` 80 ` 100 101 to 500 gm ` 150 ` 200 501 gm to 1000 gm ` 210 ` 250 More than 1000 gm ` 250 ` 300 Write a program to input weight of a parcel and type of booking ('O' for ordinary and 'E' for express). Calculate and print the charges accordingly. Solution: import java.util.*; public class Q8 { public static void main(String args[]) { Scanner in =new Scanner(System.in); double wt,chrg=0.0; char ch; System.out.println("Enter the weight of the parcel in grams"); wt=in.nextDouble(); System.out.println("Enter 'O' for ordinary and E' for express"); ch=in.next().toUpperCase().charAt(0); switch(ch) { case 'O' :if(wt<=100) chrg=80; else if(wt>100 &&wt<=500) chrg=150; else if(wt>500 &&wt<=1000) chrg=210; else if(wt>1000) chrg=250; System.out.println("Charge="+chrg); break; case 'E' :if(wt<=100) chrg=100; else if(wt>100 &&wt<=500) chrg=200;

CHAPTER-1 42 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

else if(wt>500 &&wt<=1000) chrg=250; else if(wt>1000) chrg=300; System.out.println("Charge="+chrg); break; default: System.out.println("Invalid entry"); }}} Menu Driven/Switch case programs 9. Write a menu driven program to calculate: 22 (a) Area of a circle = p*r2, where p = 7 (b) Area of a square = side*side (c) Area of a rectangle = length*breadth Enter 'c' to calculate area of circle, 's' to calculate area of square and 'r' to calculate area of rectangle. Solution: import java.util.*; public class Q9 {public static void main(String args[]) {double r,side,l,b,a; //radius, side, length, breadth, area char ch; Scanner obj=new Scanner(System.in); System.out.println("****MENU****"); System.out.println("Enter c for Area of Circle"); System.out.println("Enter s for Area of Square"); System.out.println("Enter r for Area of Rectangle"); System.out.println("Please enter your choice \n\n"); ch=obj.next().charAt(0); ch=Character.toLowerCase(ch); switch(ch) { case 'c': System.out.println("Enter the radius of the circle"); r=obj.nextDouble(); a=22.0/7*r*r; System.out.println("Area of Circle ="+a); break; case 's': System.out.println("Enter the side of the square"); side=obj.nextDouble(); a=side*side; CHAPTER-1 43 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Area of the Square="+a);break; case 'r': System.out.println("Enter the length of the breadth of the rectangle"); l=obj.nextDouble(); b=obj.nextDouble(); a=l*b; System.out.println("Area of the Rectangle="+a); break; default: System.out.println("Wrong choice"); break; }}} 10. Write a program using switch case to find the volume of a cube, a sphere and a cuboid. For an incorrect choice, an appropriate error message should be displayed. (a) Volume of a cube = s * s * s 4 22  (b) Volume of a sphere  *r*r*r     3 7  (c) Volume of a cuboid = l*b*h Solution: import java.util.*; public class Q10{ public static void main(String args[]) { Scanner in=new Scanner(System.in); int n; double s,r,l,b,h,v; System.out.println("Enter 1 to find the volume of a cube"); System.out.println("Enter 2 to find the volume of a sphere"); System.out.println("Enter 3 to find the volume of a cuboid"); n=in.nextInt(); switch(n) { case 1 :System.out.println("Enter the value of s"); s=in.nextDouble(); v=s*s*s; System.out.println("Volume of the cube is:"+v); break;

case 2 :System.out.println("Enter the value of r"); r=in.nextDouble(); v=(4.0/3.0)*(22.0/7.0)*r*r*r ; System.out.println("Volume of the sphere is:"+v);break;

case 3 :System.out.println("Enter the values l,b,h");

CHAPTER-1 44 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

l=in.nextDouble(); b=in.nextDouble(); h=in.nextDouble(); v=l*b*h; System.out.println("Volume of the cuboid is:"+v);break;

default:System.out.println("Invalid entry!!!");break; } }} 11. The relative velocity of two trains travelling in opposite directions is calculated by adding their velocities. In case, the trains are travelling in the same direction, the relative velocity is the difference between their velocities. Write a program to input the velocities and length of the trains. Write a menu driven program to calculate the relative velocities and the time taken to cross each other. Solution: import java.util.*; public class Q11 {public static void main(String acp[]) {Scanner ob=new Scanner(System.in); float v1,v2,len1,len2,rvel=0,time=0; int dir; System.out.println("Enter the velocities of the trains in metres/second"); v1=ob.nextFloat(); v2=ob.nextFloat(); System.out.println("Enter the lengths of the trains in metres"); len1=ob.nextFloat(); len2=ob.nextFloat(); System.out.println("Enter 1 for same direction or 2 for opposite direction"); dir=ob.nextInt(); switch(dir) {case 1 :rvel=Math.abs(v1-v2); time=(len1+len2)/rvel; break; case 2 :rvel=v1+v2; time=(len1+len2)/rvel; break; default :System.out.println("Invalid entry!"); } System.out.println("Relative velocity of the trains:"+rvel+"m/s"); System.out.println("Time taken for the trains to cross each other:"+time+"s"); }}

CHAPTER-1 45 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

12. In order to purchase an old car, the depreciated value can be calculated as per the tariff given below: No. of years used Rate of depreciation 1 10% 2 20% 3 30% 4 50% Above 4 years 60%

Write a menu driven program to input showroom price and the number of years the car is used ('1' for one year old, '2' for two years old and so on). Calculate the depreciated value. Display the original price of the car, depreciated value and the amount to be paid. Solution: import java.util.*; public class Q12{ public static void main(String g[]){ int n; //number of years used double price,drate,dval,amt; //price,depreciationrate,depreciated value Scanner obj=new Scanner(System.in); System.out.println("Enter the showroom price of the car"); price=obj.nextDouble(); System.out.println("Enter the number of years, the car had been used"); n=obj.nextInt(); switch(n) { case 0: case 1 :drate=10.0/100; break; case 2 :drate=20.0/100; break; case 3 :drate=30.0/100; break; case 4 :drate=50.0/100; break; default :drate=60.0/100; } dval=price*drate; amt=price - dval; System.out.println("\n\nOriginalPrice :Rs."+price); System.out.println("Depreciated Value :Rs."+ dval); System.out.println("Amount Paid for the car :Rs."+amt); }}

CHAPTER-1 46 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Unit VIII : Iterative Constructs in Java

EXERCISES

I. Fill in the blanks : 1. When the statements are repeated sequentially a number of times in a program, the construct is known as ...... 2. For loop is also known as ...... controlled loop. 3...... loop is called an exit controlled loop. 4...... loop executes at least once, if the condition is false. 5...... loop checks the condition first before its execution. 6. To find the sum of any ten numbers, the loop will run ...... times. Ans. 1. loop 2. entry 3. do-while 4. do-while 5. while 6. ten II. Answer the following questions: 1. What is 'for' loop? What are the parameters used in 'for' loop? Ans. A ‘for’ loop is an entry controlled loop where the condition is checked in the beginning. It is used when the number of iterations is fixed and known. The parameters used in a ‘for’ loop are as follows:  initial value of the loop variable  test condition (Only when the condition is true the body of the loop is executed)  step value (increment / decrement value to alter the value of the loop variable) 2. Define the following with their constructs: (a) Entry controlled loop (b) Exit controlled loop Ans. (a) Entry controlled loop - It checks the condition before executing the body of the loop. If the condition is false, the statements within the body of the loop are not executed. The ‘for’ loop and the ‘while’ loop are the two constructs under this category. (b) Exit controlled loop - It checks the condition after executing the body of the loop. Even if the condition is false, the statements within the body of the loop are executed atleast once. The ‘do-while’ loop is the only construct under this category. 3. Write down the syntax of : (a) do - while (b) while loop Ans. (a) do {

}while( );

(b) while( ) { } CHAPTER-1 47 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

4. What is the purpose of using (a) break statement (b) continue statement in a program? Ans. (a) The break statement terminates the entire loop (ie) all the forthcoming iterations of the loop. (b) The continue statement terminates only the current iteration and continues the loop from the next iteration. 5. Distinguish between while and do-while loop. [ICSE 2018] Ans. while loop  It is an entry-controlled loop.  It checks the condition before executing the body of the loop. If the condition is false, the statements within the body of the loop are not executed. do - while loop  It is an exit-controlled loop.  It checks the condition after executing the body of the loop. Even if the condition is false, the statements within the body of the loop are executed atleast once. 6. What is meant by an infinite loop? Give an example. [ICSE 2008] Ans. A loop which will never terminate or a loop which goes on infinitely is known as an infinite loop. Example:for( ; ;) System.out.print("D"); In the above example, D is printed again and again indefinitely since a terminating condition is not given. 7. State one difference and one similarity between while loop and do-while loop. [ICSE 2010] Ans. Similarity :  Both the loops are used for executing a set of statements repeatedly.  Both the loops evaluate a logical condition for terminating the loop. Difference : while loop  It is an entry-controlled loop.  It checks the condition before executing the body of the loop. If the condition is false, the statements within the body of the loop are not executed. do - while loop  It is an exit-controlled loop.  It checks the condition after executing the body of the loop. Even if the condition is false, the statements within the body of the loop are executed atleast once. III. Predict the output: 1. The following is a segment of a program. x = 1; y = 1; if(n>0) CHAPTER-1 48 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ x = x + 1; y = y +1; } What will be the value of x and y, if n assumes a value: (i) 1 (ii) 0 ? [ICSE 2009] Ans. (i) x=2 y=2 (ii) x=1 y=1 2. Analyze the following program segment and determine how many times the body of the loop will be executed (show the working). x = 5; y = 50; while(x<=y) { y = y/x; System.out.println(y); } [ICSE 2009] Ans. y 50/5 = 10 10/5 = 2 The loop is executed twice. 3. What will be the output of the following code? int m=2; int n=15; for(int i=l;i<5;i++) m++; - - n; System.out.println(“m=”+m); System.out.println(“n=”+n); [ICSE 2010] Ans. m=6 n=14 4. Analyze the following program segment and determine how many times the loop will be executed. What will be the output of the program segment? int k=l,i=2; while(++i<6) k*=i; System.out.println(k); [ICSE 2010] Ans. 3 times 60 5. Give the output of the following program segment and also mention the number of times the loop is executed. int a,b; CHAPTER-1 49 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

for(a=6;b=4;a<= 4; a=a+ 6) { if(a%b==0) break; } System.out.println(a); [ICSE 2017] Ans. 6 0 times 6. Give the output of the following program segment and also mention how many times the loop is executed. int i; for(i = 5; i >10; i ++) System.out.println( i ); System.out.println(i * 4); [ICSE 2018] Ans. 20 0 times IV. Rewrite the following programs: 1. Using for loop: [ICSE 2017] int i=l; int d=5; do { d=d*2; System.out.println(d); i++ } while (i<=5); Ans. int d=5; for(int i=1;i<=5;i++) {d=d*2; System.out.println(d); } 2. Using while loop: import java.util.*; class Number { public static void main(String args[]) { int n,r; Scanner in = new Scanner(System.in);

CHAPTER-1 50 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println(“Enter a number”); n=in.nextlnt(); do { r=n%10; n=n/10; System.out.println(r); } while(n!=0); } } Ans. import java.util.*; class Number{ public static void main(String args[]){ int n,r; Scanner in=new Scanner(System.in); System.out.println("Enter a number"); n=in.nextInt(); while(n!=0) {r=n%10; n=n/10; System.out.println(r); } }} V. Unsolved Java Programs: 1. Write the programs in Java to display the first ten terms of the following : (a) 0, 1, 2, 3, 6, ...... (b) 1, -3, 5, -7, 9, ...... (c) 0, 3, 8, 15, ...... (d) 1, 11, 111, 1111, ...... (e) 1, 12, 123, 1234, ...... Solution: public class Q1a { public static void main(String args[]) { int a=0,b=1,c=2,d=0; System.out.println("TRIBONACCI SERIES");//optional System.out.print(a+","+b+","+c+","); for(int i=1;i<=10;i++) { d=a+b+c; System.out.print(d+","); a=b;

CHAPTER-1 51 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

b=c; c=d; } }}

public class Q1b { public static void main(String args[]) { int x=1; for(int i=1;i<=10;i++) { if(i%2==0) System.out.print((x*-1)+","); else System.out.print(x+","); x+=2; }}}

public class Q1c { public static void main(String args[]) { int x=0,y=1,i; for(i=1;i<=10;i++) { System.out.print(x+" "); y=y+2; x=x+y; } }}

public class Q1d {public static void main(String args[]) { int s=1; System.out.print(s+","); for(int i=1;i<10;i++) {s=(s*10)+1; System.out.print(s+","); }}}

public class Q1e { public static void main(String args[]) { for(int i=1;i<=10;i++)

CHAPTER-1 52 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ for(int j=1;j<=i;j++) System.out.print(j); System.out.print(" , "); } }}

2. Write the programs in Java to find the sum of the following series: (a) S = 1 + 1 + 2 + 3 + 5 + ...... to n terms (b) S = 2 - 4 + 6 - 8 + ...... to n (c) S = 1 + (1 + 2) + (1 + 2 + 3) + ...... + (1 + 2 + 3+ ...... + n) (d) S = 1 + (1 * 2) + (1 * 2 * 3) + ...... + (1 * 2 * 3 * ...... * n) 1 2 1  2  3 1 2  3......  n (e) S 1    ...... [ICSE 2007] 1 2 1* 2 * 3 1* 2 * 3......  n Solution: import java.util.*; public class Q2a { public static void main(String args[]) { Scanner obj=new Scanner(System.in); int a=0,b=1,c=0,sum=0,n; System.out.println("FIBONACCI SERIES"); System.out.println("Enter the value of n....that is, the number of terms"); n=obj.nextInt(); System.out.print(a+","+b+","); sum=a+b; for(int i=1;i<=(n-2);i++)//n-2 since 2 terms are printed outside loop { c=a+b; System.out.print(c+","); sum+=c; a=b; b=c; } System.out.println("\n Sum of the above series=" +sum); }}

import java.util.*; public class Q2b { public static void main(String args[]) { int sum=0,n; Scanner obj=new Scanner(System.in);

CHAPTER-1 53 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Enter the number of terms...n"); n=obj.nextInt(); for(int i=2;i<=(2*n);i=i+2) //2n because the each term is a multiple of 2 { if(i%4==0) sum=sum-i; else sum=sum+i; } System.out.println("Sum of the series= "+sum); }}

import java.util.*; public class Q2c { public static void main(String arg[]) {int n,tmp=0,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of n....no. of terms"); n=obj.nextInt(); for(int i=1;i<=n;i++) { tmp=0; //reset to zero for each value of i for(int j=1;j<=i;j++) tmp=tmp+j; //if i=4,tmp=(1+2+3+4) sum=sum+tmp; } System.out.println("Sum of the Series= "+sum); }}

import java.util.*; public class Q2d {public static void main(String arg[]) {int n,fact,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of n....no. of terms"); n=obj.nextInt(); for(int i=1;i<=n;i++) {fact=1; //reset to zero for each value of i for(int j=1;j<=i;j++) fact=fact*j; //if i=4,tmp=(1*2*3*4) sum=sum+fact; } System.out.println("Sum of the Series= "+sum);

CHAPTER-1 54 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

}}

import java.util.*; public class Q2e { public static void main(String arg[]) { int n; double num,den,term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the VALUE OF n ....not the number of TERMS");// n=obj.nextInt(); for(int i=1;i<=n;i++) {num=0; //reset num to 0 to accumulate sum den=1; //reset den to 1 to accumulate product for(int j=1;j<=i;j++) { num=num+j; den=den*j; } term=(double)num/den; System.out.println(num+"/"+den); //optional print sum=sum+term; //sum of terms } System.out.println("Sum of the Series= "+sum); }} 3. Write the programs to find the sum of the following series: (a) S = a + a2 + a3 + ...... + an (b) S = (a + 1) + (a + 2) + (a + 3) + ...... + (a + n) a a a a a (c) S     + ...... + [ICSE 2008] 2 5 8 11 20 1 1 3 (d) S     ...... to n a a2 a 3 (e) S = a – a3 + a5 – a7 + ...... to n Solution: import java.util.*; public class Q3a {public static void main(String args[]) {int a,n; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextInt();

CHAPTER-1 55 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i++) { term=Math.pow(a,i); System.out.println(term);//optional print sum=sum+term; } System.out.println("Sum of the series="+sum); }}

import java.util.*; public class Q3b {public static void main(String args[]) {int a,n,cnt=1,term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextInt(); System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i++) {term=a+i; sum=sum+term; } System.out.println("Sum of the series= "+sum); }}

import java.util.*; public class Q3c {public static void main(String args[]) {float sum=0,term=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); int a=obj.nextInt(); for(int i=2;i<=20;i=i+3) { term= (float)a/i; sum+=term; //sum=sum+term } System.out.println("Sum of the series= "+sum); }}

CHAPTER-1 56 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

import java.util.*; public class Q3d {public static void main(String args[]) {int a,n; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextInt(); System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i++) { term=i/Math.pow(a,i); sum=sum+term; } System.out.println("The sum of the series is "+sum); }}

import java.util.*; public class Q3e {public static void main(String args[]) {int a,n,cnt=1; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextInt(); System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i=i+2) {term=Math.pow(a,i); System.out.println(term); //optional print if(cnt%2==0) sum=sum - term; else sum=sum + term; cnt++; } System.out.println("Sum of the series is "+(float)sum); }} 4. Write a program to enter two numbers and check whether they are co-prime or not. [Two numbers are said to be co-prime, if their HCF is 1 (one).] Sample Input: 14, 15 Sample Output: They are co-prime.

CHAPTER-1 57 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Solution: import java.util.*; public class Q4{ void sampleMethod(int a,int b) { int p,gcd=0; p=Math.min(a,b); for(int i=1;i<=p;i++) { if(a%i==0 &&b%i==0) gcd=i; } if(gcd==1) System.out.println("The numbers are co-prime"); else System.out.println("The numbers are not co-prime"); }} 5. Write a program to input a number. Display the product of the successors of even digits of the number entered by user. Input: 2745 Output: 15 Solution: public class Q5 { public static void sampleMethod(int n) { int d,pdt=1; while(n>0) { d=n%10; if(d%2==0) { d++; //d has successor of even number pdt=pdt*d; } n=n/10; } System.out.println(pdt); }} 6. Write a program to input a number and check and print whether it is a or not. [Pronic number is the number which is the product of two consecutive integers.] Examples: 12 = 3 * 4 20 = 4 * 5 42 = 6 * 7 Solution: import java.util.*; public class Q6 CHAPTER-1 58 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{public static void main(String args[]) { int flag=0; Scanner ob=new Scanner(System.in); System.out.println("Enter the number"); int n=ob.nextInt(); for(int i=1;i<=n/2;i++) { if(n==i*(i+1)) {flag=1; break; }} if (flag==1) System.out.println("It is a pronic number"); else System.out.println("It is not a pronic number"); }} [ICSE 2018] 7. A is said to be 'Twisted Prime', if the new number obtained after reversing the digits is also a prime number. Write a program to accept a number and check whether the number is Twisted Prime' or not. Sample Input: 167 Sample Output: 761 167 is a 'Twisted Prime'. Solution: import java.util.*; public class Q7 { static booleancheckPrime(int n) //MTD TO CHK WHETHER PRIME { int cnt=0; for(int i=1;i<=n;i++) { if(n%i==0) cnt++; } if(cnt==2) return true; else return false; }

public static void main(String args[]) //MAIN MTD {int num,d,rev=0; Scanner obj=new Scanner(System.in); System.out.println("Enter a prime number"); num=obj.nextInt(); if(checkPrime(num)==true) { do{

CHAPTER-1 59 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

d=num%10; rev=(rev*10)+d; num=num/10; }while(num>0); } if(checkPrime(rev)==true) System.out.println("It is a twisted prime"); else System.out.println("Not a twisted prime number"); }} 8. Write a program, to input a number and check whether it is a prime number or not. If it is not a prime number then display the next number that is prime. Sample Input: 14 Sample Output: 17 Solution: import java.util.*; public class Q8 { public static void main(String args[]) {int flag=1,cnt=0,n; Scanner obj=new Scanner(System.in); System.out.println("Enter the number"); n=obj.nextInt(); while(true) { System.out.println("n="+n); cnt=0; for(int i=1;i<=n;i++) { if(n%i ==0) cnt++; }

if(cnt==2) {System.out.print(n+" is a Prime number"); break; } else n++; }}} 9. A number is said to be Duck if the digit zero is (0) present in it. Write a program to accept a number and check whether the number is Duck or not. The program displays the message accordingly. (The number must not begin with zero) Sample Input: 5063 Sample Output: It is a Duck number. Sample Input: 7453 Sample Output: It is not a Duck number. CHAPTER-1 60 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Solution: import java.util.*; public class Q9 { public static void main(String jj[]) { int n,d,flag=0; Scanner in=new Scanner(System.in); System.out.println("Enter the number "); n=in.nextInt(); do{ d=n%10; if(d==0) {flag=1; break; } else n=n/10; }while(n>0);

if(flag==1) System.out.println("It is a Duck number"); else System.out.println("It is not a Duck number"); }} 10. Write a program that inputs number of runs made by a cricket player on each ball. Entering runs as -1 should display the message that player is out. Finally it displays the number of runs made and balls played by the player. Solution: import java.util.*; public class Q10 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int cnt=0,run,sum=0; while(true) { System.out.println("Enter the number of runs scored"); run=in.nextInt(); if(run>=0) { sum+=run; cnt++; } else {System.out.println("Player is out");

CHAPTER-1 61 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

break; } } System.out.println("Total runs scored="+sum); System.out.println("Total number of balls played="+cnt); } } 11. A computerised bus charges fare from each of its passengers based on the distance travelled as per the tariff given below: Distance (in km) Charges First 5 km ` 80 Next 10 km ` 10/km More than 15 km ` 8/km As the passenger enters the bus, the computer prompts 'Enter distance you intend to travel'. On entering the distance, it prints his ticket and the control goes back for the next passenger. At the end of journey, the computer prints the following: (i) the number of passenger travelled (ii) total fare received Write a program to perform the above task. Solution: import java.util.*; public class Q11 {public static void main(String args[]) { Scanner in=new Scanner(System.in); int cnt=0; double dist=0.0,chrg=0.0,tot=0.0; System.out.println("At any time,type 0 to quit"); while(true) {System.out.print("Enter the distance you intend to travel :"); dist=in.nextInt(); if(dist==0) break; else {if(dist<=5.0) chrg=80.0; else if(dist<=15.0) chrg=80.0 + 10*(dist-5.0); else if(dist>15.0) chrg=80.0 + (10.0*10.0) + (dist-15.0)*8.0; System.out.println("Ticket Cost:Rs."+chrg); tot=tot+chrg; cnt++; } //end of else block

CHAPTER-1 62 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

} System.out.println("\n\nThe number of passengers travelled :"+cnt); System.out.println("The total fare received :"+tot); }} 12. A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result is equal to the original two-digit number. Example: Consider the number 59. Sum of digits = 5 + 9 = 14 Product of digits = 5 * 9 = 45 Sum of the sum of digits and product of digits = 14 + 45 = 59 Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value is equal to the number input, then display the message "Special two-digit number" otherwise, display the message "Not a special two-digit number". [ICSE 2014] Solution: import java.util.*; public class Q12 {public static void main(String args[]) {Scanner ob=new Scanner(System.in); int num,rd,ld,pdt,sum=0; System.out.println("Enter a two digit number"); num=ob.nextInt(); rd=num%10; ld=num/10; pdt=rd*ld; sum=rd+ld; if(num==(sum+pdt)) System.out.println("It is a special 2 digit"); else System.out.println("It is not a special two digit number"); }} 13. Write a program to input a number. Check and display whether it is a Niven number or not. (A number is said to be Niven which is divisible by the sum of its digits). Example: Sample Input 126 Sum of its digits = 1 + 2 + 6 = 9 and 126 is divisible by 9. [ICSE 2016] Solution: import java.util.*; public class Q13 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int n,sum=0,d,k;

CHAPTER-1 63 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Enter a number"); n=in.nextInt(); k=n; do { d=n%10; sum=sum+d; n=n/10; } while(n!=0); if(k%sum==0) System.out.println("It is a Niven number"); else System.out.println("It is not a Niven number"); }} 14. Write a program to accept a number and check whether it is a 'Spy Number' or not. (A number is spy if the sum of its digits equals the product of its digits.) Example: Sample Input: 1124 Sum of the digits = 1 + 1+2 + 4 = 8 Product of the digits = 1 * 1 * 2 * 4 = 8 [ICSE 2017] Solution: import java.util.*; public class Q14 { public static void main(String args[]) {Scanner in=new Scanner(System.in); int n,prd=1,sum=0,d; System.out.println("Enter a number"); n=in.nextInt(); do { d=n%10; sum+=d; prd*=d; n=n/10; } while(n>0);

if(prd==sum) System.out.println("It is a spy number"); else System.out.println("It is not a spy number"); }}

CHAPTER-1 64 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

15. You can multiply two numbers 'm' and 'n' by repeated addition method. For example, 5 * 3 = 15 can be performed by adding 5 three times ==> 5 + 5 + 5 = 15 Similarly, successive subtraction of two numbers produces 'Quotient' and 'Remainder' when a number 'a' is divided by 'b' (a>b). For example, 5/2 => Quotient = 2 and Remainder =1 Follow steps shown below: Process Result Counter 5-2 3 1 3-2 1 2 Sample Output: The last counter value represents 'Quotient' ==> 2 The last result value represents 'Remainder' ==> 1 Write a program to accept two numbers. Perform multiplication and division of the numbers as per the process shown above by using switch case statement. Solution: import java.util.*; public class Q15 { public static void main(String az[]) {int a,b,x,res=0,Q=0,j; Scanner scn=new Scanner(System.in); System.out.println("***Multiplication/Division of Integers***"); System.out.println("1.Multiplication"); System.out.println("2.Division"); System.out.println("Enter your choice 1 (or) 2"); switch(scn.nextInt()) {case 1: //Multiplication is Repeated Addition System.out.print("Enter the multiplicand :"); a=scn.nextInt(); System.out.print("Enter the multiplier :"); b=scn.nextInt(); for(int i=1;i<=b;i++) res=res+a; System.out.println(a+" * "+b+" = "+res); break;

case 2: //Division Is Repeated Subtraction System.out.print("Enter the dividend :"); a=scn.nextInt(); System.out.print("Enter the : "); b=scn.nextInt(); while(a>=0) {if((a-b)<0) break; a=a-b;

CHAPTER-1 65 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Q++; } System.out.println("Quotient="+Q + "\t" + "Remainder="+a); break;

default: System.out.println("Invalid entry!"); } }} 16. Using a switch statement, write a menu driven program to: (a) generate and display the first 10 terms of the Fibonacci series 0, 1, 1, 2, 3, 5 ...... The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. (b) find the sum of the digits of an integer that is input by the user. Sample Input: 15390 Sample Output: Sum of the digits = 18 For an incorrect choice, an appropriate error message should be displayed. Solution: import java.util.*; public class Q16{ public static void main(String arg[]){ int n,r,sum=0,a=0,b=0,c=1; Scanner ob=new Scanner(System.in); System.out.println("***MENU***"); System.out.println("1.First ten terms of the Fibonacci series"); System.out.println("2.Sum of the digits of the number entered"); System.out.println("Enter your choice..1 or 2"); switch(ob.nextInt()) {case 1: System.out.println("**Fibonacci Series***"); for(int i=1;i<=10;i++) //FIRST 10 TERMS {a=b; b=c; c=a+b; System.out.print(a +", "); } break;

case 2: System.out.println("***Sum of Digits*** \n Enter the number"); n=ob.nextInt(); do{

CHAPTER-1 66 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

r=n%10; sum+=r; n=n/10; } while(n>0); System.out.println("The sum of the digits is "+sum); break;

default: System.out.println("Invalid entry"); } }}

Unit IX : Nested Loop

EXERCISES

I. Write whether the following statements are True/False: 1. Nested loop contains a single loop. 2. When break statement is applied, it terminates the loop. 3. The outer loop follows next iteration when iterations of inner loop is over. 4. Nested loop means the using of two or more loops in a program. 5. Labelled break statement allows the next iteration of the loop from any place of looping structure. 6. In a nested loop, break and continue can be used simultaneously. Answer. 1. false 2. true 3. true 4. false 5. false 6. false II. Fill in the blanks: 1...... break is used to terminate an outer loop. 2. A loop within another loop is called ...... 3. Termination of ...... loop takes place before ...... loop. 4...... statement will repeat a loop for the next iteration after ignoring some statements of the loop. 5...... statement terminates a switch-case statement as well as a loop. Answer. 1. labelled 2. nested loop 3. inner, outer 4. continue 5. break III. Answer the following questions: 1. What is a nested loop? Ans. When a loop is used within another loop, it is called as a nested loop. In the example given below, the outer loop executes thrice. For each iteration of the outer loop, the inner loop is executed twice. Hence, the pattern printed will be : MM MM MM

CHAPTER-1 67 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Example: for(int i=1;i<=3;i++) {for(int j=1;j<=2;j++) System.out.print("M"); System.out.println(); } 2. Write down the syntax of a nested for loop. Ans. for(initialization ;condition; step value) { // body of outer loop

for(initialization ;condition; step value) { //body of inner loop } // body of outer loop } 3. What action will you take to terminate an outer loop from the block of an inner loop? Ans. The termination of outer loop from the block of inner loop can be done by using the break statement along with label. In the example given below, the outer loop is terminated when the value of the inner loop variable j is equal to 2. Example: int i, j; outer: for(int i=1;i<=5;i++) {for(j=1;j<=3;j++) { if(j==2) break outer; }} 4. Give two differences between 'Break' and 'Continue'. Ans. break  break statement is used to terminate a block in which it exists.  break statement can be used in switch-case as well as in loop statements continue  continue statement is used to move the control to the next iteration of the loop ignoring other statements.  continue statement can be used only in loops ( not in switch-case) 5. What is significance of 'break outer' and 'continue outer' in a nested loop? Ans.

CHAPTER-1 68 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

break outer  break outer is a labelled break statement used to terminate the outer loop continue outer  continue outer is a labelled continue statement which is used to skip further iterations of the inner loop and continue with the outer loop iterations. 6. Write down the constructs (syntax) of: (a) Nested do-while loop (b) Nested while loop Ans. Nested do-while loop do { do{

}while();

}while();

Nested while loop while( ) { while( ) {

} } IV. Unsolved Programs: 1. Write programs to find the sum of the following series: 3 5 7 (a) S 1     ...... to n 2! 3! 4! Solution: import java.util.*; public class Q1a { public static void main(String args[]) {int a=1,n,fact=1; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of n"); n=obj.nextInt(); CHAPTER-1 69 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

for(int i=1;i<=n;i++) {fact=1; for(int j=1;j<=i;j++) fact=fact*j;

term=(double)a/fact; System.out.println(a+"/"+fact);//OPTIONAL PRINT a=a+2; sum=sum+term; } System.out.println("Sum of the series= "+sum); }} a a a a (b) S a     ...... to  2! 3! 4! n! Solution: import java.util.*; public class Q1b {public static void main(String args[]) {int a,n; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextInt(); System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i++) { term=Math.pow(a,i)/i; System.out.println(term);//optional print sum=sum+term; } System.out.println("Sum of the series="+sum); }} a a a (c) S a     ...... to n 2! 3! 4! Solution: import java.util.*; public class Q1c {public static void main(String args[]) {int n,cnt=1; double a,fact,term,sum=0;

CHAPTER-1 70 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextDouble(); System.out.println("Enter the value of n"); n=obj.nextInt(); for(int i=1;i<=n;i++) {fact=1; for(int j=1;j<=i;j++) fact=fact*j; term=a/fact; if(cnt%2==0) //even term sum=sum - term; else //odd term sum=sum + term; cnt++; }System.out.println("Sum of the series= "+(float)sum); }} a a a a a (d) S      ...... to  2! 3! 4! 5! 10! Solution: import java.util.*; public class Q1d {public static void main(String args[]) {int n,cnt=1; double a,fact,term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the value of a"); a=obj.nextDouble(); for(int i=2;i<=10;i++) {fact=1; for(int j=1;j<=i;j++) fact=fact*j;

term=a/fact; System.out.println(term);//optional print

if(cnt%2==0) //even term sum=sum - term; else //odd term sum=sum + term; cnt++; CHAPTER-1 71 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

}System.out.println("Sum of the series= "+(float)sum); }} 2 3 5 7 (e) S      ...... to n a a2 a 3 a 4 Solution: import java.util.*; public class Q1e { public static void main(String args[]) { int a,i,n=1,cnt,t,iter=0; double term,sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the number of terms"); t=obj.nextInt(); System.out.println("Enter the value of a"); a=obj.nextInt();

while(true) { cnt=0; //reset to zero for(i=1;;i++) { if(n%i==0) cnt++; if(i==n)break; }

if(cnt==2) //if cnt is 2 then the number is prime {term=i/Math.pow(a,iter); if(t==iter) break; else sum+=term; } n++;

} System.out.println(sum); }} 2. Write a program to input two numbers and check whether they are twin prime numbers or not.

Solution: CHAPTER-1 72 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

import java.util.*; public class Q2 {public static void main(String args[]) { int a,b,cnt1=0,cnt2=0; Scanner sn=new Scanner(System.in); System.out.println("Enter two integers"); a=sn.nextInt(); b=sn.nextInt();

for(int i=1;i<=a/2;i++) { if(a%i==0) cnt1++; //for prime numbers cnt will be 1 when the loop runs till half the number } for(int j=1;j<=b/2;j++) { if(b%j==0) cnt2++; //for prime numbers cnt will be 1 } if(cnt1==1&& cnt2==1 &&Math.abs(a-b)==2) System.out.println("The numbers are Twin Prime"); else System.out.println("The numbers are not Twin Prime"); }} 3. Write a program to display all the numbers between 100 and 200 which don't contain zeros at any position. For example: 111, 112, 113, ...... , 199 Solution: public class Q3 {public static void main (String args[]) { int n,d; for(int i=101;i<=199;i++) { n=i; while(n>0) {d=n%10; if(d==0) break; n=n/10; }

if(n<=0) System.out.println(i); } }}

CHAPTER-1 73 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

4. Write a program to display all prime palindrome numbers between 10 and 1000. For example: 11, 101, 131, 151, ...... Solution: public class Q4 {public static void main(String args[]) { System.out.println("Prime palindrome numbers:"); int n,cnt=0,sum=0,d;

for(int i=10;i<=1000;i++) {cnt=0; //reset to zero for every number sum=0; //reset sum for every number for(int j=1;j<=i;j++) {if(i%j==0) cnt++; }

if(cnt==2) { n=i; do {d=n%10; sum=sum*10+d; n=n/10; }while(n>0);

if(i==sum) System.out.println(i); }}}} 5. In an entrance examination, students have been appeared in English, Maths and Science papers. Write a program to calculate and display average marks obtained by all the students. Take number of students appeared and marks obtained in all three subjects;- by every student along with the name as inputs. Display the name, marks obtained in three subjects and the average of all the students. Solution: import java.util.*; public class Q5 { public static void main(String args[]) { Scanner in=new Scanner(System.in); String name; double math,eng,sci,avg; int n;

CHAPTER-1 74 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("Enter the number of students"); n=in.nextInt(); for(int i=1;i<=n;i++) {System.out.print("Enter the name of the student :"); name=in.next();

System.out.print("Enter the marks scored in math :"); math=in.nextDouble(); System.out.print("Enter the marks scored in english :"); eng=in.nextDouble(); System.out.print("Enter the marks scored in science :"); sci=in.nextDouble();

avg=(math+sci+eng)/3; System.out.println("Name:" + name); System.out.println("Average:"+avg); System.out.println(); }}} 6. Write a program in Java to enter a number containing three digits or more. Arrange the digits of the entered number in ascending order and display the result. Sample Input: Enter a number 4972 Sample Output: 2, 4, 7, 9 Solution: import java.util.*; public class Q6 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int num,n,d; String s=""; System.out.println("Enter a number with 3 or more digits"); num=in.nextInt();

for(int i=9;i>=0;i--) { n=num; do{ d=n%10; if(d==i) {s=d+","+s; } n=n/10; }while(n>0); CHAPTER-1 75 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

} System.out.println(s); }} 7. Write a program to input a number and check whether it is 'Magic Number' or not. Display the message accordingly. A number is said to be a magic number if the eventual sum of digits of the number is one. Sample Input : 55 Then, 5 + 5 = 10, 1 + 0 = 1 Sample Output: Hence, 55 is a Magic Number. Similarly, 289 is a Magic Number. Solution: import java.util.*; public class Q7 {public static void main(String args[]) {Scanner ob=new Scanner(System.in); int n,sum=0,d; System.out.println("Enter the number"); n=ob.nextInt(); do{ sum=0; do{ d=n%10; sum+=d; n=n/10; }while(n>0); System.out.println(sum); //Optional print n=sum; }while(sum>9);

if(sum==1) System.out.println("Magic Number"); else System.out.println("Not a magic number"); }} 8. A number is said to be Multiple , when divided by the sum of its digits, produces another 'Harshad Number'. Write a program to input a number and check whether it is a Multiple Harshad Number or not. (When a number is divisible by the sum of its digit, it is called 'Harshad Number Sample Input: 6804 Sample Output : Multiple Harshad Number. Solution:

CHAPTER-1 76 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

import java.util.*; public class Q8 {public static void main(String args[]) { int n,p,d,sum=0,cnt=0; Scanner obj=new Scanner(System.in); System.out.println("*** Multiple Harshad Number***"); System.out.println("Enter the number"); n=obj.nextInt(); do { p=n; //store the original number in 'p' before altering n sum=0; //clear sum for every new value of n (ie) p do{ d=n%10; sum+=d; //accumulate the sum of the digits in sum n=n/10; }while(n>0);

if(p%sum==0) {n=p/sum; //The quotient is used for the next iteration cnt++; //cnt=1 implies HARSHAD/NIVEN ...cnt>1 multiple harshad } System.out.println(n); //OPTIONAL PRINT }while(n>9);

if(cnt>1) System.out.println("It is a Multiple Harshad Number"); else System.out.println("It is a not a Multiple Harshad Number"); }} 9. Write the programs to display the following patterns: (a) 1 3 1 5 3 1 7 5 3 1 9 7 5 3 1 Solution: public class Q9a { public static void main(String ar[]) { int i,j;

for(i=1;i<=9;i=i+2) {for(j=i;j>=1;j=j-2) System.out.print(j+" "); CHAPTER-1 77 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println(); } }} (b) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Solution: public class Q9b { public static void main(String ar[]) {System.out.println("------"); int i,j,p=1; for(i=5;i>=1;i--) { System.out.println(); for(j=i;j>=1;j--) { System.out.print(p+"\t"); p++; } }} (c) 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Solution: public class Q9c { public static void main(String ar[]) {System.out.println("\n------"); int i,j,p=15; for(i=5;i>=1;i--) {System.out.println(); for(j=i;j>=1;j--) {System.out.print(p+"\t"); p--; }}} (d) 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1

CHAPTER-1 78 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Solution: public class Q9d { public static void main(String ar[]) {System.out.println("\n------"); int i,j; for(i=1;i<=5;i++) {System.out.println(); for(j=1;j<=i;j++) { if(j%2!=0) System.out.print("1"+" "); else System.out.print("0"+" "); }}} (e) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 Solution: public class Q9e { public static void main(String ar[]) { System.out.println("\n------"); k=0; for(i=5;i>=1;i--) { for(p=0;p

for(j=i;j>=1;j--) System.out.print(i);

System.out.println(); } (f) 1 2 3 4 5 2 2 3 4 5 3 3 3 4 5 4 4 4 4 5 5 5 5 5 5 Solution:

CHAPTER-1 79 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

public class Q9f { public static void main(String ar[]) {System.out.println("\n------"); int a,b,c,p=2; for(a=1;a<=5;a++) { for(b=1;b<=a;b++) System.out.print(a+" "); //a...(row number) 2 is printed twice and so on

for(c=p;c<=5;c++) System.out.print(c+" ");

System.out.println(); p++; }} (g) * *# *#* *#*# *#*#*

Solution: public class Q9g { public static void main(String ar[]) {System.out.println("\n------"); int i,j; for(i=1;i<=5;i++) { System.out.println(); for(j=1;j<=i;j++) { if(j%2!=0) System.out.print("* "); else System.out.print("# "); }}} (h) 5 4 3 2 1 5 4 3 2 5 4 3 5 4 5 Solution: public class Q9h

CHAPTER-1 80 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ public static void main(String ar[]) {System.out.println("\n------"); int i,j; for(i=1;i<=5;i++) {System.out.println(); for(j=5;j>=i;j--) System.out.print(j+" "); }} (i) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Solution: public class Q9i { public static void main(String ar[]) System.out.println("\n------"); int i,j,p=1; for(i=1;i<=5;i++) { System.out.println(); for(j=1;j<=i;j++) System.out.print(p++ +"\t"); }} 10. Write a program to generate a triangle or an inverted triangle till n terms based upon and 1000. [ICSE 2009] Example 1: Example 2: Input: Type 1 for a triangle and Input: Type 1 for a triangle and Type 2 for an inverted triangle Type 2 for an inverted triangle Enter your choice 1 Enter your choice 2 Enter the number of terms 5 Enter the number of terms 6 Sample Output: Sample Output: 1 6 6 6 6 6 6 2 2 5 5 5 5 5 3 3 3 4 4 4 4 4 4 4 4 3 3 3 5 5 5 5 5 2 2 1 Solution: import java.util.*; public class Q10 { public static void main(String az[])

CHAPTER-1 81 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ int n,i,j,x; Scanner sn=new Scanner(System.in); System.out.println("*****MENU****"); System.out.println("1. Pattern - Triangle "); System.out.println("2. Pattern - Inverted Triangle "); System.out.println("Enter your choice 1 (or) 2"); x=sn.nextInt(); switch(x) { case 1: System.out.println("Enter the number of terms"); n=sn.nextInt(); for(i=1;i<=n;i++) { System.out.println(); for(j=1;j<=i;j++) System.out.print(i); } break;

case 2:System.out.println("Enter the number of terms"); n=sn.nextInt(); for(i=n;i>=1;i--) { System.out.println(); for(j=i;j>=1;j--) System.out.print(i); } break;

default: System.out.println("Invalid Entry"); } }} 11. Using the switch statement, write a menu driven program for the following: [ICSE 2016] (a) To print the Floyd's triangle: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

CHAPTER-1 82 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

(b) To display the following pattern: I IC ICS ICSE For an incorrect option, an appropriate error message should be displayed. Solution: import java.util.*; public class Q11{ public static void main(String ag[]) {Scanner ob=new Scanner(System.in); int p=1,i,j; char ch; System.out.println("***Menu Driven Program using if-else***"); System.out.println("Enter 'a' to Print Floyd's triangle"); System.out.println("Enter 'b' to print the pattern of the word ICSE"); System.out.println("Enter your choice"); ch=ob.next().charAt(0); System.out.println(); if(ch=='a' || ch=='A') { for(i=1;i<=5;i++) {for(j=1;j<=i;j++) System.out.print(p++ +"\t"); System.out.println(); } } else if(ch=='b' || ch=='B') { String s="ICSE"; for(i=0;i<=3;i++) { for(j=0;j<=i;j++) System.out.print(s.charAt(j) +" "); System.out.println(); }}}}

CHAPTER-1 83 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Library Classes Chapter 2

EXERCISES

I. Fill in the blanks: 1...... is a collection of classes. 2. By default, ...... package is imported in a Java program. 3. The user can create a data type by using a ...... 4. The data type int is included in ...... wrapper class. 5. Wrapper class uses first letter in ...... case. 6. String data is converted to float type by using ...... function. 7. Conversion from primitive type to wrapper object is called as ...... 8. Each character oriented function uses a wrapper tag ...... Answer. 1. package 2. java.lang 3. class 4. Integer 5. upper 6. Float.parseFloat(String) 7. autoboxing 8. Character II. State whether the following statements are True/False: 1. Java class library includes all the packages. 2. Wrapper classes belong to java.util package. 3. Array is a non-primitive data type. 4. Class is a composite data type. 5. Integer.toString() converts integer data to String. Answer. 1. true 2. false 3. true 4. true 5. true III. Choose appropriate option for the following statements; 1. A package contains: (a) tags (b) classes (c) data (d) arrays 2. Each primitive data type belongs to a specific: (a) block (b) object (c) wrapper class (d) none 3. Automatic conversion of primitive data into an object of wrapper class is called: (a) autoboxing (b) explicit conversion (c) shifting (d) none 4. The parselnt() function is a member of: (a) integer wrapper class (b) character wrapper class (c) boolean wrapper class (d) none

CHAPTER-2 84 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

5. valueOf() function converts: (a) Primitive type to String (b) String to primitive type (c) character to String (d) none Ans. 1. classes 2. wrapper class 3. autoboxing 4. Integer wrapper class 5. String to primitive type IV. Answer the following questions: 1. What is a package? Ans. A package in Java is a collection of logically related classes. Example: The built-in functions Math.sqrt(), Math.pow() can be used directly in our programs by importing the built-in package java.lang 2. What is the significance of * while importing a package? Ans. The asterisk sign is used to import all classes of the package that is being imported. In case, a specific class needs to be imported, then the class name should be used in the import statement instead of the * sign. Example: import java.util.*; //imports all classes in the util package import java.util.Scanner; // imports only Scanner class from the util package 3. Define a wrapper class. Ans. Java language uses wrapper class that are a part of java library package java.lang. The wrapper class is a class that contains a primitive data type. Whenever an object to a wrapper class is created, a field in memory is allocated to contain a primitive data. For example, Integer is a wrapper class that contains primitive data type int and the following functions  Integer.parseInt() //to convert a String into integer data type  Integer.toString() //to convert an integer data type to a String 4. Differentiate between: [ICSE 2018] (a) isUpperCase() and toUpperCase() (b) parselnt() and toString() functions (c) primitive type and composite type data Ans. (a) isUpperCase() This function will return true if the given argument is an upper case letter, otherwise it returns false. Syntax:boolean=Character.isUpperCase( Character); Example:boolean p=Character.isUpperCase(c); //returns false toUpperCase() This function returns the given argument in upper case character. The given character remains the same if it is already in upper case. In case the character entered is not a letter, the same character is returned.

CHAPTER-2 85 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Syntax:char =Character.toUpperCase( Character); Examples:char p=Character.toUpperCase(y); //returns Y char p=Character.toUpperCase(Y); //returns Y char p=Character.toUpperCase(?); //returns ? (b) parseInt() - This is a method in the Integer wrapper class which is used to convert a String to an integer. Example: int n; String s= "34"; n=Integer.parseInt(s); //converts "34" i.e. (String ) to 34 i.e. (int)

toString() - This is a method in the Integer wrapper class which is used to convert a primitive data type like int to a String data type Example: int n=24; String s; s=Integer.toString(n); Now, s has the value "24" and mathematical operations cannot be performed on it. (c) primitive data type  Primitive data type is a fundamental data type.  Primitive data types are defined by the system developers. composite data type  It is a set of primitive data types.  Composite data types are defined by the users. 5. (i) int res = A; [ICSE 2018] What is the value of res? (ii) Name the package that contains wrapper classes. (iii) Write the prototype of a function check which takes an integer as an argument and returns a character. Ans. (i) res has the value 65 (ii) java.lang (iii) charcheck(int x) { char c= (char) x; return c; } V. Write the purpose of the following functions: 1. Float.parseFloat() Ans. This function is used to convert a String to primitive data type i.e. float. 2. Double.toString() Ans. This is a method in the Double wrapper class which is used to convert a primitive data type like double to a String data type.

CHAPTER-2 86 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

3. Integer.valueOf() Ans. This function is used to convert the different type of values into a String. 4. Character.isDigit() Ans. This method checks whether a character is a digit or not and returns true if it is a digit. 5. Character.isWhitespace() Ans. This method checks whether a given character is a whitespace. If it is a whitespace it returns true. VI. Find the output of the following program snippets: 1. char ch = *; boolean b = Character.isLetter(ch); System.out.println(b); 2. char c = A; int n = (int) c + 32; System.out.println((char)n); 3. String s= "7"; int t =lnteger.parselnt(s); t=t+1000; System.out.println(t); 4. char c = B; int i = 4; System.out.println(c+i); System.out.println((int)c+i); 5. char ch = y; char chr = Character.toUpperCase(ch); int p = (int) chr; System.out.println(chr+ "\t"+p); 6. int n = 97; char ch = Character.toupperCase((char)n); System.out.println(ch+ "Great Victory"); 7. char ch = x; int n = 5; n = n + (int)ch; char c = (char)n; System.out.println((char)((int)c-26)); 8. char ch = A; char chr = Character.toLowerCase(ch); int n = (int)chr-32; System.out.println(Char)n+ "\t"+chr);

CHAPTER-2 87 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Answer. 1. false 2. a 3. 1007 4. 70 5. Y 89 6. A Great Victory 70 7. c 8. A a VII. Unsolved Programs on Character Manipulations: 1. Write a program in Java to input a character. Find and display the next 10th character in the ASCII table. Solution: import java.util.*; public class Q1 {public static void main(String args[]) { Scanner in=new Scanner(System.in); char ch; int x; System.out.println("Enter the character"); ch=in.next().charAt(0); x=(int)ch+10; System.out.println((char)x); }} 2. Write a program in Java to input a character. Display next 5 characters. Solution: import java.util.*; public class Q2 { public static void main(String args[]) {Scanner in=new Scanner(System.in); char ch; System.out.println("Enter a character"); ch=in.next().charAt(0); for(int i=ch+1;i<=ch+5;i++) System.out.println((char)i); }} 3. Write a program in Java to generate all the alternate letters in the range of letters from A to Z. Solution: public class Q3 { public static void main(String args[])

CHAPTER-2 88 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ System.out.println("Alternate letter from A to Z:"); for(int i=65;i<=90;i+=2) System.out.println((char)i); }} 4. Write a program to input a set of 20 letters. Convert each letter into upper case. Find and display the number of vowels and number of consonants present in the set of given letters. Solution: import java.util.*; public class Q4 {public static void main(String args[]) {Scanner in=new Scanner(System.in); char ch; int c=0; //counter variable for consonants int v=0; //counter variable for vowels System.out.println("Enter the 20 characters"); for(int i=1;i<=20;i++) {ch=in.next().charAt(0); ch=Character.toUpperCase(ch); if(Character.isLetter(ch)==true) {if(ch==A||ch==E||ch==I||ch==O||ch==U) v++; else c++; }} System.out.println("Number of vowels="+v); System.out.println("Number of consonants="+c); }} 5. Write a program in Java to accept an integer number N such that 00 && N<27) CHAPTER-2 89 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.print( (char)(N+64)); else System.out.print("Invalid input"); }} 6. Write a program to input two characters from the keyboard. Find the difference (d) between their ASCII codes. Display the following messages: If d=0 : both the characters are same. If d<0 : first character is smaller. If d>0 : second character is smaller. Sample Input : D P Sample Output : d= (68-80) = -12 (First character is smaller) Solution: import java.util.*; public class Q6 { public static void main(String args[]) { Scanner in=new Scanner(System.in); char ch1,ch2; int d; System.out.println("Enter the two characters"); ch1=in.next().charAt(0); ch2=in.next().charAt(0); d=(ch1-ch2); if(d==0) System.out.println("Both the characters are the same"); else if(d>0) System.out.println("The second character is smaller"); else if(d<0) System.out.println("The first character is smaller"); }} 7. Write a program to input a set of any 10 integer numbers. Find the sum and product of the numbers. Join the sum and product to form a single number. Display the concatenated number. Solution: import java.util.*; public class Q7 {public static void main(String args[]) CHAPTER-2 90 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

{ Scanner in =new Scanner(System.in); int n,sum=0,prod=1; String s; System.out.println("Enter the ten numbers"); for(int i=1;i<=10;i++) { n=in.nextInt(); sum=sum+n; prod=prod=prod*n; } s=Integer.toString(sum)+Integer.toString(prod); //wrapper class to convert integer to string System.out.println("The number after joining the sum and product is "+s); } } 8. Write a menu driven program to generate the upper case letters from Z to A and lower case letters from a to z as per the users choice. Enter 1 to display upper case letters from Z to A and Enter 2 to display lower case letters from a to z. Solution: import java.util.*; public class Q8 {public static void main(String args[]) {Scanner in=new Scanner(System.in); int x; System.out.println("Enter 1 to display upper case letters from Z to A "); System.out.println("Enter 2 to display lower case letters from a to z"); x=in.nextInt(); switch(x) {case 1: for(int i=90;i>=65;i--) System.out.println((char)i); break; case 2: for(int j=97;j<=122;j++) System.out.println((char)j); break; default: System.out.println("INVALID ENTRY"); }}} 9. Write a program to input a letter. Find its ASCII code. Reverse the ASCII code and display the equivalent character. Sample Input: Y CHAPTER-2 91 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Sample Output: ASCII Code = 89 Reverse the code = 98 Equivalent character: b

Solution: import java.util.*; public class Q9 { public static void main(String args[]) { Scanner in=new Scanner(System.in); char ch; int n,num=0,d; System.out.println("Enter the character"); ch=in.next().charAt(0); n=(int)ch; do { d=n%10; num=num*10+d; n=n/10; } while(n>0); System.out.println("ASCII code="+(int)ch); System.out.println("Reversed code="+num); System.out.println("Equivalent character="+(char)num); }} 10. Write a menu driven program to display (i) first five upper case letters (ii) last five lower case letters as per the users choice. Enter 1 to display upper case letters and enter 2 to display lower case letters. Solution: import java.util.*; public class Q10 { public static void main(String args[]) { Scanner in=new Scanner(System.in); int x; System.out.println("Enter 1 to display the first five upper case letters"); System.out.println("Enter 2 to display the last five lower case letters"); x=in.nextInt();

CHAPTER-2 92 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

switch(x) {case 1: for(int i=65;i<70;i++) System.out.print((char)i+" "); break; case 2: for(int i=117;i<122;i++) System.out.print((char)i+" "); break; default:System.out.println("Invalid entry"); }}} 11. Write a program in Java to display the following patterns: (i) A (ii) ZYXWU ab ZYXW ABC ZYX abcd ZY ABCDE Z

(iii) ABCDE (iv) PRTV ABC PRT A PR P

(v) A*B*C*D*E* (vi) aaaaa A*B*C*D* bbbbb A*B*C* A AAAA A*B* B BBBB A* Solution: public class Q11{ public static void main(String args[]) { String s="abcde"; System.out.println("\n\n");

for(int i=0;i<=4;i++) {for(int j=0;j<=i;j++) { if(i%2==0) System.out.print(Character.toUpperCase(s.charAt(j)));

CHAPTER-2 93 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

else System.out.print(Character.toLowerCase(s.charAt(j))); } System.out.println(); }

s="ZYXWU"; System.out.println("\n\n");

for(int i=s.length()-1;i>=0;i--) {for(int j=0;j<=i;j++) System.out.print(s.charAt(j)+" ");

System.out.println(); }

s="ABCDE"; System.out.println("\n\n");

for(int i=s.length()-1;i>=0;i=i-2) {for(int j=0;j<=i;j++) System.out.print(s.charAt(j)+" ");

System.out.println(); }

s="PRTV"; System.out.println("\n\n");

for(int i=s.length()-1;i>=0;i--) {for(int j=0;j<=i;j++) System.out.print(s.charAt(j)+" ");

System.out.println(); }

s="A*B*C*D*E*";

CHAPTER-2 94 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

System.out.println("\n\n"); for(int i=s.length()-1;i>=0;i=i-2) {for(int j=0;j<=i;j++) System.out.print(s.charAt(j)+" ");

System.out.println(); }

char a=97; char b=98; System.out.println("\n\n");

for(int i=1;i<=4;i++) { for(int j=1;j<=5;j++) { if(i%2==1) System.out.print(a); else System.out.print(b); }

if(i>=2) { a=Character.toUpperCase(a); b=Character.toUpperCase(b); } System.out.println(); } }}

CHAPTER-2 95 Arundeep’s Computer Applications-10 https://www.arundeepselfhelp.info

Pages 96 to 223 are missing

Click on the link to buy Complete Book

https://www.arundeepselfhelp.info/index.php?route=produc t/product&path=113_159&product_id=377