Friday, 20 October 2023

JAVA

Adding two numbers using functions

Lets get started

 
       
  1. import java.util.* ;
  2. public class Main {
  3. public static void main (String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. System.out.println("Enter size : ");
  6. int size = sc.nextInt();
  7. // initializing array
  8. int[] arr = new int[size] ;
  9. // taking array inputs from the user
  10. for(int i = 0 ;i
  11. if(sc.hasNextInt()){
  12. arr[i] = sc.nextInt() ;
  13. }
  14. }
  15. // calling the function
  16. System.out.println(doSomething(arr));
  17. }
  18. // creating the function
  19. public static int doSomething(int[] arr){
  20. int Ones = 0 ;
  21. int Zeros = 0 ;
  22. // counting numner of zeros and Ones
  23. for(int i = 0 ; i < arr.length ; i++){
  24. if(arr[i] == 0){
  25. Zeros ++ ;
  26. }else{
  27. Ones++ ;
  28. }
  29. }
  30. // logic
  31. if(Ones < Zeros){
  32. return Ones * 2 ;
  33. }else{
  34. return Zeros * 2 ;
  35. }
  36. }
  37. }

Output

  Enter size : 
  7
  0
  1
  0
  1
  1
  0
  0
  6

  Enter size : 
  2
  0
  1
  2

  
        
`

No comments:

Post a Comment