Kotlin program to check if an array contains a given value

Kotlin | Checking an element in an array: Here, we are going to learn how to check if an array contains a given value in Kotlin programming language? Submitted by IncludeHelp, on May 05, 2020

Kotlin - Check if an array contains a given value

Given an array and an element, we have to check whether array contains the given element or not.

Example:

Input:
arr = [34, 56, 7, 8, 21, 0, -6]
element to check: 21

Output:
21 found at 4 index

Program to check if an array contains a given value in Kotlin

package com.includehelp

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //Input Array Size
    print("Enter number of elements in the array: ")
    val size = scanner.nextInt()

    //Create Integer array of Given size
    val intArray = IntArray(size)

    //Input array elements
    println("Enter Arrays Elements:")
    for (i in intArray.indices) {
        print("intArray[$i] : ")
        intArray[i] = scanner.nextInt()
    }

    //Print All Array Elements
    println("Array : ${intArray.contentToString()} ")

    //input integer no to be find in array
    print("Enter Integer Number to be Searched in Array : ")
    val num = scanner.nextInt()


    var isFound= false
    var itemAt = 0

    //Search Given number into Array
    for(item in intArray){
        if(item==num){
            isFound=true
            itemAt =intArray.indexOf(item)
            break
        }
    }

    //Alternatively we can also use contains(num) method of Arrays Class 
    //in kotlin to find specific elements Array or not
    //var isFound = intArray.contains(num)
    if(isFound){
        println("$num found in Arrays at Index $itemAt")
    }
    else{
        System.err.println("$num Not found in Arrays !!")
    }
}

Output

Run 1:
-----
Enter number of elements in the array: 7
Enter Arrays Elements:
intArray[0] : 34
intArray[1] : 56
intArray[2] : 7
intArray[3] : 8
intArray[4] : 21
intArray[5] : 0
intArray[6] : -6
Array : [34, 56, 7, 8, 21, 0, -6]
Enter Integer Number to be Searched in Array : 21
21 found in Arrays at Index 4
--------
Run 2:
----
Enter number of elements in the array: 7
Enter Arrays Elements:
intArray[0] : 3
intArray[1] : 4
intArray[2] : 5
intArray[3] : 7
intArray[4] : 90
intArray[5] : -89
intArray[6] : 5
Array : [3, 4, 5, 7, 90, -89, 5]
Enter Integer Number to be Searched in Array : 345
345 Not found in Arrays !!

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.