r/programminghelp • u/Aggravating_Ad_6628 • Oct 31 '23
Java can somebody help me to simplify this?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a[]={1,2,3,4,5,6,7,8,9,0};
Scanner Input=new Scanner(System.in);
int c=0;
System.out.println("enter a number to check");
int b=Input.nextInt();
for (int i=0;i<10;i++) {
if(a[i]==b){
c=1;
}
}
if(c==1){
System.out.println("the number is in the a system");System.out.println("the number is in the system");
}
else{
System.out.println("the number is not in the system");
}
}
}
1
Upvotes
1
u/cython_boy Nov 01 '23 edited Nov 01 '23
Its linear search .
You have an array of numbers name a .
First initialize c=0 means False .
Then you take an integer input and put it in the variable name b .
You are lopping to each index of an array name a and check is b equal to arrays ith index value of array a .
If the answer is yes you assign c=1 means True . You can use the break statement here to stop the loop because you found what you are looking for and it stops further looping to the array name a.
In the end if c is equal to 1 (True) means number in an array .
If c is equal to 0 (False) means number is not in array.