Yêu cầu
– Nhập vào mảng 1 chiều số nguyên
– Viết hàm tìm giá trị âm đầu tiên trong mảng số nguyên. Nếu mảng không có số âm, trả về -1
Giải thuật
– Dùng vòng lặp for() và câu lệnh if() để kiểm tra.
Code
package net.vncoding; public class JavaCore { static int arr[] = {1, -3, -9, 7, 8, 16, -23, 2, 100}; public static void main(String[] args) { int res = find_first_negative(arr); if(res == 1) System.out.println("There is no negative element"); else System.out.println("First negative of array is " + res); } public static int find_first_negative(int arr[]) { int min = 1; int i; for(i = 0; i < arr.length; i++) { if(min > arr[i] && arr[i] < 0 ) { min = arr[i]; break; } } return min; } }
Kết quả
Leave a Reply
You must be logged in to post a comment.