Nested Loops - A Third One? - java

Write a program that prints the following on the Screen:
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10
3 4 5 6 7 8 9 10
4 5 6 7 8 9 10
5 6 7 8 9 10
6 7 8 9 10
7 8 9 10
8 9 10
I'm having a little trouble correcting the nested loops - I have it to look like that, the numbers won't stop at 10 though. The code prints this:
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
I'm a beginner programmer and need help with this - do you need a third loop inside of the nested loop already? Any help is appreciated! Here is my code so far:
import java.util.Scanner;
public class LoopProgram
{
public static void main(String args [])
{
for (int e=0; e<8; e++)
{
for (int f=1; f<=10; f++)
{
System.out.print(f + e + " ");
}
System.out.println();
}
}
}

Two loops are enough.
The outer loop runs eight times, you've got that working already.
Your inner loop, however, always runs ten times, which is not what you want. You want the inner loop to run 10 times first, then only 9 times, then only 8 times etc. The trick here is to change the start or end value of that inner loop, like this:
for (int e=0;e<8;e++) {
for (int f=e+1; f<=10; f++) {
...
}
}

I think this is what you are looking for.
for(int e=1;e<9;e++) {
for(int f=e;f<=10;f++) {
System.out.print(f+" ");
}
System.out.println();
}
This ouputs exactly what you asked.

Try this for the second loop:
for(int f=e;f<=10;f++)
and for output
System.out.print(f+" ");

Here's how I would do it
for (int i = 1; i <= 8; i++) {
for (int j = i; j <= 10; j++)
System.out.print(j + " ");
System.out.println();
}

Three loops is severe overkill. This can be done with a single loop and two counters.
public class LoopProgram {
static final int LIMIT_1 = 8;
static final int LIMIT_2 = 10;
public static void main(String[] args) {
int a = 1, b = 2;
while(b <= (LIMIT_1 + 1)) {
System.out.print(a);
if(a < LIMIT_2) {
System.out.print(" ");
a++;
} else {
System.out.println();
a = b;
b++;
}
}
}
}

You only need two loops:
The outer one will run eight times and the inner one will begin at the value of the outer counter (thats what makes each line count up to ten but always start at the first value of last line + 1) and run while it's counter is less than 10.
Something like that:
for (int i = 0; i < 8; i++) {
for (int e = i; e < 10; e++) {
//print e + 1
}
}
You have to print e + 1 so that your lines do not begin at 0, but at one, going up to 10.

This is more of an explanation of how to work this sort of thing out for yourself. In the commonest cases of a for-loop, you should ask yourself three questions about the index variable:
What is the first value I want it to have?
Under what conditions do I want to do another iteration?
How should it change from iteration to iteration?
For your inner loop, the answers are:
e
f <= 10
f++
From that, it is easy to construct the loop, and you already have several examples of it written for you.

Related

dividing matrix into four sub-blocks

i want devide matrix into four sub-blocks equally by vertically and horizontallty in java (Here, we suppose that m and nare even numbers) .
for example we have matrix:
1 2 3 4 5 6
7 8 9 1 2 8
1 2 3 4 5 6
4 5 6 7 8 9
1 4 7 2 5 8
3 6 9 7 2 5
I want to display the last block that is:
7 8 9
2 5 8
7 2 5
how i can resolve this problem in java.
Iterate over the lower-right part of the matrix. Here is an example for a square matrix. I am sure you will be able to make it more generic for non-square quadrants or to get other quadrants than the lower-right one.
public int[][] getQuadrantOfSquareMatrix(int[][] matrix) {
int newDimension = matrix.length / 2;
int[][] toReturn = new int[newDimension][newDimension];
for (int i = 0; i < newDimension; i++) {
for (int j = 0; j < newDimension; j++) {
toReturn[i][j] = matrix[i + newDimension][j + newDimension];
}
}
return toReturn;
}

Incrementing 2D Arrays vertically and horizontally?

I am trying to make a method where a 2D array is created in the main, which can be any dimension. After that, we are supposed to make 2 methods, one which increments each next value in the array by a given number labeled step. One method is supposed to increment the rows, and the other increments it by columns.
This is what I have:
public static void main (String [] args){
int [][] fillRightArray = new int [5][8];
fillRight(fillRightArray, 2);
int [][] fillDownArray = new int[5][8];
fillDown(fillDownArray, -2);
For the fill right method, this is the what the output should be:
2 4 6 8 10 12 14 16
18 20 22 24... //all the way to 80, since the array has 40 elements (40*2=80)
This is my method:
public static void fillRight (int [][] fillRightArray, int step){
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
fillRightArray[i][j] += step*(j+1);
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
But for some reason, my output is:
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
Any idea as to why this is happening? Same thing happens when I go with the fillDown method, the output is supposed to be:
2 12 22....
4 14 24....
6 16 26....
8 18 28....
10 20 30.... all the way to 80
But instead I get:
2 2 2 2 2
4 4 4 4 4
6 6 6 6 6
8 8 8 8 8
10 10 10 10 10
Your code doesn't work because you aren't taking into account the previous cell.
Your logic for determining the value of a specific cell is fillRightArray[i][j] += step*(j+1); .
This line only considers the value of j to determine the value of a cell within your array, when it should also consider the value of i (explicitly or implicitly).
You should add a counter that keeps track of how many cells you have set, and set the next cells value based on the number of cells that have already been set.
Your fillRight method should instead look like this:
public static void fillRight (int [][] fillRightArray, int step){
int count = 0;
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
count++;
fillRightArray[i][j] += step*count;
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
}
You're constantly repeating the same work and going back to 0 each time.
In your fillRight, each row is doing 2,4,6,8,10 because you're doing step*(j+1), where j resets to 0 after each iteration of the loop. You need to find a way to include i as well as j when setting the value, or just have a counting variable that is incremented each step
Like this:
step += 2
fillRightArray[i][j] = step
That way you don't need to worry about position.

How can I stack up the number patterns with while loop in java?

Dear Professionals!
I'm a super beginner of programming java.
I'm just learning a basic stuff in school.
While I'm doing my homework, I'm stuck in one problem.
The question is Using nested loops to make this stack-up number pattern:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
I can only use while loop (because we haven't learned for or do loops yet), and the outer loop body should execute 10 times.
I can use print and println for making this pattern.
I tried many different methods with while loop, but I can't figure it out.
Please, please give me some hint.
This is the code that I'm working on it so far:
class C4h8
{
public static void main(String[] args)
{
int i, j;
i = 1;
while(i <= 10)
{
j = 1;
while (j <= 10)
{
System.out.print(j);
j++;
}
System.out.println();
i++;
}
}
}
but it only displays:
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
12345678910
My question may look like a silly one, but I'm really struggling with it because like I mentioned, I'm a super beginner..
Please help me, so that I can learn and move on!
Thank you so much!
Use the following: You need to limit the variable j by variable i to achieve your output
class C4h8
{
public static void main(String[] args)
{
int i, j;
i = 1;
while(i <= 10)
{
j = 1;
while (j <= i) // limit the variable j by i
{
System.out.print(j+" ");
j++;
}
System.out.println();
i++;
}
}
}
In less code with while loop
int i = 0;
int limit = 10;
while(++i <= limit){
int j = 0;
while(++j <= i)
System.out.print(j+" ");
System.out.println();
}

Trouble formatting with 2-dimensional array matrices

I need my matrices to look exactly like this.(with numbers lined up under text)
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
The results I am currently getting look like.
Here are the two matrices, and the result when added:
8 5 6 6 3 8 2 3 11 13 8 9
7 7 4 5 4 9 2 1 11 16 6 6
9 4 4 8 5 1 1 1 14 5 5 9
4 2 7 7 + 7 9 1 3 = 11 11 8 10
4 3 5 3 5 6 8 7 9 9 13 10
4 2 2 1 3 9 5 5 7 11 7 6
As you can see the code for the arrays sum is shifted to the right, and I am not quite sure how to fix this.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < array1.length; i++) {
// For loop to print out array 1 and add string, if to place +
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", array1[i][j]);
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%4s", '+');
}
}
System.out.print("\t");
// For loop to print out array2 and equals string, if to place =
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%2s", array2[i][j] + " ");
if (i == array1.length / 2 && j == array1[i].length-1) {
System.out.printf("%1s", '=');
}
}
System.out.print(" ");
// For loop to print out sum of array1 + array2
for (int j = 0; j < array1[i].length; j++) {
System.out.printf("%4s", sum[i][j]);
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Also a 3x3 array when printed out looks like.
Here are the two matrices, and the result when added:
2 2 7 3 4 3 5 6 8
4 4 8 + 6 8 5 = 7 9 13
1 9 3 6 8 6 7 7
I think this is meant to insure that numbers, when printed, always take up 2 spaces:
System.out.printf("%2s", array2[i][j] + " ");
But because of the added (technically, concatenated) " ", you get a string that is bigger than the %2s field, so there is no padding of short numbers.
Plus, you have code to decide when to print the + & =, but each should be deciding between printing the symbol and printing a space, to keep everything lined up.

Increasing skips in Josephus

Here is one solution to the Josephus problem (where people are arranged in a circle and every other person is killed until only one remains):
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
ArrayList<Integer> chairArr = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
chairArr.add(i);
}
int result = 0;
for (int i = 1; i < chairArr.size() - 1; i = i + 2) {
chairArr.add(chairArr.get(i));
result = i;
}
System.out.print("Result: " + chairArr.get(result));
}
}
But what if, instead of skipping every other person, we increased the number skipped as we went through? That is, if 10 people were arranged in the circle, persons 1, 3, 6, 10, etc. were killed in that order. I think the modification would come in the i = i + 2 in the for loop, but I'm not sure.
I worked it out on paper, and this is the order of elimination, where asterisks denote the number to be removed:
0 *1* 2 3 4 5 6 7 8 9 10
1 2 *3* 4 5 6 7 8 9 10
2 2 4 5 *6* 7 8 9 10
3 2 4 5 7 8 9 *10*
4 2 4 5 7 *8* 9
5 2 4 5 7 *9*
6 2 4 *5* 7
7 *2* 4 7
8 *4* 7
9 7 <-- Result
Thoughts?
Edit: Tried this modification of the for loop:
for (int j = 2; j < chairArr.size() - 1; j++) {
for (int i = 1; i < chairArr.size() - 1; i = i + j) {
chairArr.add(chairArr.get(i));
result = i;
}
}
This won't work because after the initial pass where j = 2, the inner loop will already have narrowed the list down to one candidate so the outer loop never completes.

Categories

Resources