Hey I have a question I have been trying to figure out for a couple hours now, I need to use nested loops to print the following
-----1-----
----333----
---55555---
--7777777--
-999999999-
This is what I have so far.
public static void Problem6 () {
System.out.println("Problem 6:");
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= 9; j += 2) {
System.out.print(j);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
This is what it prints
-----13579-----
----13579----
---13579---
--13579--
-13579-
You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:
Which loop prints out the numbers?
The 2nd nested for loop.
What does it do?
It prints out j where j ranges from 1 to 9 and j is incremented by 2 each iteration of the loop. In other words, 1, 3, 5, 7, 9, which is confirmed in your output
What do you want it to do?
Well let's look at the desired output. You want 1 to be printed once on the first first line. You want 3 to be printed three times on the third next line. You want 5 to be printed five times on the fifth next line after that. And so on.
Do you notice a pattern? You want that loop we mentioned above to print the same number (1, 3, 5, ... i) as the number of times (1, 3, 5, ... i).
edit Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still 3 three times, 5 five times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.
Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.
These for loops
for(int i=1;i<=9;i+=2)
{
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
System.out.println();
}
print
-----1-----
----333----
---55555---
--7777777--
-999999999-
public class pattern
{
public static void main ( )
{
for (int i = 1;i<=9;i+=2)
{
for(int b = 9;b>=i;b-=2)
{
System.out.print(" ");
}
for(int j =1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
Related
I just started learning about "nested for loops". But my question what is the nested for loop exactly doing every time it loops? I'm still confused as to what is variable "i" is doing and what is variable "j" is doing. If you can explain what is happening after every loop, it would make nested for loops much clearer.
import java.util.Scanner;
public class LoopStatement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numStar;
System.out.print("Number of stars: ");
numStar = input.nextInt();
while (numStar < 1 && numStar > 20) {
System.out.println("Enter a valid number ");
numStar = input.nextInt();
}
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
So this is the output I get if I input 4 for numStar
*
**
***
****
There is actually nothing special about nested loops, they behave exactly the same like regular loop.
Specifically here the outer loop loops from i being 1 to numStar and therefore prints numStar rows.
The nested loop loops from j being 1 to i where i is the number of current row being printed. In each iteration it prints one star and therefore altogether it prints i stars.
Therefore here it prints 1 star on row number 1, 2 stars on row number 2, etc.
Try writing down in a paper like this :
i=1 j=1 => *
i=1 j=2 => (j<=i) is false
.
.
i=2 j=1 => *
*
i=2 j=2 => *
**
.
.
You'll get the output if you try to write it in a paper.
In order to understand the nested loop you must understand the for structure. It sounds like you did not get it.
from the basics:
for (int i = 1; i <= numStar; i++) {
System.out.println(i);
}
the code above iterate exactly numStart following the steps:
a-Starts with i=1: int i = 1
b-Test condition: i <= numStar
c-Print the value of i in the screen: System.out.println(i)
d-increments i value: i++
It execute while the conditions is satisfied: i <= numStar. The steps c and d are executed only the condition is satisfied.
the tested loop follows the same logic:
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
when i=1 -> j iterates from 1 to 1. So it prints "*"
when i=2 -> j iterates from 1 to 2. So it prints "**"
when i=3 -> j iterates from 1 to 3. So it prints "***"
and so on...
After the nested iteration finish there is line break: System.out.println();
I'm having trouble figuring out This last pattern in a java assignment. I know I'm close but I can't figure it out here's my code:
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
int x = 6; // Counter?
for (int j = 1; j<=i; j++){ //column
System.out.print("");
x--;
}
for(int k=1;k<=i;k++) {
System.out.print(x);
}
System.out.println();
}
}
I understand that the outer loop is the rows and the inner the columns, but that's not the part I have wrong. My pattern it self is right but not the out put of the numbers.
I can't put my output on here because it won't format right. But if you copied my code exactly instead of a line of 0,then 1, then, 2... etc, I'm trying to get 1 2 3 4 5 6 on the top line, then 1 2 3 4 5, the next line and so on...
You were actually very close to the correct pattern, you just added a little too much. As a general tip (not always but most of the time), when making these loop patterns you can usually print these patterns using the integers in your loops. I changed your code a little bit to give you the pattern you wanted. You didn't need x as a counter because you can just use your deepest nested loop's integer as a counter, which in how I just adjusted your code is j because it will run for 6 times on the first then 5 on the second and so on. Another extra part that you added was the 3rd nested loop. It essentially did the exact same thing that the 2nd loop does because they both had the condition of running while they were less than i. Well here is the code; I hope my explanation helped.
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
for (int j = 1; j<=i; j++){ //column
System.out.print(j);
} System.out.println();
}
}
Here is your expect code:
import java.util.*;
public class Test{
public static void main(String[]args){
System.out.println("Pattern D:");
for(int i=6 ;i >= 1;i--){
int k=i;
for (int j=1 ;j<=k; j++){
System.out.print(j);
}
System.out.println();
}
}
}
Turns out I said what I was trying to do earlier wrong. I wanted to right justify the pattern but here is my solution. Sorry for any confusion.
for (i=6;i>0;i--) {
x=6;
for (j=i;j<6;j++) {
x--;
System.out.print(" ");
}
for(k=1;k<=i;k++) {
System.out.print(x--);
}
System.out.println(" ");
}
public class TestPattern {
public static void main(String[] args) {
for (int i = 6; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Output:
123456
12345
1234
123
12
1
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){
Guys i would like to ask how to get rid of the "and" print on my loop
2 and 4 and <
public static void main(String[] args) {
Methods(5);
}
public static void Methods(int a){
int loops = a/2;
int even = 0;
for(int i = 0; i < loops; i++){
even+=2;
System.out.print(even+" and ");
}
}
it prints
2 and 4 and <<<
Instead i want
2 and 4 <<<
thank you.
Please help me i am beginner T_T
You can do:
public static void Methods(int a){
int loops = a/2;
int even = 0;
for(int i = 0; i < loops; i++){
even+=2;
System.out.print(even);
if (i < loops - 1) {
System.out.print(" and ")
}
}
In other words: as long as i is smaller than loops - 1 (which holds during your entire loop except the last step) you would print out " and ". This ensures the last and is not printed when it goes through the loop the last time.
Test if your index is the last index you would be on, i.e. if i == loops - 1. If so, then just print even instead of even + " and ".
Before entering the loop check if there is an element, print just the first element. Increment i and then for each remaining element always pre-pend " and " first.
int i = 0;
if (i < loops) {
even+=2;
System.out.print(even);
}
i++;
for(; i < loops; i++){
even+=2;
System.out.print(" and " + even);
}
This way you avoid all the checking inside the loop.
I'm a beginner in java & I really need this answer.
I have been trying to create a triangle in this sequence:
1
21
321
4321
54321
Even though my syntax is correct, I have been going through logical errors with non-terminating loops.
This is the program which I'm trying to fix:
for(i=1;i>=1;i++)
{
for(j=i;j<=i;j=j-1)
{
System.out.print(j);
}
System.out.println();
}
Help would really be appreciated for this.
You get non-terminating loop because of this
for(i=1;i>=1;i++)
The code means, you want to loop the body if i greater or equal than 1 (i>=1), and this i value are always incremented by 1 (i++) for each loop, so it always have value greater than 1 and this condition is always correct for the loop code. So you must correct the loop statement.
I am not sure I fully understood your problem but
the following code created a nice triangle for me.
int i,j;
for(i = 1; i>= 1 && i < 10; i++)
{
for(j = i; j <= i && j > 0; j = j - 1)
{
System.out.print(j);
}
System.out.println();
}
for(i=1;i>=1;i++) is not correct in this since increment on 1 will always result in number greater than 1 so the loop will end only after i = (2^31 -1) iterations. So for given output your loop should look like this:
for(int i=1;i<=5;i++)
{
for(int j=i;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
Running through the loop
for(j=i;j<=i;j=j-1) (assume i is 2 for the example)
j=2, is 2<=2, yes:run loop
j=j-1 (j=2-1=1)
j=1, is 1<=2, yes:run loop
j=j-1 (j=1-1=0)
j=0, is 0<=2, yes:run loop
j=j-1 (j=0-1=-1)
j=-1, is -1<=2, yes:run loop
j=j-1 (j=-1-1=-2)
etc
j is getting smaller and smaller so it will always be less than 2.
i has exactly the reverse problem, its always getting bigger so it will always be greater than 1.
public static void main(String[] args)
{
for(int x=1;x<=5;x++)
{
for(int j=x;j>=1;j--)
{
System.out.print(j);
}
System.out.println();
}
}