Check Consecutive Character Sequence in an Array: This Java program aims to check whether the elements of an integer array form a consecutive sequence starting from a specific value. It does so by converting the characters from a given char array into integers and then checks for consecutive values in the resulting integer array.
Check Consecutive Character Sequence in an Array
package com.softwaretestingo.interviewprograms; public class InterviewPrograms37 { public static void main(String[] args) { char[] JavaCharArray = { 'a', 'b', 'c', 'd', 'e' }; int val[]=new int[5]; for(int i=0;i<5;i++) { val[i]=(int)JavaCharArray[i]; } System.out.println(checker(val)); } public static boolean checker(int[] array) { int array_element_count=array.length; int f_val=array[0]; int count=0; for(int i=0;i<5;i++) { if(array[i]==(f_val+i)) { count++; } } if(count==array_element_count) { return true; } return false; } }
Output
true
Here’s a breakdown of the program:
- Define the main method:
- The entry point of the program is the main method.
- Initialize the char array and integer array:
- The char array JavaCharArray is initialized with characters ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’.
- The integer array val is declared and allocated memory to store integers corresponding to the characters in JavaCharArray.
- Convert characters to integers:
- The program uses a for loop to convert each character in JavaCharArray to its corresponding ASCII value and stores it in the val array.
- Call the checker method:
- The checker method is called with the val array as an argument, which checks whether the elements in the array form a consecutive sequence.
- Define the checker method:
- The checker method takes an integer array array as input.
- It initializes array_element_count with the length of the input array.
- It sets f_val to the value of the first element in the array.
- The method then iterates through the array and compares each element to the expected value based on the first element’s value and its index. If the elements are consecutive, it increments the
count
. - Finally, the method checks if the count is equal to the array_element_count. If true, it returns true, indicating that the elements form a consecutive sequence; otherwise, it returns false.
The program then prints the result returned by the checker method. If the val array contains consecutive integers (e.g., [97, 98, 99, 100, 101]), the output will be true. Otherwise, if the array elements are not consecutive (e.g., [97, 98, 101, 102, 103]), the output will be false.
Leave a Reply