How can I find even or odd in array?
int size;
int[] myArray = new int[10];
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you enter:");
size = input.nextInt();
for(int c = 0; c < size; c++)
{
System.out.print("Enter number:");
myArray[c] = input.nextInt();
}
input.close();
for(int c = 0; c < size; c++)
{
System.out.println(myArray[c]);
}
if(size%2)
{
System.out.print("sadsadsad");
}
}
}
Use modulus operator to check if the number is even or odd. If we divide any number by 2 and reminder is 0 then the number is even, otherwise it is odd.
for(int i=0; i < numbers.length; i++){
if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even number.");
else
System.out.println(numbers[i] + " is odd number.");
}
you can check whether a number is even or odd
if((x%2)==0)
// even
else
// odd
or
You can use the modulus operator, but that can be slow. If it's an integer, you can do:
if ( (x & 1) == 0 ) { even... } else { odd... }
here is your edited code
for(int c = 0; c < size; c++)
{
if(myArray[c]%2==0)//check num is even or odd
System.out.println(myArray[c]+" even");
else
System.out.println(myArray[c]+" even");
}
Why do you want to check with the size?
Is that you want to check that if the length of the array is odd or even?
If you want the odd and even numbers in an array, you need to check it with each element in the for loop itself.
for(int c = 0; c < size; c++)
{
if(myarray[c]%2 == 0)
{
System.out.print(myarray[c] + " is even");
}
else
{
System.out.print(myarray[c] + " is odd");
}
}
Edit
A better way to find even or odd is to check only the last number.
We know that if the last digit is divisible by 2 then it is an even else it is an odd.
So If you want to check, we just check the last digit instead of using the % operator for the whole number.
for(int c = 0; c < size; c++)
{
if(isEven(myarray[c]))
{
System.out.print(myarray[c] + " is even");
}
else
{
System.out.print(myarray[c] + " is odd");
}
}
public boolean isEven(int number)
{
return (number%10) % 2 == 0;//number % 10 gets the last digit, checks if it is divisible by 2 or not
}
Related
I have the following code to print all prime numbers from 2 to 100:
int number1 = 2, number2 = 100, temp = 0;
System.out.println("prime numbers between" + number1 + "and" + number2 + "are :");
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp = 0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
What is the role of temp = 0 in the very beginning?
If I modify it to, lets say 1, I get a different output. The code then prints all primes starting from 5 instead of 2. Why are the other numbers skipped?
Explanation
Have a close look at your loop logic flow:
for (int i = number1; i <= number2; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
temp = 1;
break;
} else {
temp=0;
}
}
if (temp == 0) {
System.out.println(i);
}
}
i starts as 2 and increments. The inner loop is:
for (int j = 2; j <= i / 2; j++) {
Inner loop is skipped
That means that for the first iterations of the outer loop, for example i = 2 the condition of the inner loop evaluates to:
j <= i / 2
// which is
2 <= 2 / 2
// which is
2 <= 1
Hence the inner loop does not even enter at all and is skipped. So we directly reach
if (temp == 0) {
System.out.println(i);
}
The same is true for the iterations, i = 3.
i = 4 is the first iteration that actually enters the inner loop and starts overwriting temp with either 0 or 1.
Meaning of temp == 0
So during the first iterations of the outer loop (i = 2, i = 3), the initial state of temp plays a role, since it determines whether i will be printed or not.
So you need it to start as 0 to have the first values, for which the inner loop is not even entered, included in the output.
Notes
That said, using temp in such a way is overly complicated. It would be better if it would be moved to the place where it is actually needed, inside the loop, given a better name and also changed to a boolean. All in all, you may simplify the code as follows:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
And if you are willing to introduce a helper method like:
public static boolean isPrime(int candidate) {
for (int i = 2; i <= candidate / 2; i++) {
if (candidate % i == 0) {
return false;
}
}
return true;
}
Your code will heavily simplify and be very easy to read:
int min = 2;
int max = 100;
System.out.println("prime numbers between" + min + "and" + max + "are :");
for (int i = min; i <= max; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
you need to understand, what is the role of the variable temp in this code.
The variable temp is behaving like a flag, means whenever the number found to be divisible by another number, temp variable is setting as 1 and the code stops checking.
if we scan all the number upto i/2 and the variable temp is still 0, means we didn't find any number j which can divide current number i, then the current number is prime.
edit:
the role of temp=0 at the very beginning assumes all the number is prime. if found later number is divisible then we are assigning temp=1 and we get to know that the number is not prime.
The role in temp is to simply indicate if a prime was or was not found. Then use that value to control printing of the value under test. But it is not really needed (and as already stated in the comments, should have been a boolean).
Here is one way you could improve your effort without using that value.
Other than dividing by already found primes, you can make it somewhat more efficient by doing the following:
If the first prime is even, check to make certain it isn't 2.
if it is, print it.
if even, increment number1 by 1 to make it odd.
then starting iterating by both candidates and divisors by two to get just the odd numbers.
don't divide by any number > the square root of the candidate. Otherwise you are wasting time. Example, if 97 is not divisible by any of 3,5,7,11 then it must be a prime because any larger divisor would return a quotient < 11 which has already been checked.
you don't need a temp value. Just continue to the outer loop if the number is divided. Otherwise, print the number.
int number1 = 2, number2 = 100;
System.out.println("prime numbers between" + number1 + "and"
+ number2 + "are :");
if (number1 % 2 == 0) {
if (number1 == 2) {
System.out.println(2);
}
number1++;
}
outer:
for (int i = number1; i <= number2; i += 2) {
int max = (int)Math.sqrt(i);
for (int j = 3; j <= max; j += 2) {
if (i % j == 0) {
// try next candidate
continue outer;
}
}
// must be a prime so print it.
System.out.println(i);
}
A better approach is to use the Sieve of Erastosthenes. A BitSet is perfect for this. The idea is to:
mark every bit that is not a prime.
This eliminates composite numbers since it eliminates all their prime factors from the composite positions in the bitset.
The unset bit positions in the bitset are then primes.
as the list is being built, the first unset (clear) bit in the list is as prime.
BitSet bits = new BitSet();
bits.set(0,2); // set bits 0 and 1
initialize nextBit to the first prime
int nextBit = 2; // essentially bitSet.nextClearBit(0);
Continue the loop while the next bit is less than the square root of the terminal value.
while (nextBit <= Math.sqrt(number2)) {
// mark every prime position after this one.
for (int i = 2*nextBit; i < number2; i += nextBit) {
bits.set(i);
}
// the next clear bit after the previous prime must be a prime
// since it is next unset bit
nextBit = bits.nextClearBit(nextBit+1);
}
Now display them
// This is done by simply printing all the bit positions
// that are clear up to the terminal value.
int i = bits.nextClearBit(0);
while (i < number2) {
System.out.println(i);
i = bits.nextClearBit(i+1);
}
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.
Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0) //want factorial greater than zero
for(int j = n; j <= m; j++)
{
for(int i = 1; i <= j; i++)
{
result = result * i; //find factorial
}
System.out.println(result);
}
if(n <= 0 || m <= 0) //if value is les than zero
{
System.out.println("Not Valid!");
}
Something like should work:
public class RangeFactorial {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int max = scan.nextInt();
int min = scan.nextInt();
if (max < 0 || min < 0) {
System.out.println("Invalid Params");
}
for (int i = min; i <= max; i++) {
System.out.println("Factorial for " + i + " is: " + factorial(i));
}
scan.close();
}
private static int factorial(int i) {
if (i <= 1) {
return 1;
}
return i * factorial(i-1);
}
}
Note that the code assumes that max/min fall in place, I've omitted the logic to decide the max/min integer from the given inputs. You'll need to add this.
You forgot to reset 'result' to 1.
Also, there is no need to have another if statement if it is only checking for the negation of the first one, just use an else.
I also fixed the code style guidelines to follow the standard Java ones as:
The curly bracket style you used is the one usually used in C/C++.
Even if if-statements or loops contain only one line after them, it is good etiquette to use curly brackets anyway, in Java.
Take a look at the Google Java Style Guide if you want to know more.
Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0){
for(int j = n; j <= m; j++){
result = 1; //You forgot to reset 'result'
for(int i = 1; i <= j; i++){
result *= i;
}
System.out.println(result);
} else { // No need for another if statement
System.out.println("Not Valid!");
}
I'm required to code a program that, using a do-while loop, will print 25 prime numbers on a new line. I have everything figured out on it, except for printing out exactly 25 numbers. However, the program is only giving me prime numbers up to the number 25, not 25 prime numbers.
I set a variable "count" to increase every time the loop is run, with the same result. Here's my code (sorry for the length, I would shorten it but I'm worried the whole thing might be messed up):
int firstNum;
int secondNum = 1;
int num;
int count = 0;
System.out.println("Sample run: \n\nPrime numbers");
do {
num = 0;
firstNum = 2;
while (firstNum <= secondNum / 2) {
if (secondNum % firstNum == 0) {
num++;
count++;
break;
}
firstNum++;
}
if (num == 0 && secondNum != 1) {
count++;
System.out.print("\n" + secondNum + " ");
}
secondNum++;
} while(count < 25);
}
}
You need to remove count++; inside first if block to get 25 prime numbers.
Updated Code:
int firstNum;
int secondNum = 1;
int num;
int count = 0;
System.out.println("Sample run: \n\nPrime numbers");
do {
num = 0;
firstNum = 2;
while (firstNum <= secondNum / 2) {
if (secondNum % firstNum == 0) {
num++;
// count++; // <--- Remove this.
break;
}
firstNum++;
}
if (num == 0 && secondNum != 1) {
count++;
System.out.println(secondNum); // Use println() for new line.
}
secondNum++;
} while(count < 25);
}
Here's an example showing how you can iterate through some loop a fixed number of times, and separately calculate your next prime number. I'm clearly not calculating any primes here, just showing how you can separate the two concerns of "loop quantity" and "determine the next prime".
public static void main(String[] args) {
int prime = 0;
for (int k = 1; k <= 25; k++) {
prime = findPrimeAfter(prime);
System.out.println("#" + k + ": " + prime);
}
}
private static int findPrimeAfter(int lastPrime) {
// TODO: find the next prime that is greater than "lastPrime"
return 0;
}
I'm new to java/programming in general and this is a homework assignment. This is what I have so far: When I run it I get the powers of 2 below the n input. example if n = 50, output is 2 + 4 + 8 + 16 + 32 + = -2
I would like the + after 32 to be gone and I don't know how to properly sum it. I would want the sum to = 62 in this case. I tried using string builder to take off the last two characters but that isn't working for me.
import java.util.Scanner;
public class Powers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Enter the upper limit: ");
n = scan.nextInt();
int sum = 0;
int power = 1;
for (int i = 0; i <= n; i++) {
power = 2 * power;
if (power < n && 0 < power) {
System.out.print(power + " + ");
}
sum = sum + power;
}
System.out.println(" = " + sum);
}
}
There are multiple issues here:
When reaching the upper limit you simply stop doing the output but continue doing the summation.
You use the upper limit as the number of iterations, so in case of 50 in your example, you do a sum of all values between 1 and 2^50, which is the reason why the result is negative, because the sum became larger than the maximum number an int can keep.
Concerning your question how to break a loop, there is break ;-)
Your print is always outputting a + which is why you have the + = in your output. Change the output to something like this:
if (power < n && 0 < power) {
if (i != 0) {
System.out.print(" + ");
}
System.out.print(power);
}
I've added some functionality to your code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Type number:");
Scanner scanner = new Scanner(System.in);
int n = 0;
while (n == 0) { // to ask again if "n" is zero.
n = scanner.nextInt();
}
if (n != 0) {
scanner.close(); // to prevent resource leak
int sum = 0;
int power = 1;
for (int i = 0; i < n; i++) {
power *= 2;
sum += power;
System.out.print(power + " ");
if (sum + power * 2 < 0 | i == n - 1) {
// Should we step to the next iteration?
// If next "sum" will be bigger than the max value for
// integers
// or if this iteration is the last - it will type "sum",
// break "for" cycle and go the next line of code after
// "for" cycle.
// So in this case System.out.print("+ "); won't be
// executed.
System.out.print("= " + sum);
break;
}
System.out.print("+ ");
}
}
}
}
I'm having a little trouble with my program. I already wrote my user validation and I can print all odd numbers up to what the user inputed. My problem is trying to get 10 integers on every line. Obviously, I tried the i % 10 == 0 technique and as you know odd number can't have a remainder of zero. If you could give some tips or guidance that's be fantastic!
import java.util.*;
public class Question {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.print("Please enter a number. ");
n = input.nextInt();
while(n < 0 || n > 1000){
System.out.print("Error: 0 <= N <= 1000. Reenter.");
n = input.nextInt();
}
for(int i = 1; i <= n; i+=1) {
System.out.print(" " + i);
if(i % 10 == 0)
System.out.print("\n");
}
}
}
The following logic seems to work:
for (int i=1; i <= n; i+=1) {
if (i % 2 == 1)
System.out.print(" " + i);
if (i % 20 == 0)
System.out.print("\n");
}
The basic idea here is that the (i % 2 == 1) condition prints only odd numbers, and the (i % 20 == 0) adds a line break every ten numbers. The reason we use mod 20 is that there are ten odd numbers for every 20 counting numbers.
Demo
Here's what I came up with
int count = 0;
for(int i = 1; i <= n; i+=1) {
if (i % 2 == 1){
System.out.print(" " + i);
count += 1;
continue;}
if(count % 10 == 0)
System.out.print("\n");
}
Adding a count which only increases when an odd number is printed means that you can test to see if it is divisible by 10.