ARRAY

Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values in memory at the fixed size. Multiple types of arrays are used in any programming language such as: one -
dimensional, two - dimensional or can say multi - dimensional.
Declaration of an array: 
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as:
int num[] = {50,20,45,82,25,63};

Ques Differentiate between subscript and subscript variable.
Ans:- A subscript variable( array) is used to store more than 1 element of data using a single name. A subscript is used to access each element of the array.

Ques 2 What do you understand by an array?
Ans:- An array is a collection of variable of the same type that are referenced by a common name. they are of two type single dimension and multi dimension.


Ques 3:- How one dimension array is different from double dimension array?
Ans:- One Dimension:- A list of fixed number of homogeneous data elements.
Double Dimension:- An array in which each element itself an array.

Ques 4:- what is meant by index of an element?
Ans:- Index: Also called subscript. The number designating its position in arrays ordering. If there is an array of size N then index number will be from 0 to N-1.

Ques 5:- What is the difference between linear and binary search?
Ans:- Linear:- Each element of the array is compared with the given item to be searched for, one by one.
Binary:- Searches for the given item in a sorted array the search segment reduces to half at every successive stage.

Ques 6 How an array can be declare?
Ans :- Array can be declared using given syntax.
Datatype array_name[]=new Datatype[size]
Ex:- int arr[]=new int[10]
It will declare an array names arr of size 10.

Ques 7:- How will you initialize one dimension array.
Ans :- Array can be declared using given syntax.
Datatype array_name[]={value1, value2,value3…….…..};
For example
int days[]={31,28,31,30,31,30,31,31,30,31    ,30,31};

note:- array can be initialized at the time of declaration otherwise we need to initialize each element separately .
Ques 8 What do you mean be arrayindexoutof Bound
Ans :- It is an Exception which occurs when we try to access any element which is beyond 0 to size-1.
Ques 9:- Define Selection Sorting.
Ans: if the array is to be arranged in ascending order, the smallest element needs to be selected and exchanged with the first position element in the array. Again, the smallest element from the remaining elements is selected and exchanged with second array. The process continues till all elements are arranged. If the array needs to be arranged in descending order. Select the largest element.
Ques 10;- Define Bubble Sort.
Ans:- The adjacent elements of the array are compared. If array needs to be arranged in ascending order and the left element(say a[0]) is greater than the right element(say a[1]) they need to be exchanged.
Ques 11 Which element is num[9] of the array num .[2005]
Ans:- num [9] will be the 10th element of the array because index of an array start from 0.

Ques 12 How much memory is requied for following array.
i.                    int a[]=new int[4];
ii.                  char ch[]=new char[20];
iii.                short m[][]=new short[4][2]
Ans:- Number of bytes required = number of element in array X size of data type.
i.                    4 X 4= 16 bytes.
ii.                  20 x 2 = 40 bytes.
iii.                4 X 2 X 2 = 16 bytes.

Ques 13. What are the advantages and disadvantages of array.
Ans:- Advantage of array:-
i.                    Since elements of the arrays are stored in contiguous memory locations the sequential access of elements is very fast.
ii.                  Random access is of elements is possible. It is not necessary to access the members sequentially.
Disadvantage of array:-
i.                    One should know the size of the array at the time of declaration.
ii.                  Once array is declared we cannot change the size of array which some times lead unnecessary reservation of memory.



POINT TO REMEMBER

1.      Data grouped together into a single unit for a specific purpose is known asdata structure.
2.      Array is a data structure where similar types of data are put together, stored in continuous locations and is referred to by a single name.
3.      Arrays occupy a group of contiguous memory locations all having the samename and type.
4.      To refer to a particular location, we specify the name of the array and itsposition number.
5.      Its position number is called anelement or a subscript or an index of the array.
6.      Subscript of an array must be aninteger.
7.      In Java the first element of an array is its zeroth element and the last element 1 less than the total elements in an array.
8.      Subscripts are enclosed withinsquare brackets next to the name of the array.
9.      To retrieve an individual array element, array name along with itssubscript should be specified.
10.  An array of smaller size can be initialised using an initializer list.
11.  Newly created array of integers is automatically filled with default values: 0for numbers, false for boolean, and nullfor objects.
12.  Searching and sorting are two basic array-processing techniques that are frequently used.
13.  Sorting refers to rearranging the data of an array in some particular order increasing or decreasing.
14.  Searching refers to finding an item in an array, depending on some specific criterion.
15.  Linear searching is the simplest searching method and is done when the required element is searched sequentially in an array.
16.  Binary searching is a faster way as it eliminates one half part every time while the search is carried on.


Program 1:- to find sum of five numbers.
public class ArrayAverage{
public static void main(String[] args) {
double nums[]={1.0,2.3,3.4,4.5,40.5};
double result=0.0;
int i=0;
for(i=0; i < nums.length; i++){
result=result + nums[i];
}
System.out.println("Average is =" + result/nums.length);
}
}

Program 2- to search a number in  an array using lenear search.
import java.util.*;

class lsearch
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int arr[]={35,34,67,87,45,33,11,91,2,44,32};
int n,len,flag,i;
System.out.println( “enter a number”);
n=Sn.nextInt();
flag=0;
len=arr.length;
for(i=0;i<len;i++)
{
if(arr[i]==n)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println( n+”found at index ”+i);
else
System.out.println( n+”is not in list”);
}
}

Program 3- To search a number in  an array using binary search.
import java.util.*;
class lsearch
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int a[]={34,45,56,67,78,89,90,101,234,345};
int start,end,mid, n,len,flag;
System.out.println( “enter a number”);
n=Sn.nextInt();
flag=0;
len=a.length;
start=0;
end=len-1;
while(start<=end)
{
   mid=(start+end)/2;
   if(n==a[mid])
   {
            flag=1;
            break;
   }
    else if(n<a[mid])
            end=mid-1;
    else
     start=mid+1;
}
if(flag==1)
System.out.println( n+”found at index ”+mid);
else
System.out.println( n+”is not in list”);
}
}

Program 4- To sort numbers in ascending order using bubble sort technique[2005]
import java.util.*;
public class bubbleSort{
public static void main(String a[]) throws Exception
{
int i,j,n;
int a[] = {12,9,4,99,120,1,3,10};
System.out.println("Values Before the sort:\n");
for(i = 0; i < a.length; i++)
System.out.print( a[i]+" ");
System.out.println();
n=a.length;
for(i = 1; i < n; i++)
{
for(j = 0; j < (n-i); j++)
{
if(a[j] > a[j+1]){
t = a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.print("Values after the sort:\n");
for(i = 0; i <a.length; i++)
System.out.print(a[i]+" ");
}
}
 
Program 5- To sort numbers in ascending order using selection sort technique [2006]
import java.util.*;
public class selectionSort{
public static void main(String a[]) throws Exception
{
int i,j;
int a[] = {12,9,4,99,120,1,3,10};
System.out.println("Values Before the sort:\n");
for(i = 0; i < a.length; i++)
System.out.print( a[i]+" ");
System.out.println();
n=a.length;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[i] > a[j]){
t = a[j];
a[j]=a[i];
a[i]=t;
}
}
}
System.out.print("Values after the sort:\n");
for(i = 0; i <a.length; i++)
System.out.print(a[i]+" ");
}
}
Program 6- to sort numbers in ascending order using Exchange selection sort technique[ important]
import java.util.*;
public class exchange{
public static void main(String a[]) throws Exception
{
int i,j, pos,min;
int a[] = {12,9,4,99,120,1,3,10};
System.out.println("Values Before the sort:\n");
for(i = 0; i < a.length; i++)
System.out.print( a[i]+" ");
System.out.println();
n=a.length;
for(i = 0; i < n; i++)
{
min=a[i];
pos=i;
for(j = i+1; j < n; j++)
{
if( a[j]<min)
{
min=a[j];
pos=j
}
}
t = a[j];
a[j]=a[pos];
a[pos]=t;
}
}
}
System.out.print("Values after the sort:\n");
for(i = 0; i <a.length; i++)
System.out.print(a[i]+" ");
}
}

Program 7- Write a menu driven program to find sum of prime numbers or find smallest and largest number or array.
import java.util.*;
class array_menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
int arr[]={35,34,67,87,45,33,11,91,2,44,32};

int len,i,choice, max,min,j,ctr,sum;
choice=1;
len=arr.length;
while(choice!=0)
{
System.out.println( “1 . sum of prime”);
System.out.println( “2. smallest and largest ”);
System.out.println( “0. exit”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(ch)
{
case 1: sum=0;
            for(i=0;i<len;i++)
            {
            ctr=0;
            for(j=1;j<arr[i];j++)
            {
             if(arr[i]%j==0)
                        ctr++;
            }
            if(ctr==1)
            sum=sum+arr[i];
        }
System.out.println( “sum of   prime”+sum);
break
case 2: min=arr[0];
            max=arr[0];
            for(i=1;i<len;i++)
            {
            if(arr[i]>min)
            min=arr[i];
            if(arr[i]>max)
            max=arr[i];
            }
System.out.println( “highest number”+max);
System.out.println( “smallest number”+min);
break;
case 0 : break;
default : System.out.println( “invalid option”);
               break;
}
}
}
}

Program 8- Write a program to store number in a matrix and make is intractive to find
  1. row wise sum
  2. column wise sum
  3. diagonals sum
  4. border elements sum
import java.util.*;
class matrix_menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));

int mat[]={      {35,34,67,87},
{45,33,11,91},
{65,2,44,32},
{56,78,45,33}};
int i,j,rtot,ctot,ld,rd,bd,choice, ;
choice=1;
while(choice!=0)
{
System.out.println( “1 . row wise sum”);
System.out.println( “2. column wise sum ”);
System.out.println( “3. diagonal sum”);
System.out.println( “4. border sum”);
System.out.println( “enter your choice”);
choice =Sn.nextInt();
switch(ch)
{
case 1: for(i=0;i<4;i++)
              {
                        rtot=0;
              for(j=0;j<4;j++)
            {
              rtot=rtot+mat[i][j];
            }
       System.out.println( “sum of row “+(i+1)      +”is”+rtot);
            }
            break;
case 2:  for(j=0;j<4;j++)
              {
                        ctot=0;
            for(i=0;i<4;i++)
            {
              ctot=ctot+mat[i][j];
            }
       System.out.println( “sum of column “+(j+1)      +”is”+ctot);
            }
            break;
case 3:  ld=0;
             rd=0;
            for(i=0,j=3,i<4;i++,j++)
            {
            ld=ld+mat[i][i];
            rd=rd+mat[i][j];
            }
System.out.println( “sum of left  diagonal  “+ld);
System.out.println( “sum of right diagonal“+rd);
break;
case 4 :   bd=0;
for(i=0;i<4;i++)
              {
                          for(j=0;j<4;j++)
            {
             if(i==0 || j==0 || i==3 || j==3)
bd=bd+mat[i][j];
            }}
System.out.println(“sum of border elements”+bd);
            break;
case 0 : break;
default : System.out.println( “invalid option”);
            break;
}
}
}
}
Prog 9 Write a program to input a month number and display month name and number of days in that month.
import java.util.*;
class matrix_menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
String mon[]={“ “, “January”,”Feburary”, ”March”, ”April” , ”may” , ”June”, “July”, ”August”, ”September” ,”October” , ”November” , December”};
int day[]={0,31,28,31,30,31,30,31,31,30,  31,30,31};
int n;
System.out.println(“enter month number”);
n=Sn.nextInt();
if(n>=1 && n<=12)
{
System.out.println(mon[n]+”  “+day[n]);
}
else
{
System.out.println(“invalid month number”);
}
}
}

Program 9 The marks obtained by 50 students in a subject are tabulated as follows
Name                          Marks
---                                ---
---                                ---
Write a program to input the names and marks of the students in the subject.
Calculate and display;-
i.                    The subject average marks( Subject average marks= subject total/50)
ii.                  The highest marks in the subject and the name of the student
The maximum marks in the subject are 100.                      [2006]
import java.util.*;
class menu
{
public static void main(String args[]) throws Exception
{
Scanner Sn=new Scanner(System.in));
String name[]=new String[50];
int marks[]=new int[50];
int i,high,pos,tot;
for(i=0;i<50;i++)
{
System.out.println(“enter name and marks”);
name[i]=Sn.nextLine();
marks[i]=Sn.nextInt();
}
high=mark[0];
pos=0;
tot=0;
for(i=0;i<50;i++)
{
if(mark[i]>high)
{
high=marks[i];
pos=i;
}

tot=tot+marks[i];
}
System.out.println(“Average marks of the student”+(tot/50));
System.out.println(“Highest mark is ”+high+” highest scores is “+name[pos]);
}
}


SHORT ANSWER QUESTION

1)      Define an array.
2)      Differentiate between data type and data structure.
3)      Name four major operations on linear data structures.
4)      What are the preconditions for Binary search to be performed on a single dimensional array?
5)      State condition(s) which binary search is applicable.
6)      Explain the bubble sorting technique in array with an example.               
7)      What is difference between single dimensional array and multidimensional array                   
8)      What is sorting?
      9) What are the advantages of using an array

Q10. Write the output of following program segments-                                                   

(a)            int a[ ]={17,10,9,18,7};
            a[4]=++a[3];    a[4]=a[1]-a[2]++;
            System.out.print(a[4]+”  “+a[3]);

(b)       int a[ ]={1,2,3,4,5,6};
for(i=0;i<5;i++)
{
            a[i]=a[i+1]+a[i];
            a[i+1]=a[i]-a[i+1];
            a[i]=a[i]-a[i+1];
}
for(i=0;i<6;i++)
{
System.out.print(a[i]);
}
c) int a[]=new int[6];
a[0]=2;
a[1]=3;
for(i=2;i<6;i++)
{
a[i]=a[i-1]+a[i-2];
}
for(i=0;i<6;i++)
System.out.println( (a[i]);

  1. int a[]={3,10,15,20,25};
int I,j,k=1,m;
            i=--a[0];
            j=a[2]++;
            m=a[++i];
System.out.println( i+j+m);
f)     int a[]=new int[5];
int I;
       for(i=0;i<<5;i++)
      a[i]=3*i;
      for(i=0;i<5;i++)
     System.out.println( a[i]);
a)      char ch[][]=new int[6][6];
       int I,j;
for( i=0;i<6;i++)
   for(j=0;j<6;j++)
      {
If(i==j || i+j==5)
  ch[i][j]==’*’;
else
  ch[i][j]=’ ‘;
}
for( i=0;i<6;i++)
   for(j=0;j<6;j++)
        System.out.print( ch[i][j])
   System.out.println( );
H)    int i,j,c=2;
int a[]={1,1,1}, b[]={2,3,4};
for(i=0;i<=2;i++)
  {
  J=a[i]+b[c];
c--;
System.out.println( j*j);
}

I)       int I,j,a[][]=new int[3][2];
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
a[i][j]=i*j+2;
}
}
System.out.println( a[1][1]+”\t”+a[0][1]+ ”\t” +a[2][0]+”\t”+a[2][1]);
j) int a[]=new int[10]l
   for(int i=0;i<=9;i+=2)
    a[i]=2*i
  for(i=9;i>=0;i--)
System.out.println( a[i]);
k) int a[][]={{ 7,3,5},{2,5,4},{3,6,2}};
int i,j,s;
for(i=0;i<3;i++)
{
for(j=0j<2;j++)
{
If (a[j][j]>a[j+1][j+1])
      s=a[j][j];
      a[j][j]=a[j+1][j+1];
      a[j+1][j+1=s;
}  }  }
for(i=0;i<3;i++)
{
for(j=0j<3;j++)
{
System.out.println( a[i][j]+”  “);
}
System.out.println( );
}
L) int y[]={1999,2000,1996,1947};
 for(i=0;i<4;i++)
 {
            if(y[i]%4==0)
            System.out.println(y[i]);
}
M) int h[][]={{1,2,3},{5,6,7},{8,9,4}};
for(i=0;i<3;i++)
{
 for(j=0;j<3;j++)
  {
    if(i==j || i+j==2)
      System.out.print(h[i][j]+”\t”);
    else
      System.out.print(“\t’);
  }
}
O) int h[][]={{1,2,3},{5,6,7},{8,9,4}};
for(i=2;i>=0;i--)
{
 for(j=2;j>=0;j--)
   {
            System.out.print(h[i][j]+”\t”);
  }
   System.out.println();
}
A)    if array[]={1,9,8,5,2};             [2008]
 i What is array.length ?
 ii. What is array[2]?
Ans      i.) 5      ii.) 8



 Ques 11:- How much memory following arrayes will occupy?
a)      int a[]=new int[5];
b)      short x[]=new short[20];
c)      double d[]={34.56,67.44,6.0};
d)     char ch[][]=new char[4][5];





PROGRAM FOR PRACTICE
1.                  WAP to open an array and store 20 numbers in it. Print those numbers which are even as well as divisible by 5.Also print their locations.

2.)WAP to enter 11 names of the cricketers  & their countries  in  two arrays . Then Enter the names of a country of your choice and print all those names of cricketers Who belong to that country. Repeat the process according to the users choice.

3) WAP to open two arrays and store 10 numbers in each. Store their sum in array S And product in another array P. Print array S and  P.

4) WAP to enter any 20  numbers in an array. Print  the largest and the smallest numbers Along with their  locations.

5) Write a program to create a single dimension array to input 10 integers. Print array elements in a single line. Alsoe print sum of those elements which are divisible by 4.
6) A company produces the different products A1 and A2  …………….. A10 with P1, P2 ………………..P10 as per prices per unit and Q1,Q2,…………….Q10 as the the quantities
Produced respectively.
(i)  Store the data in 10 * 20 matrix as follows :

COST/UNIT(RS)
QUANTITY

P1
Q1
P2
Q2
:
:
:
:
P10
Q10
7.) Wap to accept 10 integer from a user in a single dimension array and sort the array using bubble sort.

8) Wap to accept 10 integer from a user in a single dimension array and sort the array using Selection  sort.

9) Write a program to create three single dimensional arrays empcode[](integer), sal[](double), spl[](double) to store employee code, monthly salary and special allowance of 10 employees. Calculate the total monthly salary (sal+spl) and annual salary of each employee of each employees. Print the salary details in tabular form including all the data. At the end print total of monthly salary and total of allowances.

12) Design a function void showtax(double tax[]). The function takes single subscripted variable tax[] as function argument with income tax amount of 8 salarid persons. Print average tax of all the persons along with maximum and minimum tax amount paid by the persons,

13) Write a program to initialize the following integer arrays. Print a suitable message whether the two array are identical or not. Make use of Boolean data type to decide whether the two arrays are same or not.
Ar[]={146,236,346,456} and Br={146,236,346,456}

14) wap to dispay the frequency of each element of an array of n integer

15) Wap to display frequency table from an array marks[] which hold marks of 100 students
ranges are as given 0-10,11-20,21-30…..91-100

16.) Wap to input date in dd,mm,yy and display corresponding date of the year. Eg 21-7-2004
            process:- 31+29+31+30+31+30+21=203
            output 203
17) Write a program to input a single dimension array ar[] of 10 integer elements store only single digit integers in another array br[]. Print array ar[] and br[] in two different lines.

18) Write a program to inititalize the given temperatures in an array. Find the minimum and maximum temperatures along with the average of all the temperatures.
Temperatures: 23.4, 44.5,12.5,28.7,34.5,6.7
Output: Minimum Temperature:- 6.7
 Maximum Temperature: 44.5
 Average Temperature:- XXX

19) Define a function void findmarks(float m[]). The function takes single subscripted variable m[] as function argument with marks of 10 students.Print average of 10 students along with highest and lowest marks scored by the student with suitable message.
20) Wap to reverse the array without using another array.

21) Wap to search for a number in an array using binary search.

22) wap to store numebr in a single dimension array and store them even number in array e[] and odd numbers in array o[].

23) Wap to input decimal number and convert it into binary equivalent.

24) Write a program to input numbers in two array A[] and array B[] of size m and n. create another array C[] that contains common elements of both array A[] and B[].

25) WAP to store 20 numbers in a 1D array and count the sum of all numbers and the sum of all evrn numbers of two digits, which are exactly divisible by 7.

26) WAP to store 10 alphabets in a 1D array X and copy all small letters in array Y and capital letters in array Z.

27) WAP to store numbers in array A and sort it in ascending or descending order according to user choice.
28) WAP to store n small alphabets in an array. If the user enters it in capital then store them in the array after converting them in small. And sort them in descending order using selection sort.

29) WAP to store n numbers in an array and copy all prime numbers in array PRIME and perfect numbers in array PERFECT.

30) Write a program to read a set of N values from a user and store it in a one dimensional array. Compute and display AM standard Deviation(SD) and Variance(var) for the N values. N is a user input.
31) Write a program to read a set of N arbitrary integer values from a user and store it in a single dimensional array. Check whether the number is prime or composite while displaying the array of numbers. N is a user defined constant.

32) Write a program to input n numbers in an array and sort  them using selection sort technique in descending order. Input a number n and search for the number in the array using binary search technique.

33) Write a program to input n number in an array display frequency for each number. As well as display mode. Mode is the number which occurs most frequently in the array.

34)Write a program to input name and marks of 3 subjects of 50 students. Perform the given
process.
 Display name and grade of students in tabular form. Where grade is assigned as per given rule
For percentage >=75 grade ‘A’, for percentage between 60 to 75 grade ‘B’, for percentage between 40 to 59 grade ‘C’, for percentage below 40 grade ‘D’.
Display the name of the student who scored highest percentage

35) Write a program to initialize an array of 5 names and initialize another array with their respective telephone numbers. Search for a name input by the user, in the list. If found, display “Search Successful” and print the name along with the telephone number, otherwise display “Search unsuccessful. Name not listed”.

36. WAP to input marks out of 100 of 100 students. Now form four arrays first[ ], second[ ],
third[ ]   and fourth[ ]. Now transfer the marks in given arrays depending upon following condition.
MARKS                      ARRAY
Above 59                    First
Between 45 and 59     Second
Between 33 and 44     Third

Below 33                     Fourth

No comments:

Post a Comment

any problem in any program comment:-

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...