In: Computer Science
Write a program to read in a collection of integer values, and find and print the index of the first occurrence and last occurence of the number 12. The program should print an index value of 0 if the number 12 is not found. The index is the sequence number of the data item 12. For example if the eighth data item is the only 12, then the index value 8 should be printed for the first and last occurrence.
The coding language required is Java.
import java.io.*;
class Main
{
public static void main(String args[])throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of elements");
int n=Integer.parseInt(in.readLine()); // taking size of array as input from user
int arr[]=new int[n];
System.out.println("Enter the elements"); // taking elements of array as input from user
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(in.readLine());
int flag=0; //to check whether 12 is present in array or not
//to determine first index of 12, run for loop from first to last index of array
for(int i=0;i<n;i++)
{
if(arr[i]==12)
{
flag=1; //if 12 is present,set flag to 1
System.out.println("First index of 12="+(i+1)); // printing i+1 because array indexing starts from 0
break; // break out from loop as soon as first index of 12 is found
}
}
// to determine last index of 12, run for loop from last index to first index of array
for(int i=n-1;i>=0;i--)
{
if(arr[i]==12)
{
flag=1;
System.out.println("Last index of 12="+(i+1)); // printing i+1 because array indexing starts from 0
break; // break out of loop as soon as last index of 12 is found
}
}
// if 12 is present in array then value of flag will be 1,else 0.
if(flag==0)
System.out.println("First and Last index of 12= 0");
}
}
An array is used to store the integer values. The inputs are taken dynamically from the user.
The first loop runs from 0th till (n-1)th index. As soon as 12 is encountered in the array, flag is set to 1 and the index position of first occurence of 12 is printed and the control breaks out of the first for loop.
The second loop runs in reverse order from (n-1)th index to the 0th index of array. As soon as 12 is encountered in the array, flag is set to 1 and the index position of the last occurence of 12 is printed and the control breaks out of the second for loop.
Lastly, we check the value of flag. If flag value is set to 1, it means that the element 12 is present in the array. If flag value is set to 0, it means that the element 12 is not present in the array and the first and last index of 12 is printed as 0 as mentioned in the question.