Blog
Java Program
Arrays
Arrays are use to store same type data in consecutive memory.
Ques 1: Write a program to multiply two 3*3 matrices and display the result.
Ans
class Matrix{
public static void main(String args[]){
int[][] mat1=new int[3][3];
int[][] mat2=new int[3][3];
int[][] ans=new int[3][3];
System.out.println(“Enter the first matrix”);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
mat1[i][j]=Integer.parseInt(System.console().readLine());
}
}
System.out.println(“Enter the second matrix”);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
mat2[i][j]=Integer.parseInt(System.console().readLine());
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
ans[i][j]=0;
for(int k=0;k<3;k++){
ans[i][j]=ans[i][j]+(mat1[i][j]*mat2[k][j]);
}
}
}
for(int i=0;i<3;i++){
System.out.println();
for(int j=0;j<3;j++){
System.out.print(ans[i][j]+“\t”);
}
}
}
}
Ques 2: Write an application to simulate the rolling of one dice 1000 times. The program should print the number of times each frequency of occurrence of each face. Implement this using a
- Switch statement using separate counters
- An array
Ans
class Dice{
public static void main(String args[]){
int i;
int c1=0,c2=0,c3=0,c4=0,c5=0,c6=0;
for(i=0;i<10;i++)
{
int rnd=(int)(Math.random()*6+1);
switch(rnd)
{
case 1:c1++;
break;
case 2:c2++;
break;
case 3:c3++;
break;
case 4:c4++;
break;
case 5:c5++;
break;
case 6:c6++;
break;
}
}
System.out.println(“the 1 will appear “+c1 +“times”);
System.out.println(“the 2 will appear “+c2 +“times”);
System.out.println(“the 3 will appear “+c3 +“times”);
System.out.println(“the 4 will appear “+c4 +“times”);
System.out.println(“the 5 will appear “+c5 +“times”);
System.out.println(“the 6 will appear “+c6 +“times”);
}
}
Ques 3: Write a program to search a given number from a set of numbers.
Ans
class Search{
public static void main(String args[]){
int[] arr={1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,2526,27,28,29,30};
System.out.println(“Enter the number to be searched “);
int n=Integer.parseInt(System.console().readLine());
boolean flag=false;
int i;
for(i=0;i<arr.length;i++){
if(n==arr[i]){
flag=true;
break;
}
}
if(flag){
System.out.println(n+” is found at index “+i);
}else{
System.out.println(n+” Not found”);
}
}
}
Ques 4: Write a program that reads a sequence of integers into an array and that computes the alternating sum of elements in the array. For example, if the input data is 1 3 5 7 9 then it computes 1+5+9=15
Ans
class Array{
public static void main(String args[]){
int a,b[],sum=0,i,j;
b=new int[20];
System.out.println(“enter the size of the array”);
a=Integer.parseInt(System.console().readLine());
System.out.println(“enter the elements of the array”);
for(i=1;i<=a;i++)
{
b[i]=Integer.parseInt(System.console().readLine());
}
for(j=1;j<=a;j++)
{
if(j%2!=0)
{
sum=sum+b[j];
}
}
System.out.println(“sum is “ +sum);
}
}