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++){
Related
Okay, I'm making a program that'll make vertical lines, horizontal lines, diagonals lines too! I'm kinda confused on one of my outputs that doesn't make any sense.
So my psudocode was like this:
//enter a char
//enter a number that will determine how long the line is
//define with easyreader what type of line it will be (hori, vert, diag)
//the idea of making the diag lines was this...
#
(two spaces) #
(four spaces) #
(six spaces) #
//we could use the sum spaces = spaces + 2; to keep on calculating what
//the previous spaces was
Code was:
class starter {
public static void main(String args[])
{
System.out.print("What char would you like? ");
EasyReader sym = new EasyReader();
String chars = sym.readWord();
System.out.print("How long would you like it to be? ");
int nums = sym.readInt();
System.out.print("Diag, Vert, or Hori? ");
//you want to read the __ varible, not the sym.readX()
String line = sym.readWord();
System.out.println("");
System.out.println("");
if(line.equals("Hori")){
for(int x = 0; x < nums; x++){
System.out.print(chars + " ");
}
}
else if(line.equals("Vert")){
for(int y = 0; y < nums; y++){
System.out.println(chars + " ");
}
}
else{
for(int xy = 0; xy < nums; xy++){
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}
}
}
}
}
At the bottom you will see a for loop called xy that will read how long the lines would be. Under that for loop would control the spaces. However, for some reason, the sum isn't updating correctly. The output is always:
2 (char)
5 (char)
8 (char)
2 (char)
5 (char)
8 (char)
...
The output should be:
2 (char)
4 (char)
8 (char)
...
EDIT **********
Since I need help now changing incriements here is an example (So I don't have to explain it a lot in comments)
Example: If user puts he wants the line as much as 5 units. With two for loops, one controlling how many spaces he wants, one controlling how many chars will print out, the output would be then 2, 4, 6, 8, 10.
In for loop statement, you say 'increase spaces by one after each iteration' (spaces++):
for(int spaces = 0; spaces < nums; spaces++){
In the body of your loop, you additionally ask to increase it by 2:
spaces = spaces + 2;
So each iteration it gets increased by 3.
By the way, there seems to be something wrong with your nested loops (if I understand the intention correctly). If the outer loop (looping over xy) draws a line on each iteration, then the inner loop, which is supposed to output an indent for the current line, must be bounded by xy (multiplied by 2) rather than nums. I'd write it like this:
for (int xy = 0; xy < nums; xy++) {
for (int spaces = 0; spaces < xy*2; spaces += 2) {
System.out.print(" ");
}
System.out.println(chars);
}
Because you are adding 3 to the spaces each time
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
spaces++ spaces += 1
spaces = spaces + 2; spaces += 2
actually the problem is in this part :
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}
when the program starts we have spaces = 0
then this part is going to run spaces =spaces + 2
now spaces is equal to 2, so we have spaces = 2
the program prints 2, after that spaces increments by 1 using spaces++ part
now spaces is equal to 3, which means spaces=3
after that this line is going to be run spaces = spaces + 2
so the value of spaces becomes 5
and if we do this for ever and ever we will have this sequence of numbers :
2 5 8 11 14 ....
in fact this is because we are incrementing spaces by 3 in each iteration
if you modify your code in this form, the problem is going to be solved :
for (int xy = 0; xy < nums; xy++) {
for(int spaces = 0; spaces < xy*2; spaces += 2)
System.out.print(spaces + " ");
System.out.println(chars);
}
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.
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.
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();
}
}
}