Binary Search Program using methods – array- Class 12 Computer Science


Program to perform binary search, values input by the user using Scanner class. Binary Search can do only in sorted arrays. So a method for Sorting bubble Sort technique , then in the sorted array key is searched by BinarySearch method.

Usually we do by initializing the array value. Here each process defined in user defined methods.

import java.util.*;
public class Userdefined
{
    
     static void BubbleSort(int num[])  //Sorting
    {
        int len=num.length;
        int i,j, temp;
        for(i=0;i<len;i++)
        {
            for( j=0;j<len-i-1;j++)
            {
                if(num[j]>num[j+1])
                {
                    temp=num[j];
                    num[j]=num[j+1];
                    num[j+1]=temp;
                   
                }
            }
        }
   //   System.out.println("Sorted Elements:");
        for(int k=0;k<len;k++)
         System.out.print(num[k]+"\t");
          System.out.println(); 
    }
     static void BinSearch(int num[],int k)  //Binary Search
     {
         int l=0,u=num.length-1;
         int m=0, found=0;
         while(l<=u)
         {
         m= (l+u)/2;
         if( k > num[m])
            l =m+1;
            else if( k< num[m])
            u=m-1;
            else
            {
                found =1;
                break;
                
            }
       
        }
        if(found==1)
         System.out.println(" Element Present at"+" "+ (m+1) +" " +"after sorting");
        
         else
          System.out.println("Not Present");
        }
      public static void main(String [] args)
      {
          Scanner sc=new Scanner(System.in);
          System.out.println( "Enter the total number of elements in the array:");
          int n=sc.nextInt();
          int a[]=new int[n];
          System.out.println( "Enter the elements:");
          for(int i=0;i<n;i++)
          {
          a[i]=sc.nextInt();
          }
         System.out.println("Entered Elements");
          for(int i=0;i<n;i++)
          {
          
       System.out.print(a[i]+"\t");

           }
     System.out.println();
      System.out.println("Elements should be sorted before Binary Search .....\n                                                                                                                                         ..Sorted Elements....");
       BubbleSort(a);                         //invoking BubbleSort ()
      
       System.out.println("Binary Search \n");
       
       System.out.println("Enter element to search");
       int ky=sc.nextInt();
       BinSearch(a, ky); // invoking Binary search method 
    }
     
}

Output:

Enter the total number of elements in the array:
5
Enter the elements:
54
12
78
1
6
Entered Elements
54 12 78 1 6
Elements should be sorted before Binary Search …..
…Sorted Elements….
1 6 12 54 78
Binary Search

Enter element to search
12
Element Present at 3 after sorting

2D Array – ISC 12th Computer- SOLVED SPECIMEN QUESTION PAPER – 2021


harvestfarmfresh.com

Write a program to declare a square matrix M [ ] [ ] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Allow the user to accept three different characters from the keyboard and fill the array according to the instruction given below:

(i) Fill the four corners of the square matrix by character 1.
(ii) Fill the boundary elements of the matrix (except the four corners) by character 2.
(iii) Fill the non-boundary elements of the matrix by character 3.

Test your program with the following data and some random data:

Example 1:
INPUT: N = 4
FIRST CHARACTER: @
SECOND CHARACTER: ?
THIRD CHARACTER: #

OUTPUT:
@ ? ? @
? # # ?
? # # ?
@ ? ? @

Example 2: INPUT: N = 5
FIRST CHARACTER: A
SECOND CHARACTER: C
THIRD CHARACTER: X

OUTPUT:
A C C C A
C X X X C
C X X X C
C X X X C
A C C C A

Example 3: INPUT: N = 15
OUTPUT: SIZE OUT OF RANGE

import java.util.*;
class matRIX
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter no.of rows M of a square matrix:");
        int m=sc.nextInt();
         char mat[][] = new char[m][m];
       System.out.println("Enter corner elements - 1st character:");
       char ch1=sc.next().charAt(0);
        System.out.println("Enter boundary except corner elements - 2ndcharacter:");
       char ch2=sc.next().charAt(0);
         System.out.println("Enter  non boundary  - 3rdcharacter:");
       char ch3=sc.next().charAt(0);
      
          for(int i=0; i<m; i++)
            {
                for(int j=0; j<m;j++)
                {
                    //fill corners with char 1
                    if( (i==0||i==m-1) && (j==0 || j==m-1))
                      mat[i][j]=ch1;
                    //fill non-corner boundary elememts with char 2
                    else if(i==0 || j==0 || i==m-1 || j==m-1)
                         mat[i][j]=ch2;
                    //fill rest with char 3
                    else
                        mat[i][j]=ch3;
                }
            }
            
            //print the array
            System.out.println("");
            for(int i=0; i<m; i++)
            {
                for(int j=0; j<m; j++)
                {
                    System.out.print(mat[i][j] + "\t");
                }
                System.out.println();
            }
        
    }
}

OUTPUT:

Enter no.of rows M of a square matrix:
5
Enter corner elements – 1st character:
@
Enter boundary except corner elements – 2ndcharacter:
?
Enter non boundary – 3rdcharacter:
#

@ ? ? ? @
? # # # ?
? # # # ?
? # # # ?
@ ? ? ? @

Converting first character into UpperCase


Write a program to accept a sentence and check whether it is terminated by ‘.’ or ‘? ‘ or ‘!’ . Display the words using default delimiter (space) and the first character of each word should be converted into Upper Case.

Sample Input :

converting first character.

Sample Output:

converting Converting
first First
character Character

import java.util.*;
class strDec
{
public static String firstLetter(String wrd)
    {
        String res="";char ch2=' ';
        int l=wrd.length();
        for(int i=1;i<l;i++)
        {
        char ch1=wrd.charAt(i);
           ch2=wrd.charAt(0);
        if(Character.isLowerCase(ch2))
        {
           ch2 =Character.toUpperCase(ch2);
    
        }
      //System.out.println(ch1);
        res=res +ch1;
        
    }
        res=ch2+res;
        return res;
        //System.out.println(res);
    }
   public static void main(String args[])
  
   {   strDec strd=new strDec();
       String str;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a sentence:");
        str=sc.nextLine();
     int l=str.length();
        char c=str.charAt(l-1);
       
       if(c=='.'||c=='?'||c=='!')
       {
        StringTokenizer st=new StringTokenizer( str, " .?!");
        int n=st.countTokens();
         String wrd[]=new String [n];
       
         String ch[]=new String[n];
         
      
         
        for(int i=0;i<n;i++){
            wrd[i]=st.nextToken();
            ch[i]=firstLetter(wrd[i]);
        System.out.println(wrd[i] + "    "+ch[i]+" " );
        }
        
     }
        
     else
        {
         System.out.println("Enter a sentence terminated with . or ? or ! :");
   }
       
    }
}

Output:

Enter a sentence:
the sky is the limit.
the The
sky Sky
is Is
the The
limit Limit

ISC Computer Science Practical – Previous Year 2020 – Solved Paper – Matrix program


Write a program to declare a matrix A[][]of order ( M*N) where ‘M’ is the number of rows and ‘N’ is the number of columns such that the value of “M’ must be greater than 0 and less than 10 and the value of ‘N’ must be greater than 2 and less than 6. Allow the user to input digits (0-7) only at each location, such that each row represents an octal number.

Example: 

231(decimal equivalent of 1st row=153 i.e. 2*8² +3*8¹ +1*8⁰)    
405(decimal equivalent of 1st row=261 i.e. 4*8¹ +0*8¹ +5*8⁰) 
156(decimal equivalent of 1st row=110 i.e. 1*8² +5*8¹ +6*8⁰)

Perform the following tasks on the matrix:
  • Display the original matrix.
  • Calculate the decimal equivalent for each row and display as per the format given below.
Example 1:
Input:
M=1        
N=3            
ENTER ELEMENTS FOR ROW 1: 1   4  4
Output:
FILLED MATRIX   DECIMAL EQUIVALENT 
1  4  4                100



Example 2:
Input:
 M=3           
 N=4            
ENTER ELEMENTS FOR ROW 1: 1 1 3 7           
ENTER ELEMENTS FOR ROW 2: 2 1 0 6            
ENTER ELEMENTS FOR ROW 3: 0 2 4 5
Output:            
FILLED MATRIX   DECIMAL EQUIVALENT                          
1 1 3 7         607                             
2 1 0 6         1094                             
0 2 4 5         165



Example 3:
Input:
ENTER ROW SIZE  M=3           
ENTER COLUMN SIZE N=9
Output:OUT OF RANGE
import java.util.*;
class mat
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter no.of rows M ");
        int m=sc.nextInt();
        System.out.println("Enter no.of rows N ");
        int n= sc.nextInt();
        int flag=0,pow=0;  
        int mat[][]=new int[m][n];
        if((m>0 && m< 10 )&&(n>2 && n<6))          //M >0 AND <10  && N>2 AND <6
        {  
            for(int i=0;i<m;i++)
            {System.out.print("Enter elements for row "+(i+1)+":");
                for(int j=0;j<n;j++)
                {
                     mat[i][j]=sc.nextInt();
                     if(mat[i][j] < 0 ||   mat[i][j]>7)     //ALLOW THE USER TO INPUT ONLY FROM 0 TO 7 (OCTAL)
                    {
                        flag=1;
                        System.out.println("INPUT DIGITS (0 -7) ONLY AT EACH LOCATION");
                        System.exit(1);
                        
                    }
                 
                }
                
            }   
        }
        if(flag==0)
        {
            System.out.println("FILLED MATRIX \t DECIMAL EQUIVALENT");
                      for(int i=0;i<m;i++)
                      {
                         int r=0,sum=0;
                          for(int j=n-1;j>=0;j--)  
                          {   
                                  pow=((int)Math.pow(8,r++)); 
                                  sum=sum+(mat[i][j]*pow);
                    
                           }
                           
                           for(int k=0;k<n;k++)
                           {
                               System.out.print(mat[i][k]+ " " );
                           }
                            System.out.print("\t\t \t" +sum);
                            System.out.println();
                      }
         }       
           
                
else
        System.out.println("Enter valid range"); 
 }
}



        
        

OUTPUT:

Enter no.of rows M
3
Enter no.of rows N
3
Enter elements for row 1:2 3 1
Enter elements for row 2:4 0 5
Enter elements for row 3:1 5 6


FILLED MATRIX DECIMAL EQUIVALENT
2 3 1 153
4 0 5 261
1 5 6 110

Tips – ISC Computer Science Board Exam


Keep up on the Exam pattern and Syllabus

Learn the concepts with examples

Dont memorize programs, think logically and write

Practice previous year question papers and specimen copies

Notice and follow the examiners comment from analysis.

Revise everyday.


Be Careful – Whenever practising the programs

Read the questions twice before starting your answer

Use the variables, method and class name what has given in the questions. Instead of that dont use your own variable, method and class. (especially Section B & Section C questions)

You have written the program with correct logic and not following the same variable, method and class name reduce your marks.

Dont forget to create main() and invoke specified methods to main(), if its asked in the question paper.

In Section C, Inheritance programs
DONT WRITE super class, main() and algorithm. (if its specified as NOT to be written)

Do more practice on recursion programs.

Magic square matrix


A magic square is an NxN matrix in which every row, column, and diagonal add up to the same number.

import java.io.*;
class magicmatrix
{
    public static void main (String args[]) throws IOException
    {
        InputStreamReader read =new InputStreamReader (System.in);
        BufferedReader x= new BufferedReader(read);
        System.out.println("Enter the size of the matrix");
        int n=Integer.parseInt(x.readLine());
        if(n>5)
        System.out.println("Enter the number from 1 to 5");
        else
        {
            int A[][]=new int[n][n];
            int i,j,k,t;
            for(i=0;i<n;i++)
            {
                for(j=0;j<n;j++)
                {
                    A[i][j]=0;
                }
            }
            if(n%2!=0)
            {
                i=0;
                j=n/2;
                k=1;
                while(k<=n*n)
                {
                    A[i][j]=k++;
                    i--;
                    j++;
                    if(i<0&&j>n-1)
                    {
                        i=i+2;
                        j--;
                    }
                    if(i<0)
                    i=n-1;
                    if(j>n-1)
                    j=0;
                    if(A[i][j]>0)
                    {
                        i=i+2;
                        j--;
                    }
                }
            }
            else
            {
                k=1;
                for(i=0;i<n;i++)
                {
                    for(j=0;j<n;j++)
                    {
                        A[i][j]=k++;
                    }
                }
                j=n-1;
                for(i=0;i<n/2;i++)
                {
                    t=A[i][j];
                    A[i][i]=A[j][j];
                    A[j][j]=t;
                    t=A[i][j];
                    A[i][j]=A[j][i];
                    A[j][i]=t;
                    j--;
                }
            }
            System.out.println("The magic matrix of size "+n+"x"+n+" is:");
            for(i=0;i<n;i++)
            {
                for(j=0;j<n;j++)
                {
                    System.out.print(A[i][j]+"\t");
                }
                System.out.println();
          
            }
        
        }
    }
}
        

Output:

Enter the size of the matrix
3
The magic matrix of size 3×3 is:
8 1 6
3 5 7
4 9 2

IMEI number


An IMEI number/ International Mobile Station Equipment Identity is a 15 digit number and it is said to be IMEI number if and only if the sum of the number is exactly divisible by 10.

The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin, model, and serial number of the device.

The IMEI number is used by a GSM network to identify valid devices and therefore can be used for stopping a stolen phone from accessing that network

The IMEI is validated in three steps:

  1. Starting from the right, double every other digit (e.g., 7 becomes 14).
  2. Sum the digits (e.g., 14 → 1 + 4).
  3. Check if the sum is divisible by 10.
Input:  47415403237518
Output:
47415403237518 – Is an IMEI Number.
import java.io.*;
public class CheckIMEINumber{
// Function for finding and returning sum of digits of a number
	int sumDig(int n) 
	{
		// initialise here.
		int a = 0;
	    while(n>0)
	    {
	    	a = a + n%10;
	        n = n/10;
	    }
	    return a;}	     
	public static void main(String args[])throws IOException
	{
	// create object here.
		CheckIMEINumber ob = new CheckIMEINumber();
	    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            // The 'Long' data type is used to store 15 digits.
	    System.out.print("Enter a 15 digit IMEI code : ");
	    long n = Long.parseLong(br.readLine()); 
	// Converting the number into String for finding length
	    String s = Long.toString(n); 
	    int l = s.length();
	// If length is not 15 then IMEI is Invalid
	    if(l!=15) 
	    System.out.println("Output : Invalid Input");
	else
	    {  	int d = 0, sum = 0;
	        for(int i=15; i>=1; i--)
	        {
	        	d = (int)(n%10);
		if(i%2 == 0)
	            {
	        		// Doubling every alternate digit
	        		d = 2*d; 
	            }
	// Finding sum of the digits
	        	sum = sum + ob.sumDig(d); 
	        	n = n/10;
	        }
	             
	        System.out.println("Output : Sum = "+sum);
	          if(sum%10==0)    
	        	System.out.println("Valid IMEI Code");
	        else
	            System.out.println("Invalid IMEI Code");
	    }
	}}


Enter a 15 digit IMEI code : 47415403237518
Output : Invalid Input
Enter a 15 digit IMEI code : 490154203237518
Output : Sum = 60
Valid IMEI Code
Enter a 15 digit IMEI code : 123456789101112131
Output : Invalid Input

Pronic Number/oblong number/ rectangular number / heteromecic number


Pronic Number : A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n (n + 1). The first few pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 …

Input :56
Output :Pronic Number
Explanation: 56 = 7 * 8 i.e 56 is a product of two consecutive integers 7 and 8.
import java.util.*;
class PronicNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        int flag = 0;
    
        for(int i=0; i<n; i++)
        {
            if(i*(i+1) == n)
            {
                flag = 1;
                break;
            }
        }
         
        if(flag == 1)
            System.out.println(n+" is a Pronic Number.");
        else
            System.out.println(n+" is not a Pronic Number.");      
    }

Enter a number : 123
123 is not a Pronic Number.
Enter a number : 110
110 is a Pronic Number.

Display as Lower triangular matrix program in java


A square matrix is called lower triangular if all the entries above the main diagonal are zero. Similarly, a square matrix is called upper triangular if all the entries below the main diagonal are zero. A triangular matrix is one that is either lower triangular or upper triangular.


import java.util.*;
class lowerTriangular
{
    void lowermat(int matrix[][],  
                      int row, int col) 
    { 
        int i, j; 
        for (i = 0; i < row; i++) 
        { 
            for (j = 0; j < col; j++) 
            { 
                if (i < j) 
                { 
                    System.out.print("0" + " "); 
                } 
                else
                System.out.print(matrix[i][j] + " "); 
            } 
            System.out.println(); 
        } 
    } 
      
 
   public static void main(String args[])
   { Scanner sc=new Scanner(System.in);
       lowerTriangular lt=new lowerTriangular();
        int i,j,count=0,no,size,flag=0;
        System.out.println("Enter size");
        size =sc.nextInt();
        int a[][]=new int[size][size];

        for(i=0;i<size;i++)
        {
            for (j=0;j<size;j++)
            {
                System.out.println("Enter the element("+i+","+j+")");
                a[i][j]=sc.nextInt();
            }
        }
        System.out.println("The given matrix:");
        for(i=0;i<size;i++)
        {
            for (j=0;j<size;j++)
            {
                System.out.print(a[i][j]);
              
            }
            System.out.println();
        }
        System.out.println("Lower triangular matrix");
        lt.lowermat(a,size,size);
    }
}

Output:

Enter size
3
Enter the element(0,0)
1
Enter the element(0,1)
2
Enter the element(0,2)
3
Enter the element(1,0)
4
Enter the element(1,1)
5
Enter the element(1,2)
6
Enter the element(2,0)
7
Enter the element(2,1)
8
Enter the element(2,2)
9
The given matrix:
123
456
789
Lower triangular matrix
1 0 0
4 5 0
7 8 9

Diagonal matrix program in java


A square matrix is said to be diagonal matrix if the elements of matrix except main diagonal are zero.

A square null matrix is also a diagonal matrix whose main diagonal elements are zero.

import java.util.*;
class DiagonalMatrix
{
	public static void main(String args[])throws Exception
	{
		Scanner sc=new Scanner(System.in);
		System.out.print("Enter the size of the matrix : ");
		int m=sc.nextInt();
		int A[][]=new int[m][m];
		
		/* Inputting the matrix */
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print("Enter an element : ");
				A[i][j]=sc.nextInt();
			}
		}

		
		System.out.println("The Matrix is : ");
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print(A[i][j]+"\t");
			}
			System.out.println();
		}
		
		int p=0, q=0;
		
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(i!=j && A[i][j]!=0) // Checking non-diagonal elements
				{
					p=1;
					break;
				}
				if(i==j && A[i][j]==0) // Checking diagonal elements
				{
					q++;
				}
		    }
		}
		
		if(p==0 && q<m)
			System.out.println("The matrix is Diagonal");
		else
			System.out.println("The matrix is not Diagonal");
	}
}

Output:

Enter the size of the matrix : 3
Enter an element : (0,0)1
Enter an element : (0,1)0
Enter an element : (0,2)0
Enter an element : (1,0)0
Enter an element : (1,1)3
Enter an element : (1,2)0
Enter an element : (2,0)0
Enter an element : (2,1)0
Enter an element : (2,2)45
The Matrix is :
1 0 0
0 3 0
0 0 45
The matrix is Diagonal

Scalar matrix program in java


Write a Program in Java to input a 2-D square matrix and check whether it is a Scalar Matrix or not.

Scalar Matrix : A square matrix is said to be scalar matrix if all the main diagonal elements are equal and other elements except main diagonal are zero. Scalar matrix can also be written in form of n * I, where n is any real number and I is the identity matrix.

import java.util.*;
class ScalarMatrix
{
	public static void main(String args[])throws Exception
	{
		Scanner sc=new Scanner(System.in);
		System.out.print("Enter the size of the matrix : ");
		int m=sc.nextInt();
		int A[][]=new int[m][m];
		
		/* Inputting the matrix */
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print("Enter an element :("+i+","+j+") ");
				A[i][j]=sc.nextInt();
			}
		}

		/* Printing the matrix */
		
		System.out.println("The Matrix is : ");
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				System.out.print(A[i][j]+"\t");
			}
			System.out.println();
		}
		
		
		int p = 0, q = 0, x = A[0][0]; // 'x' is storing the 1st main diagonal element
		
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
			    /* Checking that the matrix is diagonal or not */
				if(i!=j && A[i][j]!=0) // All non-diagonal elements must be zero
				{
					p=1;
					break;
				}
				/* Checking the matrix for scalarity */
				// All main diagonal elements must be equal to 'x' and non-zero
				if(i==j && (A[i][j]==0 || A[i][j]!=x)) 
				{
					q=1;
					break;
				}
		    }
		}
		
		if(p==0 && q==0)
			System.out.println("The matrix is scalar");
		else
			System.out.println("The matrix is not scalar");
	}
}

Output:

Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 2
Enter an element :(0,2) 1
Enter an element :(1,0) 3
Enter an element :(1,1) 1
Enter an element :(1,2) 3
Enter an element :(2,0) 1
Enter an element :(2,1) 1
Enter an element :(2,2) 3
The Matrix is :
1 2 1
3 1 3
1 1 3
The matrix is not scalar
Enter the size of the matrix : 3
Enter an element :(0,0) 1
Enter an element :(0,1) 0
Enter an element :(0,2) 0
Enter an element :(1,0) 0
Enter an element :(1,1) 1
Enter an element :(1,2) 0
Enter an element :(2,0) 0
Enter an element :(2,1) 0
Enter an element :(2,2) 1
The Matrix is :
1 0 0
0 1 0
0 0 1
The matrix is scalar

String program using StringTokenizer


ISC – Model Question Paper -October 2018

Design a class Chord that accepts a string and prints the number of vowels present in each word of the string. Also note that a string is considered valid if it does not contain any repeated spaces. For example : String : “SUMMER IN AUSTRALIA IS IN DECEMBER.
Output: SUMMER : 2
IN : 1
AUSTRALIA : 5
IS : 1
IN : 1
DECEMBER : 3
Some of the members of the class Chord are given below:
Class Name : Chord
Data members
cd : the string
Member functions:
Chord() : to initialize the member string to null
void fnInput() : to input the member string
void fnOperate() : to print “invalid Sting “ if the string is not valid, otherwise print the words of the member string along with the number of vowels present in them.

boolean isValid() : to verify whether the given string is valid or not and return true or false.
int fnVowel(String w) : to count and return the no. of vowels present in argument ‘w’.

import java.util.*;
class cord
{
String cd;
cord()
{
cd=””;
}
void fnInput()
{
Scanner sc=new Scanner(System.in);
System.out.println(“enter the string:”);
cd=sc.nextLine();
}

//Check the String is valid
boolean isValid()
{
for(int j=0;j<=cd.length()-2;j++)
{
if(cd.charAt(j)==’ ‘ && cd.charAt(j+1)==’ ‘) // checking repeated space
{
return false; //if repeated space, String is invalid
}
}
return true;

}
void fnOperate()
{
fnInput();
if(isValid() == false)
{
System.out.println(“Invalid string”);
return;
}
StringTokenizer st=new StringTokenizer(cd);
int ct=st.countTokens();
for(int j=1;j<=ct;j++)
{
String wrd=st.nextToken();
int cw=fnVowel(wrd);
System.out.println(wrd +” ” +cw);

}
}

//counting the vowels in the argument ‘w’
int fnVowel(String w)
{
int c=0;
w=w.toUpperCase();
for(int j=0; j<=w.length()-1;j++)
{
if(w.charAt(j)==’A’||w.charAt(j)==’E’||w.charAt(j)==’I’||w.charAt(j)==’O’||w.charAt(j)==’U’)
c++;
}
return c;
}
public static void main(String args[])
{
cord c1=new cord();
c1.fnOperate();
}

}

ISC – Model Question Paper -October 2018


Question 1

  1. Draw the truth table and logic diagram for the 2 inputs XOR gate. [1]
  2. Using the truth table, verify the following expression. X+(Y+Z) = (X+Y)+Z [1]
  3. If F(A,B,C)=A.B’+A’+A’.B+B’, then find F’.                                                 [1]
  4. Verify using truth table ( A ^ ~B ) V (~A ^ B) V A = AVB                                     [1]
  5. Simply the given expression using Boolean laws: F1=(a+c’).(a’+b’+c’) [1]

Question 2

  1. An array DR[-2…2,-3…3] stores elements in Col major wise, with address DR[0][0] as 2500. If each element requires 2 bytes of storage, find the base address.     [2]
  2. Write a java statement for the following:
    i) write data to a file “emp.dat” in binary form.
    ii) Read data from a file “story.txt” in text form.                             [2]
  3. Convert the following infix to postfix form:
    ((M/N-P) * (Q+R)) /(C+D)     [2]
  4. State one case when the error “Queue Overflow” occur.                                                  [2]
  5. Convert from infix to prefix form P*Q/R*(S+T/(U-V))                                            [2]

 

Question 3                                                                                                                                   [5]

The following function witty() is a part of some class. What will be the output of the function witty() when the value of n is “SCIENCE” the value of p is 5. Show the dry run/working.
void witty(String n, int p) {
if (p<0)
System.out.println(“”);
else{
System.out.println(n.charAt(p) +”.”};
witty(n, p-1);
System.out.println(n.charAt(p));
}
}

                                             PART II (50 Marks)

   Answer six questions in this part, choosing two questions from Section A,
                               two from Section B and two from Section C.
SECTION – A
                                        Answer any two questions

Question 4

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,,2,5,7,8,10,11,13,14,15)
    i)  Reduce the above expression by using 4 variable Karnaugh map, showing               [4]
    the various groups (i.e., octal, quads, pairs).
    ii) Draw the logic gate diagram for the reduced expression using NAND gates only.    [1]
    Assume that the variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (2,3,6,7,9,11,12,13,14,15)
  • Reduce the above expression by using 4 variable Karnaugh map, showing   [4]
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression using NOR gates only. [1]
    Assume that the  variables and their complements are available as inputs.

Question 5

  1. The person is not an Indian citizen but has taken active part in activities for the upliftment of the nation. The inputs are:
    Inputs
          A         The person is/was an Indian citizen
    B          Has a continuous service of more than 20 years.

C         lost his/her life in a war.
D   Taken part in activities for upliftment of the nation.

Output:  X denotes eligible for medal [1 indicate yes, 0 indicates no for all cases]
Draw the truth table for the inputs and outputs given above and write POS expression for X(A,B,C,D)                                                                                                        [5]

  1. Write the cardinal form of P(A,B,C) = ABC’ +A’BC +A’BC’+ABC                     [2]

                      

Question 6

  1. Using a truth table, verify the following proposition is valid or invalid [3]
    (a
    àb) ^(bàc) =(aàc)
  2. Draw the truth table representing a 2 input XNOR gate and derive its SOP expression and draw its logic gate diagram. [2]
  3. What is a multiplexer? Draw the truth table and logic diagram of 8*1 multiplexer. [5]                                                                                                

                                                                                   

            SECTION – B

     Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 7

A class Admission contains the admission numbers of 100 students. Some of the data members/ functions are given below:
Class name       :           Admission
Data members:
Adno[]             : integer array to store admission numbers
Member functions:
Admission()      : constructor to initialize the array elements
void fillArray(): to accept the elements of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number(v) using binary search and recursive technique and returns 1 if found otherwise returns -1.

Specify the class Admission, giving details of the constructor , void fillArray(), and
int binSeacrh(int, int, int). Define the main() to create an object and call the function accordingly to enable the task.

Question 8                                                                                                                             

The transpose of a matrix is found by interchanging the elements of rows and columns.
Design a class matrix that contains a 2D array of order [n * n ]. The maximum value possible for n is 20. The details of some of the members of the class are given below
Class name    : matrix
Data members:
int t[][]                   : to store the matrix
int n                        : integer to store the number of rows and columns
Member functions:
matrix(…..)             : Parameterized constructor to initialize n and to allocate memory to member array
void fnGet()       :  to fill the member array
void fnDisplay() : to show the member matrix
matrixfnTrans(matrix A)  : to store the transpose of the argument matrix in the current object and return that.
Specify the class matrix giving the details of the above member data and methods only

Question 9                                                                                                                              [10]

Design a class Chord that accepts a string and prints the number of vowels present in each word of the string. Also note that a string is considered valid if it does not contain any repeated spaces. For example : String   : “SUMMER IN AUSTRALIA IS IN DECEMBER.
Output:   SUMMER    :  2
IN   :           1
AUSTRALIA   :  5
IS         : 1
IN        : 1
DECEMBER   :   3
Some of the members of the class Chord are given below:
Class Name      : Chord
Data members
cd                    : the string
Member functions:
Chord()            : to initialize the member string to null
void fnIn()        : to input the member string
void fnOp()      : to print “invalid Sting “ if the string  is not valid, otherwise print the words of the member string along with the number of vowels present in them.

                                                            SECTION – C
                                                     Answer any two questions.
Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
                                       The programs must be written in Java.

 

Question 10                                                                                                                            [5]

A super class Circle has a sub class Circumference. The details of both the classes are given below.

The details of the base class:
Class name                   : Circle

Data member/ instance variable :

int rad               : an integer to store the  radius

Member functions/methods

Circle (….)                   : parameterized constructor to initialize the data members.

void show()                  : to display the  member data.

 

The details of the derived class:

Class name                   : Circumference

Data member                :

double cir                     : to store the Circumference

Member functions

Circumference (…)                   : parameterized constructor to initialize the data members of the base and current class

void calCirum               : calculates the circumference by using the formula (2*pi*r) (pi=3.14)
void show()                  : to display the details of both the classes with proper messages(apply method overriding).
Specify the class Circumference giving the details of its mentioned methods. Assume that class Circle is already present. Write the main ().

Specify the base class, derived class and write the main() and call above member methods.

 

Question 11                                                                                                                            [5]

A class  Flow allows that a user to add and delete names in a list from the same end(top). The following details of the class Flow are given below:
Class name                   :Flow

Data members :
names[]                        : a string array to hold a maximum of 10 names
top                               : stores the position of the topmost element.
Member methods:
Flow(….)                     : initialize the data member top=-1 and to create the string array
void pushName(String n): to push a name into the stack at position top, if possible, else display the message “Overflow”.
String popName()         : to remove and return element from the top. If the list is empty then return “Underflow”.

Model Question Paper -ISC Computer Science – Oct 2018


PART – I (20 Marks)
Answer
all questions.
While answering questions in this Part, indicate briefly your working and reasoning, wherever required.

Question 1

  1. Verify using the truth table, if (x => y).(y =>x) is a tautology, contradiction and contingency.                                                               [1]
  2. State the two Idempotence law. Verify any one using truth table.      [1]
  3. If F(A,B,C)=A’(BC’+B’C), then find F’.                                                        [1]
  4. Verify using truth table ( A ^ ~B ) V (~A ^ B) V A = AVB [1]
  5. Write the dual of (a.b’+0).(a’.b+1)                                                   [1]

Question 2

  1. An array DR[-2…2,-3…3] stores elements in Col major wise, with address DR[0][0] as 2500. If each element requires 2 bytes of storage, find the base address.                                                                [2]
  2. Explain the given keyword in brief: 1) import 2) extends              [2]
  3. State the difference between Function overloading and Function overriding [2]
  4. What is the difference between private and protected access specifier with an example.    [2]
  5. A char array B[7][6] has a base address 1046 at(0,0). If the address at B[2][q] is 1096. Find the value of q, given that the array is stored column major wise. Each char requires 2 bytes of storage. [2]

 Question 3   [5]

Give the output of the following function where x and y are arguments greater than 0. Show the dry run/working.

void confusing(int x, int y) 
{
if(x>1)  { 
               if( x%y==0) { 
                               System.out.print(y+””);
                              confusing(x/y, y);
                            }
else   {
confusing(x, y+1); }
}

1) What will be the function confusing(24,2 ) return?
2) What will be the function confusing(84,2) return?
3) In one line, state what is the function is doing, apart from recursion?

                                             PART II (50 Marks)

   Answer six questions in this part, choosing two questions from Section A, two from Section B and two from Section C.
SECTION – A
                                        Answer any two
questions

Question 4 [10]

  • Given the Boolean function : F(A,B,C,D) =Ʃ(0,1,2,5,8,9,10)
    i)  Reduce the above expression by using 4 variable Karnaugh map, showing     the various groups (i.e., octal, quads, pairs).
    ii) Draw the logic gate diagram for the reduced expression. Assume that the      variables and their complements are available as inputs.
  • Given the Boolean function : F(P, Q,R,S) =Π (3,4,6,7,11,12,13,14,15)
  • Reduce the above expression by using 4 variable Karnaugh map, showing
    the various groups (i.e., octal, quads, pairs).
  • Draw the logic gate diagram for the reduced expression. Assume that the variables and their complements are available as inputs.

Question 5 [10]

  1. A person is allowed to travel in a reserved coach of the train, if he/she satisfies any one of the criteria given below:
    The person has a valid reservation ticket and a valid ID proof.
    OR
    The person does not have a valid reservation ticket, but holds a valid pass issued by the Railway department with a valid ID proof.
    OR
    The person is a senior citizen and holds a valid pass issued by the Railway department along with a valid ID proof.
    The inputs are:
            Inputs
    R         The person has a valid reservation ticket
    P          The person holds a valid pass issued by the Railway department
    D         The person has a valid ID proof.
    S          The person is a senior citizen.
    Output: T denotes allowed to travel [1 indicate yes, 0 indicates no for all cases]
    Draw the truth table for the inputs and outputs given above and write the SOP expression for T(R,P,D,S).
  2. Verify using truth table, whether the given expression is a contradiction or not.             P(A,B) = A. (A’ +B)      +AB’
  3. Write the cardinal form of P(A,B,C) =ABC’+ A’BC+ A’BC’ +ABC                                 

Question 6 [10]

  1. What is an encoder? Draw the logic circuit of an Octal to Binary encoder.
  2. What is a decoder? Draw the logic gate diagram, block diagram for a 3 to 8 decoder.

            SECTION – B

     Answer any two questions.

Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
The programs must be written in Java.

Question 7 [10]

An Armstrong number is such that the sum of the cube of the digits of the number is the number itself. Example 153= 13+53+33
Design  a class Arm to perform the given task. Some of the members of the class are given below:

Class name                              : Arm
Data member/Instance variables         :
no                                            : integer to store the number
sum                                          : integer to store the sum of the cube of the digits
Member methods:
Arm(….)                                 : to initialize member data no, and assign 0 to sum.
long fnPower(int a, int b)        : to calculate a^b using recursive function
void fnPerform()                     : to verify and print whether the member data is an Armstrong number or not.
Specify the class Arm, giving the details of the above member data and methods. Also define the main() to create an object and call the relevant methods accordingly to enable the task.

Question 8                   [10]

Design a class EQUA that contains a 2D integer array of order [m *n]. The maximum value possible for m,n is 10. The details of some of the members of the class are given below:

Class name                              :           EQUA
Data member/Instance variables  :
Tam [] []                                              : to store the matrix
int m,n                                                 : integers to store the number of rows and columns
Member functions  :
EQUA(….)                                         : parameterized constructor to initialize m, n and to allocate memory to member array
void fnGet()                                        : to fill the member array with random integers
void fnDisplay()                                  : to show the member matrix
Boolean fnlsEqual(EQUA M)                        : to compare the matrix of the
argument object and the current matrix for equality. If equal, then return true else return false. [ two matrices are equal if all elements are same in corresponding cells]

Specify the class EQUA, giving the details of the above member data and methods. Also define the main() to create an object and call the other methods accordingly to enable the task.

Question 9                     [10]

Design a class Alpha which enables a word to be arranged in ascending order according to its 10 alphabets. The details of the members of the class are given below:
Class name                                          : Alpha
Data members
Str                                                       : to store a word
Member methods:
Alpha()                                    : default constructor
void readword()                      : to accept the inputted word
void arrange()                          : to arrange the word in alphabetical order using any standard sorting technique.
void disp()                               : displays the word.

Specify the class Alpha giving details of the constructor and the member functions void readword(), void arrange(), void disp() and defining the main() to create an object and call the function in order to execute the class by displaying the original word and the changed word with proper message.

    SECTION – C
           Answer
any two questions.
Each program should be written in such a way that it clearly depicts the logic of the problem. This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are
not required.)
         The programs must be written in Java.

Question 10                                                                                                        [5]

A super class Tour has a sub class Tourist. The details of both the classes are given below.

The details of the base class:
Class name                  : Tour

Data member/ instance variable :
int budget                    : to store the tour budget
int dist             : to store the proposed distance to travel in kilometer
Member functions/methods
Tour(….)                     : parameterized constructor to initialize the data members.
Void print()                 : to print the member data with proper messages.

The details of the derived class:
Class name                  : Tourist
Data member               :
String Name                 : to store the name of the tourist
double rate                  : to store the rate proposed per kilometer
Member functions
Tourist(…)                  : parameterized constructor to initialize the data members of the base and current class
void modify()              : modifies the rate after giving certain discounts, depending on proposed distance to travel as per the following chart
Distance                                  Discount
>=10000                                  40% of rate
<10000 && >=5000               20% of rate
<5000  && >=1000                10 % of rate
void print()                  : to display the details of both the classes with proper messages. Also note to print the rate proposed and the rate applied.

Specify the base class, derived class and write the main() and call above member methods.

Question 11                                                                                 [5]

Given the following code, answer the questions given below(Show the dry run/working)

void design(int d) {
int k=d, r=0, pw=0;
double b=0.0;
do {
r=k%10;
b=b*0.1 +r;
k/=10;
System.out.println(k+””+b+”*10^”+pw);
pw++;
}while(k!=0);

}

  1. What will be the output if d=2345?
  2. What will be the output if d=46?

Question 12                                                                                                              [5]

A class Admission contains the admission numbers of 100 students. Some of the data members/ functions are given below:
Class name      :           Admission
Data members:
Adno[]                        :
integer array to store admission numbers
Member functions:
Admission()    :
constructor to initialize the array elements
void fillArray():
to accept the elements of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number(v) using binary search and recursive technique and returns 1 if found otherwise returns -1.

Specify the class Admission, giving details of the constructor , void fillArray(), and int binSeacrh(int, int, int). Define the main() to create an object and call the function accordingly to enable the task.

Perform a right circular shift and a left circular shift on alternate rows of the array — by object


A class Whirl contains a 2D array of order [m * n]. Perform a right circular shift and a left circular shift on alternate rows of the array.
For example:  Input  m=5, n=4
The matrix is:
20 2 24 25
48 18 13 47
43 18 30 32
22 45 30 38
48 12 18 37

Output:
Right circular shift and left circular shift on alternate rows of the matrix:
The matrix is:
25 20 2 24
18 13 47 48
32 43 18 30
45 30 38 22
37 48 12 18

Class name              :Whirl
Data member:
wam[][]            : to store the amtrix
int m, n             : integer to store the number of rows and columns
Member functions:
Whirl(……)        :  initialize m, n and to allocate memory to member array
void fnGet()     : to fill the member array
void fnDisplay() : to show the member matrix
Whirl fnChangeMat()  :  modify the current matrix as per the given criteria and returns it.Specify the class Whirl, and define main() , giving the details of the above member data and methods.
Program:

import java.util.*;
class Whirl
{
int wam[][], m,n;
Whirl(int m1, int n1)
{
m=m1; n=n1;
wam=new int[m][n];
}
void fnGet()
{
for(int r=0;r<=m-1;r++)
{
for(int c=0;c<=n-1;c++)
wam[r][c]=(int)(Math.random()*50);
}
}

void fnDisplay()
{
System.out.println(“The matrix is:”);
for(int r=0;r<=m-1;r++)
{
for(int c=0;c<=n-1;c++)
{
System.out.print(wam[r][c]+”\t”);
}
System.out.println();
}

}
Whirl fnChangeMat()
{ int tmp=0;
for(int r=0;r<=m-1;r++)
{
if(r%2==0)
{
tmp=wam[r][n-1];
for(int c=n-1;c>=1;c–)
{ wam[r][c]=wam[r][c-1];
}
wam[r][0]=tmp;
}
else
{
tmp=wam[r][0];
for(int c=0;c<=n-2;c++)
{
wam[r][c]=wam[r][c+1];
}
wam[r][n-1]=tmp;
}
}
return this;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println(“Enter the value of m:”);
int m1=sc.nextInt();
System.out.println(“Enter the value of n:”);
int n1=sc.nextInt();
Whirl w=new Whirl(m1,n1);
Whirl w1=new Whirl(m1,n1);
w.fnGet();
w.fnDisplay();
w1=w.fnChangeMat();
System.out.println(“Right circular shift and left circular shift on alternate rows of the matrix:”);
w1.fnDisplay();
}
}

Output:
Enter the value of m:
5
Enter the value of n:
4
The matrix is:
20 2 24 25
48 18 13 47
43 18 30 32
22 45 30 38
48 12 18 37
Right circular shift and left circular shift on alternate rows of the matrix:
The matrix is:
25 20 2 24
18 13 47 48
32 43 18 30
45 30 38 22
37 48 12 18

Two matrices are equal( by object) – ISC 2018


Two matrices are said to be equal if they have the same dimension and their corresponding elements are equal.

For example , the two matrices A and B given below are equal:

Matrix A                 Matrix B
1  2    3                     1   2     3
2   4   5                     2   4     5
3    5   6                    3     5    6
Design a class EqMat to check if tow matrices are equal or not. Assume that the two matrices have the same dimension.
Class name            :  EqMat
Data members:
a[][]                                        : to store integer elements
m, n                                        : to store the number of rows and columns
Member functions:
EqMat(int mm, int nn)             :  initialize the data members m=mm and n=nn
void readarray()                        :  to enter the elements in the array
int check(EqMat P, EqMat Q)  : checks if the parameterized objects P and Q are equal and returns 1 if true,otherwise returns 0.
void print()                                 : displays the array elements
Define the class and define main() to create objects and call the functions accordingly to enable the task.

Program:

import java.util.*;
class EqMat{
int a[][], m,n;
EqMat( int mm, int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
public void readarray()
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the elements for the array:”);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
}
public int check(EqMat P, EqMat Q)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(P.a[i][j]!=Q.a[i][j])
return 0;
}
}
return 1;
}

public void print()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+”\t”);
}
System.out.println();
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the row and column size for the array:”);
int a=sc.nextInt();
int b=sc.nextInt();
EqMat A =new EqMat(a,b);
EqMat B=new EqMat(a,b);
A.readarray();
B.readarray();
A.print();
System.out.println();
B.print();
if(A.check(A,B)==1)
System.out.println(“Both are equal matrix”);
else
System.out.println(“Both are unequal matrix”);
}
}

Output:

Enter the row and column size for the array:
3
3
Enter the elements for the array:
2
3
4
5
6
7
8
9
1
Enter the elements for the array:
2
3
4
5
6
7
8
9
2
First matrix
2 3 4
5 6 7
8 9 1

Second matrix
2 3 4
5 6 7
8 9 2
Both are unequal matrix

Subtraction of matrix (object)


A class matrix  contains a @d integer array of order[m * n]. The maximum value possible for both m and n is 10. Design a class matrix to find the difference of the two matrices. the details of the members of the class are given below:
Class name     : matrix
Data members:
atm[][]      : to store the matrix
m, n          :  integer to store the number of rows and columns
Member functions:
Matrix(…..)   : initialize m, n  and to allocate memory to member array
void fnGet()   : to fill the member array
void fnDisplay() : to show the member matrix
Matrix fnSub(Matrix A)  : Subtract the current object from the matrix of parameterized object and return the resulting object.
Specify the class Matrix,  Define main(), giving the details of the above member data and methods only.

Program:

import java.util.*;
class Matrix
{
int atm[][];
int m,n;

public Matrix(int r, int c)
{m=r;
n=c;
atm= new int [m][n];

}
void fnGet()
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.println(“Enter the elements:”);
for(i=0;i<m;i++){
System.out.println(“Enter the elements of row:”+(i+1));
{for(j=0;j<n;j++)
{
atm[i][j]=sc.nextInt();
}
System.out.println();
}}
}
void fnDisplay()
{
System.out.println(“The array elements:”);
int i,j;
for(i=0;i<m;i++)
{for(j=0;j<n;j++)
{
System.out.print(atm[i][j]+”\t”);
}
System.out.println();
}
}
public Matrix1 fnSub(Matrix1 o1)
{
int i, j;
Matrix1 o3=new Matrix1(m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
o3.atm[i][j]=o1.atm[i][j]-atm[i][j];
return o3;
}

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the values of row and columns:”);
int r=sc.nextInt();
int c=sc.nextInt();
Matrix m1=new Matrix(r,c);
Matrix m2=new Matrix(r,c);
Matrix m3=new Matrix(r,c);
System.out.println(“Enter the 1st array:”);
m1.fnGet();
System.out.println(“Enter the 2nd array”);
m2.fnGet();

System.out.println(“\u000c”);
System.out.println(“array1 elements:”);
m1.fnDisplay();
System.out.println(“array2 elements:”);
m2.fnDisplay();
m3=m2.fnSub(m1);

System.out.println(“Subtracted” );
m3.fnDisplay();
}
}

Output:

Enter the values of row and columns:
2
3
Enter the 1st array:
Enter the elements:
Enter the elements of row:1
9
8
7

Enter the elements of row:2
6
5
4

Enter the 2nd array
Enter the elements:
Enter the elements of row:1
6
5
4

Enter the elements of row:2
4
3
2

array1 elements:
The array elements:
9 8 7
6 5 4
array2 elements:
The array elements:
6 5 4
4 3 2
Subtracted
The array elements:
3 3 3
2 2 2

 

 

Anti clockwise spiral matrix / anti clockwise circular matrix – java


import java.util.*;
class anticlockwise
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int n = sc.nextInt();

int A[][] = new int[n][n];
int k=n*n, c1=0, c2=n-1, r1=0, r2=n-1;

while(k>=1)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k--;
}

for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k--;
}

for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k--;
}

for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k--;
}
c1++;
c2--;
r1++;
r2--;
}

/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
}
}

Output:

Enter the number of elements : 4
The Circular Matrix is:
16 15 14 13
5 4 3 12
6 1 2 11
7 8 9 10

Transpose of a matrix using object


The transpose of a matrix is found by interchanging the elements of rows and columns.
Design a class matrix that contains a 2D array of order [n * n ]. The maximum value possible for n is 20. The details of some of the members of the class are given below
Class name    : matrix
Data members:
int t[][]                   : to store the matrix
int n                        : integer to store the number of rows and columns
Member functions:
matrix(…..)             : parameterized constructor to initialize n and to allocate memory to member array
void fnGet()       :  to fill the member array
void fnDisplay() : to show the member matrix
matrix fnTrans(matrix A)  : to store the transpose of the argument matrix in the current object and return that.
Specify the class matrix giving the details of the above member data and methods only.

 

Program:

import java.util.*;
class matrix
{
int t[][];
int n;

public matrix(int n1)
{n=n1;
t= new int [n][n];

}
void get()
{
Scanner sc=new Scanner(System.in);
int i,j;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{
t[i][j]=sc.nextInt();
}
}
}
void disp()
{
int i,j;
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{
System.out.print(t[i][j]+”\t”);
}
System.out.println();
}
}
public matrix Trans(matrix o1)
{
int i, j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
t[i][j]=o1.t[j][i];
return this;
}

public static void main(String args[])
{
matrix m1=new matrix(3);
matrix o1=new matrix(3);
matrix o2=new matrix(3);
m1.get();
m1.disp();
o2=o2.Trans(m1);

System.out.println(“Transpose of matrix”);
o2.disp();
}
}

 

Output:

Enter the elements:
9
8
7
6
5
4
3
2
1
9 8 7
6 5 4
3 2 1
Transpose of matrix
9 6 3
8 5 2
7 4 1

Sort the array elements in ascending order


A class Collection contains an array of  100 integers. using the following class description create an array with common elements from two integer arrays.

Class name  : Collection
Data members
arr[], len
Member functions:
Collection()   : default constructor
Collection(int) : parameterized constructor to assign the length of the array
void input()    : to accept the array elements
Collection common(Collection) : returns a Collection containing the common elements of current Collection object and the Collection object passed as a parameter.
void arrange()  : sort the array element of the object containing common elements in ascending order using any sorting technique
void display()  : displays the array elements
Define the main() to call above member methods.

Program

import java.util.*;
class Collection
{
int arr[];
int len;
Collection()
{
arr=new int[10];
len=10;
}
Collection(int size)
{
arr=new int [size];
len=size;
}
public void input(){
Scanner sc=new Scanner(System.in);
int val=0;
for(int i=0;i<len;i++)
{
System.out.println(“Enter the elements “+(i+1));
val=sc.nextInt();
arr[i]=val;}
}
private void setLength(int le)
{
len=le;
}
public Collection common(Collection c2)
{
Collection c3=new Collection();
int val, k=0;
for(int i=0;i<len;++i)
{
val=arr[i];
for(int j=0;j<c2.arr.length ; ++j) {
if(val==c2.arr[j]) {
k++;
}
}
}c3.setLength(k);
return c3;
}
public void display()
{
for(int i=0;i<len;i++) {
System.out.print(arr[i]+””);
}
System.out.println();
}
public void arrange()
{
for(int i=len-1;i>=0;i–)
{int highestIndex=i;
for(int j=i;j>=0;j–)
{
if(arr[j]>arr[highestIndex])
highestIndex=j;
}
int temp=arr[i];
arr[i]=arr[highestIndex];
arr[highestIndex]=temp;
}
display();
}

public static void main(String args[])
{
Collection c1=new Collection(10);
Collection c7= new Collection();
c1.input();
System.out.println(“Display the entered matrix”);
c1.display();
System.out.println(“Ascending order”);
c1.arrange();
c7=c7.common(c1);
}
}

Output:

Enter the elementts 1
9
Enter the elements 2
8
Enter the elements 3
7
Enter the elements 4
6
Enter the elements 5
5
Enter the elements 6
4
Enter the elements 7
3
Enter the elements 8
2
Enter the elements 9
1
Enter the elements 10
10
Display the entered matrix
9 8 7 6 5 4 3 2 1 10
Ascending order
1 2 3 4 5 6 7 8 9 10

Shuffle the matrix(2D)(1st row becomes the last, 2nd row becomes the 1st & so on..) — by object


A class Shift contains a 2D array of order (m*n) where the maximum values of both m and n is 5. Design the class Shift to shuffle the matrix (the first row becomes the last, the second row becomes the first and so on.)

Class name                    :Shift
Data members
mat[][], m,n;
Member functions:
Shift(int mm, int nn) : constructor to initialize the data members m=mm and n=nn
void input()                 : enters the elements of the array
void cyclic(Shift P)    : enables the matrix of the object(P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object.
void display()            : display the matrix elements.
Define the main() to create an object and call the methods accordingly to enable the task of shifting the array elements.

Program:

import java.util.Scanner;
 public class Shift {  
     static Scanner sc=new Scanner(System.in); 
     int mat[][];      
     int m,n;   
     Shift(int mm,int nn)  
     { m=mm;     
         n=nn;   
         mat=new int[m][n];   
        }   
        void input()     
        {  System.out.println("Enter elements");  
            for(int i=0;i<m;i++)    
            for(int j=0;j<n;j++)    
            mat[i][j]=sc.nextInt();  
        }    
        void display()    
        {     
            for(int i=0;i<m;i++) 
            {  System.out.println();  
                for(int j=0;j<n;j++)  
                System.out.print(mat[i][j] +"\t");   
            }     }    
            void cyclic(Shift P)  
            {  for(int i=0;i<m;i++)     
                for(int j =0;j<n;j++)  
                {    if(i!=0)          
                    mat[i-1][j]=P.mat[i][j];   
                    else                      
                    mat[m-1][j]=P.mat[0][j];   
                }    
            }
              static void main()   
              { Shift x=new Shift(2,3);  
                  Shift y=new Shift(2,3);   
                  x.input();     
                  y.cyclic(x);  
                  System.out.println("Initial array is ");
                  x.display(); 
                   System.out.println();
                  System.out.print("Array after the shift ");
                  y.display();   
              } } 

Output: