I want to output 20 numbers? - java

I have an array that has the size 20 values, but when I run my code it only outputs 3 values.How do I input 20 values into my array?
public class LoopsMaybe
{
public static void main(String [] args)
{
int[] lott = new int[20];
for( int i=5; i<lott.length;i=i+7)
{
System.out.println(i);
}
}
}
Output:
5
12
19
I want it to print out 5,12,19,26, 33, 40, 47.....and stop at the 20th number in the sequence

A very easy and concise way to get this done, for those interested in Java 8 niceties, is:
int seed = 5, inc = 7, many = 20;
IntStream is = IntStream.iterate(seed, n -> n + inc);
is.limit(many).forEach(x -> System.out.print(x + " "));
Output: 5 12 19 26 33 40 47 54 61 68 75 82 89 96 103 110 117 124 131 138

If you must use the array then you need something else to perform the increment by 7. That way you are guaranteed 20 iterations.
public class LoopsMaybe
{
public static void main(String [] args)
{
int[] lott = new int[20];
int inc=5;
for( int i=0; i<lott.length;i++)
{
System.out.println(inc);
inc += 7;
}
}
}

public class LoopsMaybe {
public static void main(String [] args) {
int[] lott = new int[20];
int val = 5;
for(int i=0; i<lott.length; i++) {
lott[i] = val;
System.out.println(val);
val = val + 7;
}
}
}

Related

How to pass by value in java? [duplicate]

This question already has answers here:
Problem with assigning an array to other array in Java
(4 answers)
Make copy of an array
(11 answers)
Closed 2 years ago.
I'm trying to make a project in which an array is sorted by different sorting algorithms. However, I have noticed that after one algorithm sorts the array and displays the value, the original array is also changed. How can I solve this?
public static void main(String[] args) {
int[] array = {20, 35, -15, 7, 55, 1, -2};
printArray(array);
boubleSort(array);
printArray(array);
}
The first function prints out the array in its unsorted form, the second one sorts the array and then prints the sorted array. The third line prints the original array (which should remain unsorted) as sorted. Why odes this occur and how can I change this?
public static void boubleSort(int[] array) {
System.out.println("Bouble Sort");
int [] arr = array;
for(int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex;i++) {
if(arr[i] < arr[i+1]) {
swap(arr,i, i+1);
}
}
}
printArray(arr);
}
public static void swap(int [] array, int i, int j) {
if (i == j) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void printArray(int [] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println();
}
Current output: Desired output:
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2
Bouble Sort
35 35
20 20
7 7
1 1
-2 -2
-15 -15
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2

Printing 2D Matrix in a given format

//Given a number n i want to generate the corresponding 2-d matrix for it .
//for example for n = 1 my 2-D matrix should be
for n = 1
1 2
3 4
for n = 2
1 2 5 6
3 4 7 8
9 10 13 14
11 12 15 16
for n = 3
1 2 5 6 17 18 21 22
3 4 7 8 19 20 23 24
9 10 13 14 25 26 29 30
11 12 15 16 27 28 31 32
33 34 37 38 49 50 53 54
35 36 39 40 51 52 55 56
41 42 45 46 57 58 61 62
43 44 47 48 59 60 63 64
The problem could be solved using recursion. For example, the code below prints exactly the required matrix for a given n.
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
final int n = scanner.nextInt();
final int[][] matrix = create(1, (int) Math.pow(2, n));
print(matrix);
}
private static int[][] create(final int startValue, final int size) {
if (size == 1) {
return new int[][]{{startValue}};
} else {
final int half = size / 2;
final int step = half * half;
return combine(create(startValue, half), create(startValue + step, half),
create(startValue + 2 * step, half), create(startValue + 3 * step, half));
}
}
private static int[][] combine(final int[][] m1, final int[][] m2, final int[][] m3, final int[][] m4) {
final int initialSize = m1.length;
final int sizeOfResult = initialSize * 2;
final int[][] result = new int[sizeOfResult][sizeOfResult];
for (int row = 0; row < initialSize; row++) {
for (int col = 0; col < initialSize; col++) {
result[row][col] = m1[row][col];
result[row][col + initialSize] = m2[row][col];
result[row + initialSize][col] = m3[row][col];
result[row + initialSize][col + initialSize] = m4[row][col];
}
}
return result;
}
private static void print(final int[][] matrix) {
for (final int[] row : matrix) {
for (final int val : row) {
System.out.printf("%-5d", val);
}
System.out.println();
}
}
}

Random Number Generator of Even and Odd Numbers

I need to create an application that generates 25 random integers between 0 and 99 and then outputs those integers on two separate lines one for odd numbers and one for even numbers. I will need to use one array for even numbers and one for odd numbers. This is what I have so far:
public static void main(String[] args) {
//Odd Numbers
int[] oddNums = new int[25];
for (int index = 0; index < oddNums.length; index++) {
oddNums[index] = (int) (Math.random()*99);
}
System.out.print("ODD: ");
for (int index = 0; index < oddNums.length; index++) {
System.out.print(oddNums[index] + " ");
}
//Even Numbers
int[] evenNums = new int[25];
for (int index = 0; index < evenNums.length; index++) {
evenNums[index] = (int) (Math.random()*99);
}
System.out.print("\nEVEN: ");
for (int index = 0; index < evenNums.length; index++) {
System.out.print(evenNums[index] + " ");
}
}
I have set up the program to print out 25 random integers, but I do not know how I am going to get the program to print out only even numbers on one line and odd numbers on another (I am new to java).
Here is a sample output I am getting:
ODD: 28 36 54 98 35 1 59 43 96 69 41 66 37 15 30 17 29 67 56 83 71 4
24 70 38
EVEN: 34 45 36 26 73 84 60 39 21 49 28 98 69 14 32 24 72 29 26 88 77 2
23 58 47
This is wrong since there are both even and odd numbers on both lines.
This is what the output should look like:
ODD: 25 97 23 45 63 91 13 47 93 51 29
EVEN: 22 94 46 74 18 48 32 84 28 92 56
There are only odd numbers on one line and even numbers on another line.
Does anyone know what I need to add here?
A little modification to your program will yield the desired result.
public static void main(String[] args) {
//Odd Numbers
int[] randomNumbers = new int[25];
int[] evenNumbers = new int[25];
int[] oddNumbers = new int[25];
int k = 0, l = 0;
for (int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random() * 99);
}
for (int i = 0; i < 25; i++) {
if (randomNumbers[i] % 2 == 0) {
evenNumbers[k] = randomNumbers[i];
k++;
} else {
oddNumbers[l] = randomNumbers[i];
l++;
}
}
}
You can generate an even number uniformly at random in [0,100] with the formula n = 2*x where x is uniformly random in [0, 49].
You can similarly generate an uniformly random odd number with n = 2*x+1 where x is uniformly random in [0,49].
You can just generate the 25 number. After generating those ints, you can locate them in the array they belong.
int num;
int oddIndex = -1;
int evenIndex = -1;
for (index = 0; index < 25 ; index++){
num = (int) (Math.random()*99);
if (num % 2 == 1){
oddIndex++;
oddNum[oddIndex] = num;
}
else{
evenIndex++;
evenNum[evenIndex] = num;
}
}
In this case, you're not sure about the sizes of each array. So, I advise you to use ArrayList instead of array. If you use an ArrayList, you won't need to deal with oddIndex and evenIndex.
Firstly,The random function you have written will be generating random numbers between 0 and 99. It will not be considering whether the numbers are odd or even.
If there is no restriction on the number of odd numbers and number of even numbers, just use the random generator once and depending on whether it is odd or even place it in the correct array.
For doing so, use the MOD operator i.e. check for remainder after dividing by 2 to see odd or even
At some point in your code, you need to have something like,
Pseudocode:
if (nextNumber is odd) then
put nextNumber at end of ODD array
else
put nextNumber at end of EVEN array
endif
You should also have a look at util.Random.nextInt() which is preferable for generating random integers.
Here's a solution that uses Java 8 streams:
public class NumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int[] ints = random.ints(25, 0, 99).sorted().toArray();
int[] even = IntStream.of(ints).filter(x -> x % 2 == 0).toArray();
int[] odd = IntStream.of(ints).filter(x -> x % 2 == 1).toArray();
System.out.println(Arrays.toString(even));
System.out.println(Arrays.toString(odd));
}
}
First an array of all random integers are being created. 25 random integers are created and they should all be between 0 and 99.
The evens and odds are filtered out into two separate arrays.
[0, 4, 6, 16, 18, 22, 40, 42, 58, 64, 82, 84, 98]
[7, 27, 29, 31, 35, 55, 73, 75, 75, 79, 83, 91]

Pascal Triangle Not Printing Correctly in Java?

I got an assignment that requires us to print out pascal's triangles based on the user entered value of N. We were provided a main that allows the user to calculate Pascal’s Triangle based on a value of n. In this case if n is 0, then Pascal’s Triangle is 1. Otherwise for n being greater than 0, the appropriate Pascal’s Triangle will be created and displayed. Here is the main:
public class CSCD210Lab13
{
public static void main(String[] args)
{
int n = 0;
int [][] pascal = null;
do
{
n = Lab13Methods.readN();
pascal = Lab13Methods.createPascalsTriangle(n);
Lab13Methods.printPascals(pascal);
}while(MyUtil.goAgain());
}// end main
}// end class
Here is my Methods file:
import java.util.*;
public class Lab13Methods
{
public static int readN()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter N: ");
int n = kb.nextInt();
while(n < 0)
{
System.out.println("Number Below 1. Re-Enter: ");
n = kb.nextInt();
}
return n;
}
public static int[][] createPascalsTriangle(int n)
{
int[][]pascalTri = new int[n + 1][(n + 1) * 2];
int sideOne, side;
pascalTri[0][n - 1] = 1;
sideOne = side = n - 1;
for (int y = 1; y < n; y++)
{
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
for (int k = 1; k <= y; k++)
{
int left = pascalTri[y - 1][sideOne + (2 * k) - 1];
int right = pascalTri[y - 1][sideOne + (2 * k) + 1];
pascalTri[y][sideOne + (2 * k)] = left + right;
}
}
return pascalTri;
}
public static void printPascals(int[][]pascal)
{
for (int f = 0; f < pascal.length; f++)
{
for (int v = 0; v < pascal[f].length; v++)
{
if (pascal[f][v] == 0)
{
System.out.print("");
}
else
{
System.out.print(pascal[f][v]+" ");
}
}
System.out.println();
}
}
}
Here is my goAgain file:
public static boolean goAgain()
{
boolean goAgain = false;
String answer;
Scanner kb = new Scanner(System.in);
System.out.println();
System.out.print("Do you want to go again? ");
answer = kb.nextLine();
while(!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no"))
{
System.out.print("Invalid Input. Do you want to go again? ");
answer = kb.nextLine();
}
if(answer.equalsIgnoreCase("yes"))
{
goAgain = true;
}
else if(answer.equalsIgnoreCase("no"))
{
goAgain = false;
}
return goAgain;
}
}
My question is about how it's printing. If I enter 10 to be the value of N, this is how it is supposed to print:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
However, this is how mine prints:
1
1 1 1 1
1 1 2 1 1
1 1 3 3 1 1
1 1 4 6 4 1 1
1 1 5 10 10 5 1 1
1 1 6 15 20 15 6 1 1
1 1 7 21 35 35 21 7 1 1
1 1 8 28 56 70 56 28 8 1 1
What am I doing wrong?
I think your error may be here:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
Your program is designed to fill in the cells of the array in a checkerboard pattern:
for any two adjacent rows, one row will have non-zero entries only
in even-numbered locations, and the other will have non-zero entries
only in odd-numbered locations.
Notice that right after you do pascalTri[y][sideOne] = 1;, you decrement sideOne.
That means if you are in a row that should be using odd-numbered cells,
sideOne now is odd, but when you did pascalTri[y][sideOne] = 1;,
sideOne was still even. So you have put an even-numbered entry in a row that
should have only odd-numbered entries.
That is where all the extra 1s are coming from in your output.
Just delete these lines:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
All they are doing is creating those extra, unwanted 1 values. All the correct values
are being written in the array by other statements.
I don't know if you know what a pascal triangle is let me explain to you what it is.
11^0 = 1
11^1 = 11
11^2 = 121
11^3 = 1331
11^4 = 14641
11^5 = 161051
I don't know why have you done some much code all when you need was
public static void printPascalsTriangle(int n)
{
long number=11l;
for(int i=0;i<=n;i++)
{
System.out.println(new Double(Math.pow(number,i)).longValue());
}
}
You would need a case more that five which can be handled like this link.
Refer this short pascal code i have written which is depend on user input:
public class Pascal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the Number of levels of Pascal");
int levelCount = scanner.nextInt();
for(int i =0;i<levelCount;i++) {
int value = 1;
for(int j=0;j<=i;j++) {
System.out.println(value);
value = value * (i - j) / (j + 1);
}
System.out.println("\n");
}
}
}
Enjoy..!!

How to print nth number series in java

Could anyone please help me to print below series in java . I am trying to use below code but it seems not working correctly.
Desired output:
9 18 27 36 45
9 18 27 36
9 18 27
9 18
9
My code :
public class NumberSet {
public static void main (String args[])
{
int i = 0, j=0;
for (j=1;j<=5;j++)
{
for (i=1;i<=50;i++)
{
if (i%9 ==0)
{
System.out.print(" " + i + " ");
}
}
System.out.println();
}
}
}
Output of my code:
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
Thanks for your help in Advance.
Arfater
First, you can generate multiplies of 9 more efficiently by multiplying by 9 than by looping over all numbers and checking if they are divisible by 9.
Second, you can simply change the order of the outer loop, and make the inner loop variable depend on the outer loop variety to get different behavior for every iteration of the outer loop.
public class NumberSet {
public static void main (String args[])
{
int i,j;
for (j=5;j>=1;j--)
{
for (i=1;i<=j;i++)
{
System.out.print(" " + i*9 + " ");
}
System.out.println();
}
}
}
Output:
9 18 27 36 45
9 18 27 36
9 18 27
9 18
9
Try this:
public class NumberSet {
public static void main (String args[])
{
int i = 0, j=0, mul= 1;
for (j=5;j>=1;j--)
{
mul = 1;
for (i=1;i<=j;i++)
{
System.out.print(" " + mul++ * 9 + " ");
}
System.out.println();
}
}
}
Hope this helps u...
Try this:
enter code here
public class Myclass {
public static void main(String args[])
{
int num = 5;
for (int i = 0; i < 5; i++, num--)
{
for (int j = 1; j <= num; j++ )
{
System.out.print(9*j + " ");
}
System.out.println();
}
}
}

Categories