Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to not print out number 23 in my code?

Create a program that takes an array of integers as arguments. The program should output odd numbers from the array and will stop if it encounters the number 23.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[] = new int[n];
        boolean add =true;
        gig(n, arr);
    }

    public static void gig(int n, int arr[]){
        Scanner in = new Scanner(System.in);
        for(int i=0; i<arr.length; i++){
            arr[i] = in.nextInt();
            if(arr[i]%2!=0){
                System.out.println(arr[i]);
            }
            if(arr[i]==23)
                break;
        }        
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can change the if conditions order, this way the for loop will break when the number is equal to 23 before it gets printed

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[] = new int[n];
        boolean add =true;
        gig(n, arr);
    }

    public static void gig(int n, int arr[]){
        Scanner in = new Scanner(System.in);
        for(int i=0; i<arr.length; i++){
            arr[i] = in.nextInt();
            
            if(arr[i]==23)
              break;
                
            if(arr[i]%2!=0){
                System.out.println(arr[i]);
            }
        }        
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading