0% found this document useful (0 votes)
40 views26 pages

Understanding Single Dimensional Arrays

Uploaded by

saptarshi1421
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views26 pages

Understanding Single Dimensional Arrays

Uploaded by

saptarshi1421
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Arrays

An array is a collection of items or values of same data type that are referred by one name. An array
creates continuous memory locations to store actual values of variables. Each memory location of array
stores only one value. The value store in the memory location is known as element of array

Types of Array:
1. Single Dimensional Array
2. Double Dimensional Array

The array which creates continuous memory locations/indexes upto a finite limit to store data
items is known as single dimensional array.

Syntax:

datatype arrayname/variable [ ] = new datatype [size of array];

OR
datatype[ ] arrayname/variable = new datatype [size of array];

int arr[]=new int[5]; //declaration of array

The “size of array” means number of memory locations to be created and the memory location is
also known as index or array index or indecies or subscript.

To declare a single dimensional array:


int x[ ]= new int [5];
OR
int [ ] x = new int [5];
OR
int x[ ];
x= new int [5];

0 1 2 3 4 These are the memory locations/indexes

x 20 30 40 50 These are the elements of array 10


Array name
x[0] x[1] x[2] x[3] x[4]
Q1) Write a program to initialize a single dimensional array of 5 integers. Print the array elements.

Q2) WAP to create a single dimensional array to accept 5 names. Print the names after converting the
names to UpperCase.
Ans:
import [Link].*;
class a2
{
static void main()
{
String str[]=new String[5];
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 String elements=");
for(int i=0;i<5;i++)
{
str[i]=[Link]().toUpperCase();// accepting the string and converting to uppercase
}
[Link]("Uppercase Elements=");
for(int i=0;i<5;i++)
{
[Link](str[i]);
}
}
}

Q3) WAP to initialize a single dimensional array 0f 8 integers. Print array elements along with the
indexes of each element and square of each element in three columns
Index Position Element Square
xxx xxxx xxx

Q4) WAP to create a single dimensional array to accept 10 integers. Print array element in a single line
with one space between them. Also print sum of elements present at even indexes and sum of elements
present at odd indexes in array.
Ans:
import [Link].*;
class a4
{
static void main()
{
int arr[]=new int[5];
int sum_e=0, sum_o=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 elements:");
for(int i=0;i<5;i++)
{
arr[i]=[Link]();
}

for(int i=0;i<5;i++)
{
[Link](arr[i]+"\t");
}
for(int i=0;i<5;i++)
{
if(i%2==0)
sum_e=sum_e+arr[i];
else
sum_o=sum_o+arr[i];

}
[Link]("\nSum of even elements="+sum_e);
[Link]("Sum of odd elements="+sum_o);
}
}

Q5_a) WAP to create a single dimensional array a[] and n as size of the array. Calculate sum of single
digit and sum of double digit elements only from the array.
Ans:
import [Link].*;
class a5_a
{
static void main()
{

int s1=0,s2=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter size:");
int n=[Link]();
int arr[]=new int[n];
[Link]("Enter "+n+" elements:");
for(int i=0;i<n;i++)
{
arr[i]=[Link]();
}

for(int i=0;i<n;i++)
{
if(arr[i]>=0 && arr[i]<=9)
s1=s1+arr[i];
else if(arr[i]>9 && arr[i]<=99)
s2=s2+arr[i];

}
[Link]("Sum of single digit elements="+s1);
[Link]("Sum of double digit elements="+s2);
}
}
Q5_b) WAP to create a single dimensional array a[] and n as size of array. The array a[] should store
only single and double digit numbers. If a number more than 2-digit is stored in the array then the
program execution should stop there it self by displaying an appropriate message. Calculate sum of
single digit and sum of double digit elements only from the array.
Ans:
import [Link].*;
class a5_b
{
static void main()
{

int s1=0,s2=0;
int cnt=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter size:");
int n=[Link]();
int arr[]=new int[n];
[Link]("Enter "+n+" elements:");
for(int i=0;i<n;i++)
{
int no=[Link]();
if(no>=100)
{
[Link]("You enter a 3-digit number");
[Link]("Execution Stopped!!");
cnt++;
break;
}
else
{
arr[i]=no;
if(arr[i]>=0 && arr[i]<=9)
s1=s1+arr[i];
else if(arr[i]>9 && arr[i]<=99)
s2=s2+arr[i];
}

}
if(cnt==0)
{
[Link]("Sum of single digit elements="+s1);
[Link]("Sum of double digit elements="+s2);
}
}
}
Q6) WAP to input a decimal number. Find the binary equivalent of the number. Print the number along
with its binary form.
Eg:
Enter number: 12
Binary number: 1100

Q R
12%2 6 0
6%2 3 0
3%2 1 1
1%2 0 1
Ans:
class a6
{
static void main(int num)
{
int bin[]=new int[50];
int c=0;
int temp=num;
while(num>0)
{
int d=num%2;
bin[c]=d;
c++;
num=num/2;

}
[Link]("Binary equivalent=");
for(int i=c-1;i>=0;i--)
{
[Link](bin[i]);
}

}
}

Q7) WAP to input 3 single dimensional arrays cod[], price[], qty[] to store product code, unit price and
quantity of 5 products. It is required to calculate the total cost of each product and print the result in
tabular form including product code, unit price, quantity and total cost of each. At the end calculate
total price, total quantity and total cost.
code price qty total
XX XX XXX XXX
…..
…..
Sum total price=XXX
Total Qty=XXX
Total cost=XXX
Q8) a)WAP to create a single dimensional array to accept 5 names. Check and print only those name
from the array which starts with capital letter and print number of names starting with capital.
Ans:
import [Link].*;
class a8
{
static void main()
{
String str[]=new String[5];
int cnt=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 names:");
for(int i=0;i<5;i++)
{
str[i]=[Link]();
}
[Link]("Capital Letter words:");
for(int i=0;i<5;i++)
{
char ch=str[i].charAt(0);
if([Link](ch))
{
cnt++;
[Link](str[i]);
}
}
[Link]("No of words starting with capital="+cnt);
}
}

Q8) b) WAP to create a single dimensional array to accept 5 names. Convert the first letter of each
element to Uppercase and reprint the new array list.
Ans:
import [Link].*;
class a8_b
{
static void main()
{
String str1[]=new String[5];
String str2[]=new String[5];
int cnt=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 names:");
for(int i=0;i<5;i++)
{
str1[i]=[Link]();
}

for(int i=0;i<5;i++)
{
String s=str1[i];
char ch=[Link]([Link](0));
String ans=ch+[Link](1);
str2[i]=ans;
}

for(int i=0;i<5;i++)
{
[Link](str2[i]);
}
}
}

Q9) Design a function void findMarks(double 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.
Ans:
import [Link].*;
class a9
{
static void findMarks(double M[])
{
int len=[Link];
double sum=0;
double min=M[0],max=M[0];
for(int i=0;i<len;i++)
{
sum=sum+M[i];
}
double avg=sum/len;
for(int i=0;i<len;i++)
{
if(M[i]<min)
min=M[i];
if(M[i]>max)
max=M[i];
}
[Link](("Average="+avg);
[Link] ("Min="+min);
[Link] ("Max="+max);
}
}
Q10) WAP to store average marks of 40 students in single subscripted variable and print number of
students falling in the following categories in two columns: (HW)
Average Marks Number of students
1-30 xx
31-50 xx
51-70 xx
71-85 xx
86-100 xx

Q11) WAP to create a single dimensional array of n integers. Print only those elements from the array
which are Armstrong numbers.
Eg: 153,370,371,407

153>> 13 + 53 +33 =153

Q) WAP to create a single dimensional array of n integers. Print only those elements from the array
which are Palindrome numbers. Also print number of Palindrome elements found.

Q12) Write a function int printSum(int arr[ ]) to find and return the sum of only even numbers from the
array arr[ ] passed as argument. Write a main function to initialize a single dimensional array of 10
integers and by calling printSum() display sum of even numbers.

Q13) WAP to accept the end limit from the user and depending on it make an integer array to accept
values and print only those elements from the array which are palindrome numbers.
Create the following functions:
1. void palin(int p[]): to find and print palindrome numbers.
2. void main(): to accept all elements in the array and call the function palin() to print the palindrome
numbers.

Q) WAP to accept an array of 5 integer values. Print all even values of the arrays. Print sum of even
values as well.

Q) WAP to accept an array of 10 integer values. Print all the positive values entered in the array, also
count and print all positive and negative elements
Q) Define a class to declare an array of size 10 of int datatype, accept the elements into the array and
perform the following:
• Create a new array to store only the numbers which are divisible by 3 and 5 from the array.
• Display the original and the new array elements.
Sample input:
3 15 45 90 6 34 12 11 60 120
Sample Output:
Original Array: 3 15 45 90 6 34 12 11 60 120
New Array: 15 45 90 60 120
Ans:
import [Link].*;
class prelim2_Q2
{
static void main()

{
int a[]=new int[10];
int c=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter 10 elements:");
for(int i=0;i<10;i++)
{
a[i]=[Link]();
if(a[i]%3==0 && a[i]%5==0)
c++;
}
int b[]=new int[c];
int pos=0;
for(int i=0;i<10;i++)
{
if(a[i]%3==0 && a[i]%5==0)
{
b[pos]=a[i];
pos++;
}
}
[Link]("Original Array:");
for(int i=0;i<10;i++)
{
[Link](a[i]+"\t");
}
[Link]("\nNew Array:");
for(int i=0;i<pos;i++)
{
[Link](b[i]+"\t");
}
}
}
Q) Define a class to declare a character array of size 10, accept the character into the array and perform
the following:
• Display all the uppercase letters in the array and count.
• Display all the special characters in the array and its count.
Sample input:
Enter elements: a B c D e * / # f M
Sample output:
Uppercase: B D M
Uppercase count: 3
Special character: * / #
Special character count: 3
Ans:
import [Link].*;
class prelim2_Q4
{
static void main()
{
char ch[]=new char[10];
int c1=0,c2=0;
Scanner sc=new Scanner([Link]);
[Link]("Enter 10 elements:");
for(int i=0;i<10;i++)
{
ch[i]=[Link]().charAt(0);
}
[Link]("Uppercase:");
for(int i=0;i<10;i++)
{
if([Link](ch[i]))
{
[Link](ch[i]+"\t");
c1++;
}
}
[Link]("\nUppercase count:"+c1);
for(int i=0;i<10;i++)
{
if(![Link](ch[i]))
{
[Link](ch[i]+"\t");
c2++;
}
}
[Link]("\nSpecial characters count:"+c2);
}
}

Sorting
The method of arranging elements of an array in ascending order or in descending order is known as
sorting.
Types:
1. Selection sort
2. bubble sort
3. insertion sort
4. Merge sort
5. quick sort
6. shell sort

Bubble Sort:
Def: Two adjacent elements are compared each time and if they are not at their proper places/indexes,
the elements are exchanged/swapped to place them at the actual indexes. This process goes for all the
array and finally the array will be in sorted form.

i=0 j=0-4
11 6 4 23 2

6 11 4 23 2

6 4 11 23 2

6 4 11 23 2

6 4 11 2 23

i=1
j=0-4

4 6 2 23
11

4 6 11 2 23

4 6 2 11 23

4 6 2 11 23
i=2

4 6 2 11 23

4 2 6 11 23

4 2 6 11 23

4 2 6 11 23

i=3 j=0

2 4 6 11 23

2 4 6 11 23

2 4 6 11 23

2 4 6 11 23

Q1) WAP to initialize a single dimensional array of 5 elements. Arrange the array in ascending order
using bubble sort method. Print the elements before and after sorting.
Ans: (Program to initialize array elements and then sorting)
//Bubble sorting for integer values only
class bubble1
{
static void main()

{
int arr[]={90,4,8,1,10};
int len=[Link]; //5
int temp;
[Link]("Printing Array elements before sorting");
for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}

[Link]("\nPrinting Array elements after sorting");


for(int i=0;i<len;i++)
{
for(int j=0;j<len-1;j++)
{
if(arr[j]>arr[j+1]) //ascending order
{
temp=arr[j]; //swapping elements
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}
}
}

Note:
> (greater than) symbol will be used for ascending order.
< (less than) symbol will be used for descending order.

(Program to accept 10 values from the user and then sorting in descending order)
Ans:
//Bubble sorting for integer values only
class bubble1
{
static void main()

{
int arr[]=new int[10];

int temp;

for(int i=0;i<10;i++)
{
arr[i]=[Link]();
}

[Link]("\nPrinting Array elements after sorting");


for(int i=0;i<10;i++)
{
for(int j=0;j<10-1;j++)
{
if(arr[j]<arr[j+1]) //descending order
{
temp=arr[j]; //swapping elements
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

for(int i=0;i<10;i++)
{
[Link](arr[i]+"\t");
}
}
}

(Program to accept array elements in method call and then sorting it in ascending order)
//Bubble sorting for integer values only
class bubble1
{
static void main(int arr[])

int len=[Link];
int temp;
[Link]("Printing Array elements before sorting");
for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}

[Link]("\nPrinting Array elements after sorting");


for(int i=0;i<len;i++)
{
for(int j=0;j<len-1;j++)
{
if(arr[j]>arr[j+1]) //ascending order
{
temp=arr[j]; //swapping elements
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}

for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}
}
}

Q1) WAP to accept a single dimensional array of 7 character elements. Arrange the array in ascending
order using bubble sort method. Print the elements before and after sorting.
Ans:
//character sorting in ascending order
import [Link].*;
class sort3
{
static void main()
{
Scanner sc=new Scanner([Link]);
char temp;
char arr[]=new char[7];

for(int i=0;i<7;i++)
{
arr[i]=[Link]().charAt(0);
}
[Link]("Array before sorting");
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
[Link]("\nArray sorted");
for(int i=0;i<7;i++)
{
for(int j=0;j<7-1;j++)

{
if((int)arr[j]>(int)(arr[j+1])) //ascending order
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
}
}

//character sorting in descending order


import [Link].*;
class sort3
{
static void main()
{
Scanner sc=new Scanner([Link]);
char temp;
char arr[]=new char[7];

for(int i=0;i<7;i++)
{
arr[i]=[Link]().charAt(0);
}
[Link]("Array before sorting");
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
[Link]("\nArray sorted");
for(int i=0;i<7;i++)
{
for(int j=0;j<7-1;j++)

{
if((int)arr[j]<(int)(arr[j+1])) //descending order
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
}
}

//initialize 5 character and sort them in ascending order

//character sorting in ascending order


import [Link].*;
class sort3
{
static void main()
{

char temp;
char arr[]={‘z’,’b’,’p’,’a’,’e’};
int len=[Link];

for(int i=0;i<len;i++)
{
arr[i]=[Link]().charAt(0);
}
[Link]("Array before sorting");
for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}
[Link]("\nArray sorted");
for(int i=0;i<len;i++)
{
for(int j=0;j<len-1;j++)

{
if((int)arr[j]>(int)(arr[j+1])) //ascending order
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int i=0;i<len;i++)
{
[Link](arr[i]+"\t");
}
}
}

//String sorting in ascending order


//accept 7 elements from the user and sort in descending order
import [Link].*;
class sort2
{
static void main()
{
Scanner sc=new Scanner([Link]);
String temp;
String arr[]=new String[7];

for(int i=0;i<7;i++)
{
arr[i]=[Link]();
}
[Link]("Array before sorting");
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
[Link]("\nArray sorted");
for(int i=0;i<7;i++)
{
for(int j=0;j<7-1;j++)

{
if(arr[j].compareTo(arr[j+1])<0) //descending order
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
}
}

//String sorting in ascending order


//accept 7 elements from the user and sort in ascending order
import [Link].*;
class sort2
{
static void main()
{
Scanner sc=new Scanner([Link]);
String temp;
String arr[]=new String[7];

for(int i=0;i<7;i++)
{
arr[i]=[Link]();
}
[Link]("Array before sorting");
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
[Link]("\nArray sorted");
for(int i=0;i<7;i++)
{
for(int j=0;j<7-1;j++)

{
if(arr[j].compareTo(arr[j+1])>0) //ascending order
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(int i=0;i<7;i++)
{
[Link](arr[i]+"\t");
}
}
}

Q2) WAP to make two single dimensional array age[] and name[] to store 10 elements in it. Arrange the
element in ascending order of their age. Print name and their corresponding age after sorting in a
tabular format.
Ans: import [Link].*;
class sorting_Q1
{
static void main()

{
Scanner sc=new Scanner([Link]);
int age[]=new int[10];
String nm[]=new String[10];
int temp1;
String temp2;
int pos=0;
[Link]("Enter 10 vales:");
for(int i=0;i<10;i++)
{
[Link]("Enter "+(i+1)+" name:");
nm[i]=[Link]();
[Link]("Enter "+(i+1)+" age:");
age[i]=[Link]();
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5-1;j++)

{
if(age[j]>(age[j+1])) //ascending order
{

temp1=age[j];
age[j]=age[j+1];
age[j+1]=temp1;

temp2=nm[j];
nm[j]=nm[j+1];
nm[j+1]=temp2;

}
}
}
[Link](“Name \t Age”);
for(int i=0;i<5;i++)
{
[Link](nm[i]+"\t\t"+age[i]);
}

}
}
Searching
The process of finding an element from either in an ordered or unordered list or data or array is known
as searching.
Types:
1. Linear Searching
2. Binary Searching

Linear Searching

Def: The method of searching any desired element from an array by comparing each element in
consecutive sequence one by one is known as linear search or sequential search.

15 2 30 35 40
Element to be searched: 30
Output: Element present
Position: 2
Place: 3

Element to be searched: 50
Output: Element not found.

Q1) WAP to initialize a single dimensional array X[] of 10 integer elements. Input another integer num.
Search num from array X[] using Linear search method. Print array X[] and index or position of num, if
found in the array otherwise print message “ Not found in the list and search unsuccessful” along with
the num.
Ans:
class search
{
static void main(int num, int a[])

{
int len=[Link];
int pos=0;
int c=0;
[Link]("Printing the elements=");
for(int i=0;i<len;i++)
{
[Link](a[i]);
}

for(int i=0;i<len;i++)
{
if(num==a[i])
{
pos=i;
c++;
break;
}
}
if(c>0)
{
[Link]("Element found");
[Link]("Position="+pos);
[Link]("Place="+(pos+1));
}
else
[Link]("Element not found");

}
}
Q14) WAP to input elements in a single dimensional array. Input and index or subscript within 0-9 and
print the table upto 10 of the number/element present at the given index.
Ex:
Enter elements:
2 3 4 5 6 7 8 9 10 12
Enter subscript:2
4*1=4
4*2=8
…..
4*10=40

Q15) WAP to initialize 5 city/country names into array of string and perform the following: (CW)
1. Print all the strings along with index numbers in separate lines.
2. Print the character present at the 3rd position in the 2nd string element.
3. Print length of string present at 3rd index along with the string itself.
delhi,pune,mumbai,nagpur,jaipur
Output:
delhi 0
pune 1
mumbai 2
nagpur 3
jaipur 4
Character present at 3rd position in the 2nd string “mumbai”= b
String=nagpur Length=6

Q16) WAP to store 6 integer elements in an array P, and 4 elements in array Q and produce a third array
R, containing all the elements of arrays P and Q. Display resultant array.
P[]={11,2,3,4,5,6}
Q[]={11,22,33,44}
R[]{11,2,3,4,5,6,11,22,33,44}
Binary Searching

1. Binary Search will work only on sorted array either in ascending or descending order.
2. Binary Search is faster than Linear Search.

50 40 30 20 10
0 1 2 3 4

For Ascending:

import [Link].*;
class BinarySearch
{
static void show(int val)

{
int a[]={10,20,30,40,50};
int l=[Link];
int lb=0, ub=l-1;
[Link]("Displaying the array elements:");
for(int i=0;i<l;i++)
{
[Link](a[i]+"\t");
}
int pos=-1;
while(lb<=ub)
{
int mid=(lb+ub)/2;
if(val==a[mid])
{
pos=mid;
break;
}
else if(val>a[mid])
lb=mid+1;
else if(val<a[mid])
ub=mid-1;
}
if(pos>=0)
[Link]("\nElement found at "+pos+" position");
else
[Link]("\nElement not found");
}
}
For Descending:

import [Link].*;
class BinarySearch
{
static void show(int val)

{
int a[]={50,40,30,20,10};
int l=[Link];
int lb=0, ub=l-1;
[Link]("Displaying the array elements:");
for(int i=0;i<l;i++)
{
[Link](a[i]+"\t");
}
int pos=-1;
while(lb<=ub)
{
int mid=(lb+ub)/2;
if(val==a[mid])
{
pos=mid;
break;
}
else if(val<a[mid])
lb=mid+1;
else if(val>a[mid])
ub=mid-1;
}
if(pos>=0)
[Link]("\nElement found at "+pos+" position");
else
[Link]("\nElement not found");
}
}

You might also like