Java nested for loop print out - java

I'm a total beginner to java and need help writing this nested for loop. This is the desired output.
2 3 5
5 10 26
11 31 131
23 94 656
I understand that the increment is 2 times the first number + 1, but I don't understand how to create the loop for it.
public static void main(String[] args) {
for(int i = 2; i <= 5; i++) {
for(int j = i; j <= i; j++) {
System.out.print(j+(i*j));
}
System.out.println();
}
}

Question is so simple it consists of two things read the pattern and use the appropriate loop statements in java to achieve this. Printing them is another task which is not difficult.
#Jonathan your pattern is right but your algorithm is incorrect.
I'm not giving you perfect solution but you have to use proper loop statement to make it efficient. I'm here giving you a thought so that you can think in this way..hope you get it.
public static void main(String[] args) {
/* 2 3 5
5 10 26
11 31 131
23 94 656
*/
int two = 2;
int three = 3;
int five = 5;
int i=0;
//use do-while to print 2 3 5
do{
System.out.println(two +" "+ three +" "+five);
two=two*2+1; // apply math pattern
three= three*3+1;
five= five*5+1;
i++;
}while(i<4);;
}

Please try the following code (I have tested the code, the output is exactly the same as yours):
public static void main(String args[]) {
int[][] results = new int[4][3];
results[0][0] = 2;
results[0][1] = 3;
results[0][2] = 5;
for (int i = 1; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
results[i][j] = results[i - 1][j] * results[0][j] + 1;
}
}
for (int i = 0; i < results.length; i++) {
for (int j = 0; j < results[0].length; j++) {
System.out.print(results[i][j] + "\t");
}
System.out.println();
}
}

Related

Loop not properly modifying array elements

The loop causing issues is the second for loop.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; dataPoints[i] < controlValue; ++i) {
dataPoints[i] = dataPoints[i] * 2;
}
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
Currently when i run the test, this is what pops up.
Testing with inputs: 10 2 12 9 20
Output differs.
Your output
4 12 9 20
Expected output
4 12 18 20
the first number in the list of inputs is the maximum number it should multiply by 2. Since 20 is > 10, it is not multiplied. However 9 should be multiplying to 18, but it is not. If anyone could give some insight into anything i might be doing wrong when forming this loop, I would greatly appreciate it. Thank you!
Your second for loop is exiting because of the condition and the order of your input data, and will stop when a control value is reached. For example, if you instead had an input of 10 1 2 3 4, you would get the results you expect (ie. 2 4 6 8), but your for loop is exiting when the condition dataPoints[i] < controlValue is reached (in your case at 12).
Instead you should loop through the entire dataPoints array, as you do in your 3rd loop, and check the controlValue before doubling the values.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; i < dataPoints.length; ++i) {
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
}
// This could be combined into the loop above...
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
You could also do all of this in a single loop if you wanted to, for example:
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
System.out.print(dataPoints[i] + " ");
}

How can I complete my code about the Sieve of Erathostenes?

It's about finding the prime numbers from 2 to 1000 using this method but I can't get the solution and I've been thinking and trying to solve this issue for three days. I'm desperate for help so if anyone can help me I would really appreciate it
I tried another for loop and an if statement since my teacher said that I only need another loop or just one more code line but I can't seem to get the solution. I'm really bad at this so I'm sorry if my code seems cringeworthy
public class Practica {
public static void main(String []
byte []marcado = new byte [1000];
for (int i = 2; i < 1000; i++);
if (marcado[i] == 1) {
for (int j = 2; i*j < 1000; j++) {
marcado [i*j] = 0;
}
}
I expect to have all the prime numbers printed
Give it a shot:
public static void main(String[] args) {
byte[] marcado = new byte[1000];
for (int i = 2; i*i < 1000; i++) {
if (marcado[i] == 0) {
for (int j = 2; i * j < 1000; j++) {
marcado[i * j] = 1;
}
}
}
// print the numbers:
for (int i = 1; i < 1000; i++) {
if(0 == marcado[i]){
System.out.print(" " + i);
}
}
}
Besides removing syntax errors, I reversed the logic such that marcado[i]==0 indicates a prime and noneprime otherwise.
The other possibility based on your aproach would be to initialize all the array elements with "1"(eg. with fill);

Transpose java error

I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).

For loop within a for loop

So I'm working on for loops and nested for loops. So I need to stick to these as my main functions.
I've gotten stuck on one question. I can think of the logic of how I'd solve it...but I can't figure how I'd do it with for loops/nested for loops.
I've got to print Ascii codes in rows of 10
Example:
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
(from 32-122)
Here's my code so far:
public class chars{
public static void main(String[]args){
for( int j = 32; j < 122; j++){
System.out.print((char)j);
//Once above loop is performed 10*...execute a new line..using a for loop..??
System.out.println();
}
}
}
You're outer loop should control what row you're on, and the inner loop what column. Thus, just the outer loop looks like this (there are 9 rows):
for (int i = 1; i <= 9; i++)
{
System.out.println("");
}
This will print 9 newlines, giving you the 9 rows.
Now, your column logic goes inside, but before the println.
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
char print = (char)((i * 10) + 32 + j);
System.out.print(print);
}
System.out.println("");
}
This utilizes a small math trick to generate the numbers of the sequence. Row 1 = 32 to 41, 2 = 42 to 51, etc.
Note also that this is slightly more verbose than other possible answers because I used nested loops like you asked.
A straight forward approach could be to use an if statement as QuakeCore suggested. the code would come to look something like the following:
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char)j);
if (j % 10 == 1) {
System.out.println();
}
}
}
This leaves for some ugly code when working with the Modulus function in the if condition. The reason for it is that we are starting with the number 32 and incrementing from their, thus we get j % 10 == 1 instead of something nicer such as j % 10 == 0.
But, your question states you wish to solve it with For loop inside a for loop, making me think it's a school task. This can be solved by looking at for loops as functions to be performed within the 2D space. Such that the first for loop is handling the rows, while the inner for loop is handling columns (or y and x space respectively). From this we can solve the problem as follows:
public static void main(String[] args) {
// Increment row/counter by 10
for (int row = 32; row < 122; row += 10) {
for (int col = 0; col < 10; col++) {
System.out.print((char)(row + col));
}
System.out.println();
}
}
The syntax for a for loop is:
for ( initialization ; termination condition ; increment ) body
However, each of those items in italics above is optional. The initialization and increment parts can have multiple components, separated by a comma.
Since you know the total number of characters is a multiple of 10, here's what I would do:
public static void main(String[]args){
for( int j = 32; j < 122; /* don't increment j here */){
// print 10 chars per line
for (int col=0; col<10; col++, j++ /* increment j here instead */) {
System.out.print((char)j);
}
System.out.println();
}
}
Note that if the total number of characters wasn't a multiple of 10, then the inner loop might print some extras, since the outer loop's condition is only checked once every 10 characters.
This will print each char 10 times in a row ( with nested for loops ):
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
// print 10 times the same char in the same line
for (int i=0;i<=10;i++){
System.out.print((char) j);
}
// after 10 char : goto next line
System.out.println();
}
}
do it with for loops/nested for loops
Try this-
public static void main(String[] args) {
for (int j = 32; j < 122; j++) {
System.out.print((char) j);
if((j-32)%10==0){
System.out.println();
}
}
}
Here the inner condition will take care of changing line when you have printed 10 values
If you must use nested loops, then maybe something like this would work:
int lineLength = 10;
int lineCount = (122 - 32) / lineLength;
for (int line = 0; line < lineCount; line++) {
for (int column = 0; column < lineLength; column++) {
int index = (line * lineLength) + column;
System.out.print((char)(32 + index) + " ");
}
System.out.println();
}

How to make pattern of numbers in java using only two variables?

#1
#2 3
#4 5 6
#7 8 9 10
#11 12 13 14 15
this is the required pattern and the code which i used is
public class Test{
public static void main(String[] args) {
int k = 1;
for (int i = 0; i <= 5; i++){
for (int j = 1; j <= i; j++){
System.out.print(k + " ");
k++;
}
System.out.println();
}
}
}
as you can see i used the variable k to print the numbers.
My question is that is there a way to print the exact same pattern without using the third variable k?
I want to print the pattern using only i and j.
Since this problem is formulated as a learning exercise, I would not provide a complete solution, but rather a couple of hints:
Could you print the sequence if you knew the last number from the prior line? - the answer is trivial: you would need to print priorLine + j
Given i, how would you find the value of the last number printed on i-1 lines? - to find the answer, look up the formula for computing the sum of arithmetic sequence. In your case d=1 and a1=1.
You can use this:
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print((i * (i - 1)) / 2 + j + 1 + " ");
}
}
}
Or you can the find the nth term and subtract it each time:
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(((i * (i + 1)) / 2) - (i - j) + " ");
// k++;
}
System.out.println(" ");
}
}
You can use
System.out.println((i+j) + " ");
e.g.
i j (i+j)
0 1 1
1 1 2
2 1 3
2 2 4
..........

Categories