Click here to Skip to main content
15,887,254 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given an array of numbers. For each number in array, find the multiples that exist in the array.
I was supposed to get
Array - [2, 3, 6, 10]
Output-
Multiples of 2 - 6,10
Multiples of 3 - 6
Multiples of 6 - No multiples
Multiples of 10 - No multiples
Instead I am getting
Multiples of3is:3
No multiples

What I have tried:

import java.util.*;
import java.io.*;
import java.lang.*;
public class multiplesarrays
{
    public static void main(String[] args)
    { 
        Scanner sc=new Scanner(System.in);
        
        System.out.println("Enter the no: of elements in array");
        int n=sc.nextInt();
        int arr[]=new int[100];
        for(int i=0; i<n; i++)
        {
            arr[i]=sc.nextInt();
        }
        System.out.println("Multiples of each element of array is:");
       for(int i=0; i<n; i++)
       {
       for(int j=0; j<n; j++)
       {
           if(arr[j++]%arr[i++]==0)
           {
              
               System.out.println("Multiples of"+arr[i++]+"is:"+arr[j++]);
               break;
           }
           else
           {
               System.out.println("No multiples");
               break;
           }
       }
       }
    }
}
Posted
Updated 23-Jun-23 9:11am
v2

1 solution

Quote:
Find multiples of each number in array using java

Never use postincrement on variables that control the loops. Unless you know exactly what you do.
Java
for(int i=0; i<n; i++) // Here is the only ++ you need on i
{
for(int j=0; j<n; j++) // Here is the only ++ you need on j
{
    if(arr[j++]%arr[i++]==0) // no ++ here
    {

        System.out.println("Multiples of"+arr[i++]+"is:"+arr[j++]); // no ++ here
        break;
    }
    else
    {
        System.out.println("No multiples");
        break;
    }
}
}

Other errors too.
Edit:
As for the errors, run your code and look at the results you should understand rather quickly what is wrong.
Hint: you should not test a value against itself.
 
Share this answer
 
v2
Comments
k5054 23-Jun-23 15:23pm    
This applies to pre-increment and pre/post decrement of loop control variables as well. In general modifying a loop control variable inside the loop is not the right thing. There are times when you do want to modify the loop control variable, but not usually, especially when using the loop control to iterate over a data collection of some sort.
Patrice T 23-Jun-23 15:37pm    
Sure, you are right.
I didn't meant to make a course on the subject, just to adress the spécific problem in this code.
Patrice T 23-Jun-23 15:49pm    
You can make this comment a solution. So that OP will pay attention.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900