Showing posts with label Theory. Show all posts
Showing posts with label Theory. Show all posts

Tuesday, March 1, 2011

Function calling techniques-Call be reference and call by value in BlueJ

Function calling in Java can be done using two techniques, call be reference and call by value. We know that whenever we define any function in our program, to execute the codes inside the function body the function must be called. This is also known as invoking the function. In many functions we define argument. The argument may be single or muttiple. We can even define functions without any argument. Such functions are known as zero argument function or function without argument. Call by value and call by reference has nothing to do with such functions.

The values which are passed to a function are known as actual argument and the variables or objects which are declared inside the parenthesis of the defined function are known as formal argument.

For example, suppose we have two variables ‘int a’ and ‘int b’ with 3 and 5 as values. We are calling a function using a statement like ‘object_name.function_name(a,b);’. Here ‘a’ and ‘b’ are called actual argument. Again suppose the function ‘function_name()’ is defined like:

void function_name(int x, int y)
{
Statements
}

Here’int x’ and ‘int y’ are called formal arguments.

Calling a function using call by value technique

Whenever we use primitive variables as actual argument, the function calling technique is known as call by value. As the actual argument or arguments are primitive variable, the formal arguments should also be primitives. In such calling technique of function, the values of the actual arguments or parameters are not affected in the function body as function creates new set of variables which are declared as formal arguments to copy the values of actual arguments and any modification done within the function body will affect formal argument variables only, not the actual arguments.

Program to demonstrate call by value



import java.io.*;
class CallByValue
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
public void take() throws Exception
{
System.out.println("Enter 1st Value:");
a=Integer.parseInt(br.readLine());
System.out.println("Enter 2nd Value:");
b=Integer.parseInt(br.readLine());
System.out.println("Values before calling function:"+ a + ","+b);
change(a,b);
System.out.println("Values after calling function:"+ a + ","+b);
}
void change(int x, int y)
{
int t;
t=x;
x=y;
y=t;
System.out.println("Values within function body:"+ x + ","+y);
}
public static void main(String args[])throws Exception
{
CallByValue ob=new CallByValue ();
ob.take();
}
}


The above program is an example of call by value. The actual arguments in this program are ‘int a’ and ‘int b’. The values are displayed within the function ‘public void take()’ twice, one before calling the ‘void change()’ function and another display is after calling the function. Both the display will show same values as the exchange of values are done on the variables of the function ‘void change()’. The name of the formal arguments of the function can be same as that of actual arguments.

Calling a function using call by refence technique



Whenever we use objects of any class or array as actual argument, the function calling technique is known as call by reference. We know that simple declaration of object does not create object and in java, declared objects can refer created objects of same class or sub class. A reference object deals with the actual members of the passed argument and in such case any modification done inside the function body will have an impact on the actual object.

Program to demonstrate call by value



import java.io.*;
class CallByRef
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
public void take() throws Exception
{
System.out.println("Enter 1st Value:");
a=Integer.parseInt(br.readLine());
System.out.println("Enter 2nd Value:");
b=Integer.parseInt(br.readLine());

}
void change(CallByRef ob)
{
ob.a=100;
ob.b=200;
}
public void display()
{
System.out.println("Values :"+ a + ","+b);
}
public static void main(String args[])throws Exception
{
CallByRef ob1=new CallByRef();
CallByRef ob2=new CallByRef();
ob1.take();
ob2.take();
System.out.println("Values of the second object before calling 'change()' function :");
ob2.display();
ob1.change(ob2);
System.out.println("Values of the second object after calling 'change()' function :");
ob2.display();
}
}

Here in this program ‘CallByRef ob’ declared as formal argument in ‘void change()’ function refers the object ‘ob2’ of CallByRef class. Using the reference object ‘ob’ we have changed the data member values which affects the values of the acual argument ‘ob2’.

Tuesday, February 8, 2011

Abstract class and abstract function in BlueJ

In a simple class in BlueJ, the data members of the class are declared and function members are defined. The members can have any access specifiers, public, private, protected or default. Function definition means where function return type, name, argument list (if no argument, it is kept blank)and function body is defined. Function body of a function should have an opening and closing curly brace.

Example of function definition:



public void setData( int x, int y)
{
Statement 1;
Statement 2;
……………..

}

If in any class a function is not defined as shown above, its prototype is simply declared then the keyword abstract should be used with the function otherwise compiler will show error.
.

Example of abstract function



abstract void set();

This above function has no body, it is not defined. Thus we can say that this function is incomplete. In java, incomplete function means abstract function. If a single function of a class is abstract then the class also becomes abstract class. An abstract class can have more than one abstract function. For abstract class, the keyword abstract should be used before the class name while defining the class otherwise compiler will show compile time error.

Example of abstract class definition



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

Abstract class can have instance members as well as static members. Abstract can define it’s own constructor also but the only difference with abstract class is that objects of abstract class can not be created. We have defined an abstract class ‘MyClass’ just above. If we try to create object of this class using the statement MyClass obj=new MyClass(), it will show compile time error. Abstract class can be inherited by other class but the sub class would either override the abstract functions of the abstract super class or declare itself abstract class.

Example of abstract class inheritance



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

class MyClass2 extends MyClass
{

void show()
{
System.out.println(“Value=”+a);
}
}

Here the sub class MyClass2 inherites the abstract class MyClass and the abstract function is overridden in the sub class. If the sub class MyClass2 do not override the abstract function then the codes would be like

abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

abstract class MyClass2 extends MyClass
{

void showValue()
{
System.out.println(“Value=”+a);
}
}

Here in the above codes both the classes are abstract so objects of both the classes can not created. One point to be remembered that abstract class objects can be declared and it can refer its sub class object.

Wednesday, January 19, 2011

Understanding the use of inner loop in BlueJ programs


Nested loop means there should be an outer loop and one or more inner loop. We have seen the use of inner loop in different type of programs. Whenever we use any nested loop, inner loop plays the most vital part. In sorting programs inner loop does the sorting job. In pattern printing programs, it is the inner loop which displays the pattern. So for any type of the above jobs, students should understand the inner loop properly.

Use of inner loop in nested loop

For any type of pattern, the inner loop is the main architech to display the design or pattern. Job of outer loop is simply to maintain the rows but the major job is performed by inner loop. Take any program on printing pattern, you would find that the construction of inner loop, the logical statements used in the inner loop are the main points to stydy and understand. Any change in the statements of inner loop will change the shape of the pattern.

Here is a program to print a pattern like

55555
55554
55543
55432
54321

Simply observe the checking done in inner loop

class Pat
{
int i,n,j;
 public void show()
 {
 for(i=0;i< 5;i++)
 {
  n=5;
  for(j=0;j< 5;j++)
  {
  if(i+j >=5)
  n--;
   System.out.print(n);
   }
   System.out.println();
  }
  }
public static void main(String args[])throws Exception
{
 Pat obj=new Pat();
 obj.show();
}
}

Use of inner loop in sorting programs

In any type of sorting programs, inner loop performs the major job.  In slection sort programs, the checking job is performed by inner loop and the necessary exchange of values is also performed within inner loop.
In Bubble sort , the accessing the values, cheking the values and exchanging the values on requirements are done by inner loop only. The outer loop determines the maximum number of passes required.

Other uses of inner loop

Inner loop has many other countless uses. One of the very common use of inner loopis to store unique values in an array. Inner loop is used in such program to search a particular values from the list. Although normal searching program do not need inner loop but to [ HREF]store unique values in an array, inner loop is used to search if the value is already in the array.

Tuesday, January 4, 2011

Understanding do while loop in BlueJ

It is observed that students mostly use for loop or while loop whenever loop execution is necessary in a program. If they are asked about their favorite loop, I am sure most of them will go with for loop and then major part of the rest will favors while loop.

We know that any type of loop can perform any type of job. There is no difference in using any type of loop in any program. Still do while loop has got some unique features which make it different from the other two types of loop. Firstly, do while loop is an exit control loop which indicates that the conditional statement will be executed at the end of loop body. This feature helps us to start the loop execution without initializing the loop control variable before the first execution of the loop. In such case when the do while loop executes for the first time, the loop control variable gets initialization and afterwards during iterations, it gets reinitialized.

Syntax of do while loop



Do while loop starts with the keyword ‘do’ and ends with the keyword ‘while’. Like other loops, we have to put curly braces in between ‘do’ and ‘while’ to define the body of loop if the loop body contains more than one statement. One important point to be kept in mind that ‘while’ is the control statement of do while loop and after this statement a semicolon is a must.

do
{
Body statement(s)
Re initialization
} while (condition);

Program using do while loop

This program is as stated below:
Take ‘n’ numbers from the user and display the total even numbers entered by the user.

import java.io.*;
class Test
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show()throws Exception
{
String ans;
int i,c=0;
do
{
System.out.println("Enter a number:");
i=Integer.parseInt(br.readLine());
if(i%2==0)
c++;
System.out.println("Any More (Yes/No):");
ans=br.readLine();
} while(!ans.equalsIgnoreCase("NO"));
System.out.println("Total even numbers entered="+c);
}
public static void main(String args[])throws Exception
{
new Test().show();
}
}

Here the loop control variable is a String class object ‘ans’. Note that ‘ans’ is not initialized before the start of the do while loop. The loop executes for the first time without any checking and performed the job assigned within its body. At the end of the loop body user’s choice is taken and assigned on ‘ans’ and this is initialization of loop control variable. From the second iteration of the loop, ‘ans’ is reinitialized.

The basic difference between entry control loops and do while loop

In entry control loops, loop control variables are initialized before the looping cycle starts whereas in do while loop we can leave the initialization process for the body statements of the loop. Sometimes in do while loop initialization of loop control variable is needed above the loop body. One such example of do while loop is given below.

In this program, user will enter two numbers and the result of first number divided by the second number will be displayed. This process will continue for ‘n’ times.

import java.io.*;
class Test
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show()throws Exception
{
String ans;
int a,b,r,c=0;
do
{
System.out.println("Enter 1st number:");
a=Integer.parseInt(br.readLine());
System.out.println("Enter 2nd number:");
b=Integer.parseInt(br.readLine());
if(b==0)
continue;
r=a/b;
System.out.println("Result:"+r);
System.out.println("Any More (Yes/No):");
ans=br.readLine();
}
while(!ans.equalsIgnoreCase("NO"));

}
public static void main(String args[])throws Exception
{
new Test().show();
}
}

On compilation error will be shown ‘variable ans might not have been initialized’.

Why this happens?

‘continue’ statement is used in the do while loop of this program and it is required. If the entered second number becomes zero then a run time error would be flagged. To overcome such situation, continue is used. When this continue statement in do while loop is encountered, it sends the control to the control statement. For this reason, the loop control variable needs initialization above the loop body although it’s a do while loop.

Necessary change needed is to initialize the loop control variable where it is declared. Within show () function modify the statement ‘String ans’ with String ans=”y”

Thursday, December 30, 2010

Use of static keyword in bluej programs

Among several keywords in java, static is a keyword mainly used in functions and variables. Any variable declared in as a data member are normally instance variable. The meaning of instance variable means those variables whose existence depends on the creation of an object. After any object is created, instance variables come into existence. Another feature of instance variable is that for each and every object, separate copies of instance variable are created.

So far as functions are concerned, they are also known as instance function so far as static keyword is not used. Normally for any number of objects, only single copy of functions of that particular class is created. Existence of instance functions also depends upon the creation of the object. I think students have observed the feature that whenever the function readLine() of BufferedReader class is called, it is called after creating the object of BufferedReader class as readline() is an instance function.

Use of static in variable



Whenever we declare any variable as static, it becomes the class member and its existence does not depend upon the creation of object of that class. In a word static variable can be used before creating the object and it is accessed using the class name. Number of objects may be created of that class but unlike instance variable, only one instance of static variable will be created. All the objects of that class will deal with the same copy.

class Stat
{
int a;
static int b;
void set(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Values are="+a+","+b);
}
public static void main(String args[])
{
Stat ob1,ob2;
ob1=new Stat();
ob2=new Stat();
ob1.set(2,4);
ob2.set(10,20);
System.out.println("First object");
ob1.display();
System.out.println("Second Object");
ob2.display();
}
}

Here in the above program ‘int a’ is instance variable while ‘int b’ is the static one. Although in this program the static variable is accessed after creating objects but it can be accessed before creating objects. The point to be noted here is that for both the objects, the static member is common. While assigning value through set() function, for the first object the value is 4 and for the second object it is 20. As the static member is common for both the objects, last assigned value 20 will be the ultimate value of the static variable ‘int b’. Displaying the values through display() function, we will find that for both the objects, the static variable ‘int b’ is 20 while ‘int a’ will contain different values for the objects.

What is static method or function ?



Static method or static function means whose existence comes before creating any object of that class and can be accessed using the class name.

class Stat
{
int a;
static int b;
static void setStatic(int y)
{
b=y;
/* instance variable can not be accessed here */
}
void set(int x)
{
a=x;
/* static variable can be accessed here */
}
void display()
{
System.out.println("Values are="+a+","+b);
}
public static void main(String args[])
{
Stat ob1,ob2;
ob1=new Stat();
ob2=new Stat();
Stat.setStatic(100);
ob1.set(2);
ob2.set(10);
System.out.println("First object");
ob1.display();
System.out.println("Second Object");
ob2.display();
}
}

In this above program, just see how the function ‘setStatic()’ is called. It can be called using the object reference also. Keep the following points in mind for static method
1. Non static members can not be accessed within static function body while non static or instance functions can access static members.
2. ‘this’ keyword can not be used within static function body.

Monday, December 20, 2010

Basic Logics Behind Pattern Printing In BlueJ - Chapter II

Lets take another simple pattern like:

A
AA
AAA
AAAA

As I have discssed in my previous post that firstly we have to count the number of rows. Here the row numbers are 4, so the outer loop will execute four times. The number of columns in all the rows are not same but there is a sequence in which they are increased. In each iteration the number of columns increases by 1. The outer loop will execute for 4 times and there is no doubt about it. But the problem is with the inner loop.

We will set such a variable in the conditional statement of the inner loop that increases by 1 after each full course iteration of the inner loop. It is the outer loop control variable which increases by 1 after each of it's iteration. So, the problem is solved. Place the outer loop control variable in the conditional statement of the inner loop.

Using for loop the program on pattern printingwill be like:

class PatternDisplay
{
int i,j;
public void show()
{
for(i=0;i< 4; i++)
{
for( j=0; j< =i;j++)
{
System.out.print("A");
}
System.out.println();
}
}
public static void main(String args[])
{
PatternDisplay ob=new PatternDisplay();
ob.show();
}
}


Again the same program on printing pattern can be done using nested do while loop.

class PatternDisplay
{
int i,j;
public void show()
{
i=0;
do
{
j=0;
do
{
System.out.print("A");
j++;
}while(j<=i);
System.out.println();
i++;
} while(i<4);
}
public static void main(String args[])
{
PatternDisplay ob=new PatternDisplay();
ob.show();
}
}

Here in this above program using do while loop, the outer loop prints the rows and the inner loop prints the pattern.
Loop control variable of the outer do while loop is 'i' while that of the inner do while loop is 'j'.

Related Post: BlueJ Programs On Pattern

Wednesday, December 15, 2010

Basic Logics Behind Pattern Printing In BlueJ - Chapter I

It is observed that many students face problems regarding the logics behind pattern printing. I think everybody knows that to print pattern nested loops are required. So before we proceed for printing pattern, out first job will be to understand nested loop properly.

We know that combination of control statement and body of a loop is a single statement. Again loop body contains statement (s). So we can put loop(s) inside the body of another loop. This is nested loop.

The loop kept inside the body of another loop is called inner loop and the other is known as outer loop. It is the inner loop which does the printing job of any pattern and in which row the inner loop will work is determined by outer loop. In every pattern there are rows and columns. I think it is now clear which loop controls what. Inner loop controls the columns where the values are displayed.

The concept would more clear if we take the case of Excel sheet. In a sheet there are number of rows starting from 1,2,3…, but in every row the columns are fixed like ‘A’, ‘B’,…. And values are always written on columns. From the above, it can be said that rows changes but columns remains the same in every row.

In case of pattern, it is also a combination of rows and columns. Rows are changing where the columns are repeated. Let’s take an example to illustrate it better. A simple pattern is given below:

@@@@
@@@@
@@@@
@@@@

In the above patterns there are four rows and four columns in each row. The rows are controlled by outer loop, hence it should runs four times. As the prints are on columns and columns are controlled by inner loop, we can say that on each iteration of the outer loop, inner loop must run times. The loop will be like

for( int i=0; i< 4; i++)
 {
 for( int j=0; j< 4; j++)
{
    System.out.print(“@”);
}
System.out.println();
}


The statement given below is the inner loop:
for( int j=0; j< 4; j++)
{
    System.out.print(“@”);
}

When the outer loop ‘for( int i=0; i< 4; i++)’ runs for the first time, the inner loop catches the control and executes for four times printing the symbols in the fixed row ( determined by ‘i’) but in different columns. After the inner loop has executed for four times, the control goes out of its body and new line is feed. A full course iteration of the inner loop means one iteration of the outer loop. As the outer loop starts its second iteration again the inner loop catches the control and executes for another full course, means four times as defined. Ultimately the inner loop runs for total 16 times and the symbol is printed for 16 times. There are four rows in the pattern and the outer loop has executed for four times only feeding four rows.
The final coding for this program is

class Pat1
{
public void  showPattern()
{
for( int i=0; i< 4; i++)
 {
 for( int j=0; j< 4; j++)
{
    System.out.print(“@”);
}
System.out.println();
}
}
}


Please put your comments here so that I can understand whether we are moving in the right direction. Lots of patterns are to be discussed.

Related Post: BlueJ Programs On Pattern

Monday, December 13, 2010

Difference between constructor and function in BlueJ

Constructor is called a special function due to many reasons. The points which make them different are listed below.

(i) Class name and it’s constructor name must be same where as class name and function name must be different.

(ii) Constructor has no return type not even void, function should have a return type. If the function does not return any value, it should be void.

(iii) Constructor can’t use any return statement within it’s body. Return type function have to use return statement. The return statement of a return type function should be followed by a value or expression which results in a value which matches the return type of the function. Void type function can also use return statement but it should not be followed by any value. Such return statements are used in void type function to send the control back to the caller of the function before the execution of the function is completed.

(iv) Constructor execution is a must whereas all the functions defined in a class may not execute.

(v) If a constructor is not defined in a class, compiler supplies the default constructor – means constructor with zero / no argument and empty body. This is not the case with functions. Normally constructor initializes the data members of an object. In broader sense constructors are used to perform the loading stage jobs in a program.

Point number (v) needs some clarification specially for ISC students. Normal ICSE / ISC BlueJ programs can be done without defining any constructor. Then what is the need of defining constructor? Again if we define constructor in a class, why the entire job of the program is not performed within the constructor?

‘what is the need of defining constructor?’. As stated constructors are used to perform the loading stage jobs in a program apart from initializing the data members. Loading stage jobs means the jobs which are to be done at the start of the program and which is must. These type of job is not within the scope of ICSE or ISC students.


Lets discuss this matter using some BlueJ programs.

This is a simple BlueJ program of displaying the sum of two numbers.

Program number 1

This program uses two functions, the first function is public void set(int x,int y) which takes two values and sets them on the object members. The other function public void display() displays the sum of the values.

class Ab
{
int a,b;
public void set(int x,int y)
{
a=x;
b=y;
}
public void display()
{
System.out.println("Sum="+(a+b));
}
public static void main(String args[])
{
Ab ob=new Ab();
ob.set(2,3);
ob.display();
}
}

Program number 2 is little bit modified. In this program constructor is defined with argument to initialize the object members and the public void set() function is omitted as the job of this function is performed by the constructor.

class Ab
{
int a,b;
public Ab(int x,int y)
{
a=x;
b=y;
}
public void display()
{
System.out.println("Sum="+(a+b));
}
public static void main(String args[])
{
Ab ob=new Ab(2,3);
ob.display();
}
}


Program number 3 is the worst among the three programs. Here the entire job is done within the constructor body means whenever object is created it will display the result also.

class Ab
{
int a,b;
public Ab(int x,int y)
{
a=x;
b=y;
System.out.println("Sum="+(a+b));
}
public static void main(String args[])
{
Ab ob=new Ab(2,3);
}
}

This program is the best one with distinct job for different functions. Here in this program overloaded versions of constructor are used. One constructor creates the object and at the same time initialize the object members and the other just creates the object. The need of constructor overloading is related with inheritance which will be discussed in the next posting.

class Ab
{
int a,b;
public void set(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Sum="+(a+b));
}
public Ab(int x,int y)
{
a=x;
b=y;
}
public Ab()
{
}
public static void main(String args[])
{
Ab ob=new Ab(2,3);
ob.display();
Ab ob1=new Ab();
ob1.set(10,20);
ob1.display();
}
}

Monday, December 6, 2010

Binary search tree – it’s traversal and construction for ISC students


Tree is a non linear data structure of representation of nodes. A binary tree can be defined as a finite set of elements that is either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other subsets are themselves binary trees , called the left and right subtree of the original tree. So while adding elements into a tree , we can add them category wise in left and right subtree.

Traversing binary trees

Once you have created a binary tree , you can display it’s contents in several ways. The process of moving through a tree is known as tree traversal. The traversal of a binary tree involves visiting each node in the tree exactly once.There are three popular methods of binary tree traversal – inorder , preorder and postorder traversal . Traversing a binary tree means visiting the root node , it’s left and right subtrees. The only difference among the methods is the order in which these three operations are performed.

To traverse a binary tree in inorder , we perform the following operations :-

1.Traverse the left subtree inorder
2.Visit the root.
3.Traverse the right subtree inorder.

To traverse a tree in preorder

1.Visit the root.
2.Traverse the left subtree in preorder
3.Traverse the right subtree in preorder

To traverse a tree in postorder

1.Traverse the left subtree in postorder
2.Traverse the right subtree in postorder
3.Visit the root.

Steps for constructing a binary tree having preorder sequence as A,B,C,D,E and inorder sequence B,A,D,C,E

In such case always read the root from preorder and sub trees from inorder. In preorder traversal, root of the tree is visited first, so ‘A’ is the root. Again in inorder traversal, top most root is visited after visiting the left sub tree. We can easily mark the left sub tree and right sub tree of the tree. In the above case from preorder sequence we find that ‘A’ is the root and from the inorder sequence it is clear that left sub tree has only one node ‘B’ and right sub tree has the nodes ‘D’, ‘C’, ‘E’.

In preorder traversal of tree, after visiting the root, left subtree is visited. Here ‘B’. In inorder sequence only ‘B’ is there at the left of root ‘A’.
Again in preorder, next node visited is ‘C’, and in the inorder sequence, position of ‘C’ is between ‘D’ and ‘E’.

In this style we have to find out the root from preorder sequence and left and right sub trees from inorder sequences.

Tuesday, September 28, 2010

Few fundamental question answers in ICSE BlueJ

Define an object

Object is the instance of a class. Class is the template and object is the real entity which can be used to perform specific type of jobs as defined in the class. An object consists of data members and function / method members. Data member hold values and function members of the object acts on the data members.
Data members may be of primitive type variables or objects of other predefined classes.

What is a method?


Method or function means statement or statements kept within a block. In java block is defined by curly braces [{…}]. A name is assigned to the block which is known as function name. The name must start with any alphabet and by convention, function name starts with lower case character. A function should have a return type which indicates what type of values the function should return to the calling program while invoked. If a function does not return any value, its return type should be ‘void’. The return type may be any primitive type or user defined type, i.e. class. The function name is followed by parenthesis which is known as argument or parameter zone which is utilized to pass values to the function from outside. If a function is defined in such a way that it does not take any value or argument from outside, a blank parenthesis is a must. Function body is executed while invoked. Functions of an object actually define the behaviour of an object.

Can there be objects without having any methods?


We can define a class without methods also. In such case the data members should be either declared with public specifier or default specifier as they are to be accessed from outside the class.
e.g.

class BlueJ
{
int height,width,length;
}

Why are methods so important for the description of objects?


As per encapsulation, methods or functions hide the data members from unauthorized access and it is the methods which manipulates the data members of an object. Normally an object contains number of methods which acts on its data members. Each function is normally assigned different jobs. This concept reduces the complexity of a program and the same time reduces the space complexity of a program.

Simply think about your mobile set. It has number of functions and without knowing the complex working of the functions we simply invoke functions get the desired result.

What is a class?


Class can be defined as user defined new data type. Every programming language has number of predefined types which are known as primitive data types. Data types define the nature and behavious of its instance. For example, a declaration ‘int a;’ denotes that ‘a’ is the instance of the predefined type ‘int’ and ‘int’ defines that ‘a’ can hold whole number of a specific range and different operators like ‘+’,’-‘ etc can act on this variable.
Similarly by defining a class we can create a new type with specific nature and behaviour. After defining the class we can create instance of a class which is known as object.

What is an abstraction?

In program language, abstraction means managing complexity without going in details of any working. In real life also we perform lot of work through abstraction. For example a driver drives the car through abstraction. Using the brake, he can stop the car. The complex gearing arrangement behind this operation is unknown to him.
Similarly in programming language, we can work with a predefined object without knowing the details of its methods and data members. We should know how the methods of the object can be invoked and what would be the result. This is called abstraction.

Can there be multiple abstractions of a real world entity

In real life there is lot of examples on abstraction. During fever we take medicine without knowing how this medicine will work. We operate our television set using the remote without knowing how a simple press on remote button changes the channel.

How are classes and abstraction linked?

In every class, number of methods is defined. These methods use number of data members and act on these data members. While using any object of a predefined class, we simply invoke methods of the object to get our work done without knowing the detail operation of the method. This is abstraction. For example while calling ‘print()’ or ‘println()’ method we know that it will display the argument as a string but the codes executed by these methods to perform the job is not known to us.

What is an object factory?

Class is known as object factory, as after defining any class we can create number of instances of that class. These instances are known as objects. Objects are created following the nature and behaviour defined by the class.

Thursday, August 12, 2010

Sample paper on BlueJ

In this sample paper on BlueJ, some questions and answers are given. The continuation of this sample paper will be the next post.

Question :  Write any  two rules for naming variable.

Answer : Variable names must start with alphabet and keywords can not be used in variable names. These are two rules for naming variable.
     

Question :  Write any two differences in Implicit Type Casting and  Explicit Type Casting.

Answer :In implicit type casting, variables of different types are converted into one type if they are used in any expression where as in explicit casting, variables of one type are to be converted to other type using coding.

Question : Write a main difference between while loop and do while loop in BlueJ.

Answer :While loop is an entry controlled loop where do while is an exit control loop. This is the  main difference between while and do-while loop.  

 Question : Give an example of conditional operator.     
If (a >b)
{
 max=a;
}
else
{
 max=b;
}

This above statement can be written as
max=(a>b)?a:b;


 Read the following program and answer the given questions :
class demo{
 public void main( ) {
 int a,b,i,j;
 for(i=1;i< 5;i=i+1)
 {
  for(j=1;j< =I;j=j+1)
  {
   System.out.print(“ “+j);
  }
 System.out.println( );
            }}}
 ( i )  How many times the first loop of i will perform?  Ans: 4 times     (ii)   How many times the first print statement work ? Ans: 10 times  
(iii)  What will be the output of program ?

Output would be like:
1
1 2
1 2 3
1 2 3 4     


Write the output of following statements :       class output
                  {
   public void fmn( )
                            {   
int a=12,b=10;
         System.out.println (“a++=”+a++);
         System.out.println (“a>b=”+a>b);
         System.out.println (“++a=”+++a);
         System.out.println (“--a=”+--a);
         System.out.println (“a!=(a+b)=”+a!=(a+b));
                              }
                          }
Ans: a++=12
       a>b=true
       ++a=14
       --a=13
       a!=(a+b)=true


      Find the errors if any in the following program :        
class 12design
{
  public void mn ()
                      {
   byte 1a=10;
   int b=20;
   int c=a>b?a,b;
   System.out.println(‘The value of c is :’+c);
  } 
                 }

Ans: Class name should start with alphabet, so class name 12design will generate compile time error.
byte 1a; variable name must start with alphabet.
int c=a>b?a,b;  this should be int c=a>b?a:b;
The value of c is: should be kept within “ “.

Explain the bubble sort technique in array with an example.
       
Bubble sort technique compares consecutive values and if necessary exchange the values between them. In every pass it starts from the first location (starting index of the array) . This technique arranges the values from the last location, so on every pass it reduces the checking from right end. The main advantage of this sorting process is that if no exchange is found in any pass, the process is terminated.

Suppose the values in an array of size 5 are as follows:
4 2 3 66 5 and we want to arrange them ascending orer.
In the first pass
array[0]>array[1]  exchange. Now the array is 2 4 3 66 5
array[1]>array[2] No exchange
array[2]>array[3] No exchange
array[3]>array[4] exchange. Now the array is 2 4 3 5 66
This is the end of first pass and the highest value is set in the last location. In the second pass array[3] and array[4]  will not be compared.

In the start of second pass the array is 2 4 3 5 66
array[0]>array[1] No exchange
array[1]>array[2] exchange. Now the array is 2 3 4 5 66
array[2]>array[3] No exchange
End of second pass and the array is now 2 3 4 5 66

Third pass
array[0]>array[1] No exchange
array[1]>array[2] No exchange
End of third pass and as there is no exchange, the process is terminated.

Thursday, August 5, 2010

User defined function in BlueJ programs - Part I

What is function



Function means a block where number of statement(s) are kept. These statement(s) are to be executed when required. In structured programming, a program is divided into different modules. Another reason of using functions in a program is to reduce the size of the program. In programs there may be situations when same set of statements will be required to be executed in different parts of the same program. In such case create, a function with the statements. In BlueJ and other Object oriented programming languages, user defined function is a must.

In Icse and Isc computer applications question papers, you will find BlueJ programs to write with using specific user defined functions as written in question paper. You have to do the program with the guide line provided. So a clear concept on user defined function is very much needed for students.

Components of a function



1.Function name (user defined)—Function should have a name.

2.Return type of the function (should be placed before the function name)– function which returns value must have a return type equivalent to the type of value returned (e.g. int, float etc). If a function does not return any value then it’s return type should be void.

3.parentheses [()] follow the function name. Functions can take values or arguments when invoked .If a function takes any argument then it must be declared inside the parentheses.

Two steps required for function



1. Function definition – next comes the function definition. The function definition of the above declared functions would look like: -
void add ()
{
From this point the function body starts
The statement(s), which form the unit
Should be placed within this body
} Function body ends here.

Note that there is no semicolon after void add (). In case of function definition there should be no semicolon. A function definition must have a function body and inside the body the function statements should be placed. In BlueJ programs, sometimes we have to define a function with empty body, means no statement inside the function body. In such case also we have to define the block of function body. On calling the function the statements will be executed. void main () is an example of function definition.

2.Calling the function – To execute the statements of a function body, the function is to be called. At the time of calling a function no return type should be used. Suppose we want to call the previously defined function then the syntax should be: - add ();

In BlueJ programs, we normally define function and call function. Declaring a function in BlueJ means something different. In such case, the class would be abstract class. In inheritance we will discuss it abstract class in details. Where as in C Language and C++ programs we can declare functions in normal situation.

Sunday, August 1, 2010

For the beginners in BlueJ

I got one comment on this site from one visitor that he wants to learn BlueJ and his query is - from where to start and how to start. For those who don’t have any previous knowledge of language and want to learn BlueJ through this site from the beginning are advised to go through my other site on C Language. C Language is the mother language of any modern programming language. Java is object oriented programming, so before starting java one should have knowledge on variables, array, structure and user defined function very clearly. In C Language we have the scope to learn the necessity of array and ultimately necessity of structure. Actually structure is the platform of object oriented program. Then comes function, user defined functions. In BlueJ we have to define our own functions in each and every program. So without a clear cut conception on user defined function, one cann’t apply it in BlueJ perfectly.

So, my advice to the beginners, please go through C Language first, Find out the advantages of structure in C language. Then find out the limitations of structure, for these limitations object oriented programming languages are developed.

Try to have a clear idea about user defined function. In BlueJ you have to juggle with functions.

Happy Journey through C.

Sunday, May 30, 2010

ICSE Board Guess Question And Answer on BlueJ(3)

Today's topic icse computer applications sample papers.

What is a class?
Class means user defined new type. class is the template or blue print which defines the nature and behavior of it’s instance – object. In class definition we normally the fields of it’s instance are declared and the methods are defined.

What is a constructor
Constructor is a special type of function which is needed to create an object. Without the execution of a constructor, object can’t be created. Constructor is a special method for several reasons
(i) Class name and it’s constructor name must be same
(ii) Constructor has no return type not even void
(iii) Constructor can’t use any return statement.
(iv) Constructor execution is a must
Normally constructor initializes the data members of an object.

Why do we use functions?
Function or methods are mini programs which perform a specific job. By using function we can reduce the complexity of a program. Without knowing the details we can invoke function to perform any specific job. This is an example of abstraction.

What will be the output

Class name
{
int a=15,b=35,c;
public void prac()
{
c=a+b;
System.out.println(c);
}
}

Output will be 50
What will be the output
Class out
{
public void oe( )
{
int a=26;
String s=”rajat”
Int ac=s+a;
}
}

Output rajat26

Consider the following class

Class all
{
public static int a=5;
public float=7.5
}

i) how many class variables are present
ii) how many instance variables are present

One class variable public static int a=5; and one instance variable public float=7.5is present in the class

Explain call by reference and call by value

Values are passed from program to functions. Values can be passed in two ways. It may be either call by value or call by reference.
Call by value means when variables are passed as arguments from the program and function creates variables, called function variables to store the values. As the variables are passed as arguments in case of call by value, the function body is getting the reference of the value or values that are passed as argument. So any modification done on the values in the function will have no impact on the actual value.

When objects are passed from calling program to a function as function arguments, it is called call by reference. In such case the variables of the function which will hold the passed values must be pointer variables. Here any modifications performed on the values within the function will have the same effect in the actual value of the calling program


This page is on icse sample papers. If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.

Similar post can be found in Indiastudychannel

Tuesday, May 18, 2010

ICSE Board guess question, answer and sample programs on BlueJ (2)


Today we'll deal with icse computer applications sample papers.

Write any two rules for naming varible declaration.
Two rules of variable declaration are
(i) Variable name must start with an alphabet
(ii) Java keywords can't be used as variable name

Write down the difference between prefix and postfix operators.

Prefix and postfix operators while used in single statement has no difference. e.g
int a=10;
a++ or ++a has the same meaning,both are incremented by 1 after the statement is executed. But in expression they reacts differently.
e.g int a=10;
System.out.println(a++);
Here the output will be 10 as when postfix expression is used in expression, the expression executes first and then the operator works. So println() will display 10 and after that 'a' will be incremented by 1.
Again in prefix, the operator will work first and after that the expression will work.
e.g
int a=10;
System.out.println(++a);
Here the output will be 11.

 A class is a user-defined data type. Say whether the statement is correct or not and justify your answer.

This statement is correct as we know that type defines the nature and behavior of it's instance. By defining a class we also defines the nature and behavior of it's instance which are known as object.So class can be called as user defined data type.

Give an example of conditional operator.

Suppose int a,b,max are three variables and a and b holds unique value. We want to assign the maximum value on the variable max.
Using conditional statement we can write the codings as below
max=(a>b)?a:b;

Write a function to suppress negative elements of an array to bottom without altering the original sequence i.e. if array contains
5 , -4 , 3 , -2 , 6 , -11 , 12 , -8 , 9 
Then the return array will be  : 5 , 3 , 6, 12 , 9 , -4 , -2 ,  -11 ,  -8 

int separate(int a[],int n)
{
int pos[]=new int[n];
int neg[]=new int[n];
int i,p=0,n1=0
for(i=0;i< n;i++)
{
if(a[i] >=0)
pos[p++]=a[i]
else
neg[n1++]
}
 for(i=0;i< p;i++)
a[i]=pos[i];
for(int j=0;j< n1;j++)
a[i++]=neg[j];
return a;
}

What is inheritance and how is it useful in java ?

Inheritance is the process of acquiring properties, means data members and function members  of any defined class in another class. Inheritance means reuse of codes. By the power of inheritance a class can acquire nature and behavior of a predefined class without writing a single line of code.
There are three types of inheritance - multilevel, multiple and hierarchical. Java supports multilevel and hierarchical inheritance.

What is an exception ? how does java deal with it ?

Exception means run time abnormality.
Java uses Exception Handler to deal with such situation. In java we can use throws clause, try....catch , try...finally block and throw clause as exception handler.

What is meant by polymorphism? Give an example.

Polymorphism is one of the four features of OOPs. When same operator or same function behaves differently in different environment, it is called polymorphism. There are three types polymorphism, operator overloading, function overloading and
function overriding. Constructor overloading is an example of function overloading.

State difference between call-by-value and call-by-reference.

When variables are used as actual and formal argument, it is called call by value and call by reference means when objects are used as actual and formal arguments.

What output will the following code fragment produce ?
int val=9, res , n =1000;

res = n + val > 1750 ? 400 : 200 ;

System.out.println(res);


Output will be 200

What will be the result of following two expressions if I =10 initially ?                                            

I )    ++ I <=10     II ) I++ <=10For the first statement the result will be false and for the second statement the result will be true.Given the following set of identifiers:
long longval ; char ch ; int intval ; float fl ; short sh ;
Identify the datatype of the following expressions:

a) ‘a’-3    b) intval*longval-ch    c) fl+ longval/sh    d) longval * 3

Ans: a) int
b) long
c) float
d) long

Write a java program to print largest even and largest odd number from a list of
numbers entered through keyboard. The list terminates as soon as one enter 0 (zero).

import java.io.*;
class Max
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int maxeven=1,maxodd=2,n;
void take() throws IOException
{
for(;;)
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
if(n==0)
break;
if(n%2==0 && maxeven==1)
maxeven=n;
elseif(n%2==0 && n > maxeven)
maxeven=n;
elseif(n%2!=0 && maxodd=2)
maxodd=n;
elseif(n%2!=0 && n > maxodd)
maxodd=n;
}
System.out.println("Maximum even number="+maxeven);
System.out.println("Maximum odd number="+maxodd);
}
}
 Write a java program to print fibonacci series i.e. 0 1 1 2 3 5 8 ………. 

class Fib
{
int i,p=0,c=1,next;
void  show(int n)
{
System.out.println("Series is as follows:" + p+" "+ c);
for(i=0;i< n-2;i++)
{
next=p+c;
System.out.println(" "+next);
p=c;
c=next;
}
}
}


Let A (n* n) be a two dimensional array. Write a program to find sum of all the elements which lie on either diagonal.

For example for the matrix shown below, your program should output 68 = (1 + 6+11+16+4+7+10+13)                  

1 2 3 4
5 6 7 8
9 10 11 12                                  
13 14 15 16



import java.io.*;
class Mat
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[4][4];
int i,j,sum=0

void take() throws IOException
{
for(i=0;i< 4;i++)
{
for(j=0;j< 4;j++)
{
System.out.println("Enter the number:");
a[i][j]=Integer.parseInt(br.readLine());
}
}
for(i=0;i < 4;i++)
{
for(j=0;j < 4;j++)
{
if(i==j || i+j==3)
sum+=a[i][j];
}
}
System.out.println("sum of the diagonals="+sum);
}
}

This page is on icse sample papers . If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.


Friday, April 30, 2010

ICSE Board Computer question, answer and sample programs


For ICSE and ISC Students
Explain the function of the following with its syntax and an example:
a. If – else
In decision making the most common statement used is if..else.
if (test condition)
{
This block is known as if block or true block.
If the condition is true,statement/statements
of this block will be executed.
}
else
{
This block is known as else block or false block
If the condition is false, this block will be executed.
'else' is optional. The control will execute either if block
or else block.
} 

example:
void display() throws IOException
{
int num;
System.out.println ("Enter the number:");
num=Integer.parseInt(br.readLine());
if (num >100)
{
System.out.println ("The input value is greater than 100.");
/* This is if block. If the condition is false the control will skip this  block.*/
}
else
{
System.out.println ("The value is less than or equal to 100.");
}   

 Switch statement
The switch statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statement/statements associated with that constant are executed and the control leaves the switch body.
The general form of switch statement is:

switch (variable to be compared with a number of constants)
{
body of switch opens.
case int or char constants:
{
case body opens.’ case' is a keyword. case then space then           
the constant value or variable, again space and then:
within the body the statements are kept which are to
be executed when switch variable finds match with
the case constant.
last statement of the case body must be break;
This statement will send the control out of the
switch body.
}
The last case is default: .default is a keyword and
this is optional. If no match is found then the default
body is executed.

void display() throws IOException
{

System.out.println ("Enter the day of the week:-\n");
day=Integer.parseInt(br.readLine());
switch (day)
{
case 1:
System.out.println ("The day is sunday.");
break;
case 2:
System.out.println ("The day is monday.");
break;
case 3:
System.out.println ("The day is tuesday.");
break;
case 4:
System.out.println ("The day is wednesday.");
break;
case 5:
System.out.println ("The day is thursday.");
break;
case 6:
System.out.println ("The day is friday.");
break;
case 7:
System.out.println ("The day is saturday.");
break;
default:
System.out.println ("You have entered a wrong day.");
} // end of switch body
}

Differentiate between isUpperCase() and toUpperCase() function.

Both are String class functions.
isUpperCase()                                                
1. Return type of this function is boolean.                  
If the invoking string object is in upper                  
case this function will return true otherwise              
it returns false. 

toUpperCase() 
Return type of this function is String object.
This function returns the upper case version of the invoking object whether the string is in lower case                        

 Give any 2 advantages of Exception handling.

Using Exception handling we can eliminate the risk of abnormal termination of the program.
using try...finally block we can ensure execution of any specific block of statements
  
What is a “fall through” situation in switch case statement.

In swich case statement, break statement is compulsory at the end of each case body. If this statement is missing, the

control will go on executing the remaining case body statements apart from the case body where the control finds match.

Example:

int a=0;
swich(a)
{
case 0:
a++;
case 1:
a++;
case 2:
a++;
}
Here the match is found in the case 0, since no break statement is used, control will execute all the case bodies.This is called fall through situation in swich statement.

Write a program which will accept a string and print out the text with the uppercase and lowercase letters reversed, but all other characters should remain same as before.

Example : Input    :    WelComE TO School
Output  :    wELcOMe  to sCHOOL

import java.io.*;
class St
{
String str1,str2=" ";
char ch;
int len;
BufferedReader br;
public St()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public void take() throws IOException
{
System.out.println("Enter the string:");
str1=br.readLine();
len=str1.length();
for(i=0;i< len;i++)
{
ch=str1.charAt(i);
if (ch >=97 && ch< =122)
ch=ch-32;
else if(ch >=65 && ch< =90)
ch=ch+32;
str2=str2+ch;
}
str2=str2.trim();
System.out.println("Modified string=" + str2);
}
}

This page is on icse sample papers. If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.

Monday, April 5, 2010

ICSE Board guess Computer question - answer and sample programs



Take a sentence from user and replace a specific character from the sentence with another specific character- both are supplied by the user.

import java.io.*;
class Replace
{
String sent,mod=" ";char orig,rep,ch;int l;
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
public void take()throws IOException
{
System.out.print("Enter the sentence:");
sent=r.readLine();
System.out.print("Enter the character to be replaced:");
orig=(char)r.read();
r=null;
r=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the character with which it is to be replaced:");
rep=(char)r.read();
}
public void replace()
{
l=sent.length();
for(int i=0;i< l ;i++)
{
ch=sent.charAt(i);
if(ch==orig)
mod=mod+rep;
else
mod=mod+ch;
}
mod=mod.trim();
System.out.println("The Modifyed sentence is:"+mod);
}
public static void main(String args[])throws IOException
{
Replace ob= new Replace();
ob.take();
ob.replace();
}
}

A customer purchase a computer from a store. It may be laptop or desktop. Discount is offered against the purchase amount and the rate of discount varies with type of purchase (Laptop or Desktop). The discount rate as follows;

Purchase Amount             Laptop               Desktop
upto 10000                    0.0%                 5.0%
10001 to 20000                5.0%                 7.5%
20001 to 35000                7.5%                 10.0%
above 35000                   10.0%                15.0%


Take the purchase amount, type of purchase and display the payable amount by the customer

import java.io.*;
class Purchase
{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
String t;
double pr,disc,p;
public void take()throws IOException
{
System.out.print("Enter the type of computer(Laptop/Desktop):");
t=r.readLine();
System.out.print("Enter the price range:");
pr=Double.parseDouble(r.readLine());

}
public void price()
{
char ch=t.charAt(0);
if(ch=='L' || ch=='l')
{
if(pr<=10000)
{
p=pr;
}
else if(pr< =20000)
{
disc=5.00;
p=(disc/100)*pr;
}
else if(pr< =35000)
{
disc=7.50;
p=(disc/100)*pr;
}
else if(pr >35000)
{
disc=10.00;
p=(disc/100)*pr;
}
}
else if(ch=='D' || ch=='d')

{
if(pr< =10000)
{
disc=5.00;
p=(disc/100)*pr;
}
else if(pr< =20000)
{
disc=7.50;
p=(disc/100)*pr;
}
else if(pr< =35000)
{
disc=10.00;
p=(disc/100)*pr;
}
else if(pr >35000)
{
disc=15.00;
p=(disc/100)*pr;
}
}
}
public void disp()
{
System.out.println("The total price is:"+(pr-p));
}
public static void main(String args[])throws IOException
{
Purchase ob;
ob=new Purchase();
ob.take();
ob.price();
ob.disp();
}
}

 Take two numbers from the user and display the sum. Every precaution must be taken so that perfect entry is done by the user and result is displayed.

import java io  *;
class My int
{
public static void main (string arg[])
{
bufferdReader br;
string str;
int a,b,c;
booiean bool=true;
br=new BufferedReader(new inhputstreamReader(system.io) );
while(bool)
{
system.out.println("1st no:");
try
{
str=br.readline();
a=interger.passInt(str);
bool=falose
} catch(Exception e)

{
system.out println("wrong enter");
}
}
bool=true;
while(bool)
{
system.out.printline("2nd no");
try
{
b=Interger.parseInt(br.readline());
bool=false;
}
catch(exception e)
{
system.out.println("wrong enter");
}
c=a+b;
system.out.println("sum="+c);
}
}
  
The following public function is a part some class. Assume ‘n’ is always positive. Answer the given question.
Give the dry run/working

int unknown(int n)
{
int i,k;
if(n%2==0)
{
i=n/2;
k=1;
}
else
{
k=n;
n--;
i=n/2;
}
while(I >0)
{
k=k*i*n;
i--;
n--;
}
return k;
}
  
(i) what value will be returned by the expression unknown(7) ? 
Ans: Returned value will be 5040

(ii)what value will be returned by the expression unknown(6) ?
Ans: Returned value will be 720

(iii) In a line state what is being computed by the function unknown(n) ?
Ans : This function is used to calculate the factorial value of the number passed as argument to function int unknown()

Here in the function the value passed as argument is first checked whether it is even or odd. If the number is even then value/2 is assigned on ‘i’ and another variable ‘k’ is initialized with 1. In case the number is odd then ‘k’ is initialized with the number and the number , here ‘n’ is assigned the nearest even number and again ‘I’ is assigned with n/2. This ensures that ‘i’ is assigned with the middle value of the number (n).
Next the while loop multiple k,I and n until I becomes 0 and the value is stored in k. within the loop body valie of i and n is decremented by 1 in each iteration.

Dry run for 7:
k=7
i=3
n=6
While(i>0)
(
k=k*i*n;// means 7*6*3 in first iteration
i--;// I becomes 2
n--;// n becomes 5
}
in the second iteration k becomes 7*6*3*2*5
and I becomes 1 and n becomes 4 so in the last iteration k becomes 7*6*3*2*5*1*4 and the loop breaks as I becomes 0.
  
A public function has been designed to do a binary search for the integer ‘m’ in the sorted integer array data. The array is sorted in ascending order. If ‘m’ is present in the array it returns ‘1’ otherwise returns ‘0’. There are five places in the code marked with ?1?, ?2?, ?3?,?4?,?5? which should be replaced with expression or statement so that the program works properly.

int data (int m, int data[], int size)
{
/* int m is the value to search, int data[] is the array of integers stored in ascending order and  int size is the size of the array.*/
Int found;
Int j=0,k=?1?;
If(?2?)
{
while(?3?)
{
int i=(j+k)/2;
if(m==data[i])
{
?4?;
break;
}
else
{
if(?5?)
j=i+1;
else
k=i-1;
}
}
}
return found;
}

 What is the expression/ statement ?1?
Ans : k=size-1

What is the expression/ statement ?2?
Ans: found==0

What is the expression/ statement ?3?
Ans: j<=kWhat is the expression/ statement ?4?Ans : flag=1;

What is the expression/ statement ?5?
Ans: m>data[i]


This page is on icse sample papers . If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.

Subscribe via email

Enter your email address:

Delivered by FeedBurner