java nested for loop spaces and numbers - java

I can't seem to figure out how to figure this problem out. I want to add a number and remove a space on each line working down from 1.
for (int line = 1; line <= 5; line++) {
for (int space = 5; space >= line + 1; space--) {
System.out.print(" ");
}
System.out.println(line);
}

The trick to your problem is recognizing that 5 characters need to be printed on each line. Each digit is printed the same number of times it represents, with spaces filling in the rest.
for (int i=1; i <= 5; i++) {
// print 5 minus i spaces
for (int j=5; j >= i + 1; j--) {
System.out.print(" ");
}
// repeat the ith digit i times
for (int k=0; k < i; ++k) {
System.out.print(i);
}
System.out.print("\n");
}
Output:
1
22
333
4444
55555
But note that you could even simplify this further, if you want fewer lines of codes, to this:
for (int i=1; i <= 5; ++i) {
String line = new String(new char[5-i]).replace("\0", " ") +
new String(new char[i]).replace("\0", String.valueOf(i));
System.out.println(line);
}

Try this
for (int line = 1; line <= 5; line++) {
for (int space = 5; space >= line + 1; space--) {
System.out.print(" ");
}
for (int k = 0; k < line ; k++) {
System.out.print(line);
}
System.out.println("");
}

Related

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

How do i draw an Arrow in Java?

Here is what I am trying to create:
*
**
***
****
*********
****
***
**
*
Here is what i have created:
*
**
***
****
**********
****
***
**
*
Here is my code:
for(int i = 1; i <= 5; i++){
for(int j = 1; j<=i; j++){
System.out.print("*");
}
System.out.println();
if(i == 4){
for(int f = 0; f < 5; f++){
System.out.print("*");
}
}
}
for(int i = 1; i <= 5; i++){
for(int j = 4; j>=i; j--){
System.out.print("*");
}
System.out.println();
}
I dont know how to indent the tail part, please dont give me the answer, just tell me where the problem is and I will try to do it. Thank you!
Given the shape you have provided, and assuming it's going to be output in a monospace font, we can draw it on a grid.
Splitting it visually into 2 sections, we can see that there are 2 main modes.
The tail (green), and the head (red).
There's also a second mode. where the number of stars in the head increase and decrease.
The size of the tail could potentially vary, as could the size of the head, and it would still be a shape we recognise as an arrow.
When outputting text, the easiest iteration order is generally left to right, up to down, unless dealing with right to left languages, or vertical reading, I'm going to assume western culture for the output, as that is what's been popularised in programming output streams.
So, the question is, how best to build up the strings required for output.
Given the format that the output is going to be on a stream,
width is going to be your outside loop, and tail/length your inside loop.
The code you provided uses 10 for width, by splitting it into 2 groups of 5, with the second one being offset by one.
for(int i = 1; i <= 5; i++){
for(int j = 1; j<=i; j++){
System.out.print("*");
}
System.out.println();
if(i == 4){
for(int f = 0; f < 5; f++){
System.out.print("*");
}
}
}
for(int i = 1; i <= 5; i++){
for(int j = 4; j>=i; j--){
System.out.print("*");
}
System.out.println();
}
so translating your code back to the drawings, you loop over width, and on the last iteration output the line of stars for the tail.
What you need to do, is output a space on all other lines.
There are a variety of ways to do so, you could output the character, or use one of the fixed width formatting functions using printf.
But given your current code, the minimal difference will be to output a space character, when the width iteration for the increasing mode is not 4, and for the loop of width - 1.
Looking at your end result, your tail is being printed after your head. That needs to move earlier.
Your tail is too long, need to offset that by 1.
And you need to insert pink and brown sections by printing spaces, the same amount of times as you output the tail, whenever you do not output the tail.
You should add another inner for-loop that prints " " before the for-loop that prints "*".
You can use printf method to tell Java print in specific format. For example, you need 5 spaces prefixed then print your text:
System.out.printf("%5s","hello");
To get your desired output, try the below code. Note: There may be better solutions.
for (int i = 1; i <= 5; i++) {
if (i != 5) // middle line should not be prefix with spaces
// empty 5 spaces before starting the loop
System.out.printf("%5s", "");
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
}
for (int i = 1; i <= 5; i++) {
// print 5 space before
System.out.printf("%5s", ""); // <== note the printf here with empty string
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}
Here's a method you can use to print the arrow:
private static void printArrow (final int min, final int max, final int tip)
{
final int numSpaces = tip - max - 1;
// print the top
for (int i = min; i <= max; i++)
{
for (int j = 0; j < numSpaces; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
// print the tip
for (int i = 0; i < tip; i++)
{
System.out.print("*");
}
System.out.println();
// print the bottom
for (int i = max; i >= min; i--)
{
for (int j = 0; j < numSpaces; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
}
Call it from main with:
public static void main(String[] args)
{
// this will print the arrow in your question
printArrow(1, 4, 9);
}
Another Example:
printArrow(1, 10, 19);
Outputs:
*
**
***
****
*****
******
*******
********
*********
**********
*******************
**********
*********
********
*******
******
*****
****
***
**
*
Here is my answer. You just need to first insert the space and then print * until you reach the middle line. If you want to make it dynamic, just replace the boundary value for k dynamically the same as the boundary for the f:
public static void main(String[] args) {
int k = 1;
int m = 0;
for (int i = 1; i <= 5; i++) {
m = i - 1;
while (k != 6 && m != 4) {
System.out.print(" ");
k++;
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
k = 1;
}
k = 1;
for (int i = 1; i <= 5; i++) {
while (k != 6) {
System.out.print(" ");
k++;
}
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
k = 1;
}
}
EDIT
I realized the output is one* behind. So just need to change the boundary value of k from 5 to 6 (from the value of boundary for f to the value of boundary for f+1)
The output looks like this:
for (int i = 1; i <= 5; i++) {
if (i!=5) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if (i == 4) {
for (int f = 0; f < 5; f++) {
System.out.print("*");
}
}
}
for (int i = 1; i <= 5; i++) {
System.out.print(" ");
for (int j = 4; j >= i; j--) {
System.out.print("*");
}
System.out.println();
}

Nested for loops 0123

I need to create a nested for loops that gives the following output,
0
1
2
3
This is what I have, but for the second test, userNum is replaced by 6 and obviously my code fails.. help?
public class NestedLoop {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
int j = 0;
for(i = 0; i <= userNum; i++){
System.out.println(i);
for(i = 1; i <= userNum; i++){
System.out.println(" " +i);
for(i = 2; i <= userNum; i++){
System.out.println(" " +i);
for(i = 3; i <= userNum; i++){
System.out.println(" " + i);
}
}
}
}
return;
}
}
I think (it's a guess, though) that you're looking for this.
public static void main (String [] args)
{
int limit = 6;
for(int i = 0; i <= limit; i++)
{
for(int j = 0; j < i; j++)
System.out.print(" ");
System.out.println(i);
}
}
The reason why your approach fails is, as I see it, that you are looping through the numbers to show (which is right) but you fail to loop up on the number of spaces (which I resolved by relating the inner loop's limit to the outer loop's current value.
Let's talk a bit about what your intention is with these loops.
The inner loop is meant to produce an arbitrary number of spaces, depending on what number you're iterating on. So if you're on number 0, you produce no spaces, and if you're on 1, you produce one space, and so forth. The other caveat is that they all must appear on the same line, so System.out.println is the incorrect choice.
You would want to use System.out.print to print out the spaces. So let's write that.
for(int j = 0; j < 6; j++) {
System.out.print(" ");
}
This will print out six spaces unconditionally. What that condition is depends on the current number we're iterating on. That comes from your outer loop.
You only need to define a loop that starts from an arbitrary starting point - like 0 - and then loop until you are at most your ending number. For this, your current loop is sufficient:
for(i = 0; i <= userNum; i++) {
}
Now, we need to bring the two pieces together. I leave the figuring out of the question mark and what to print after you've printed the spaces as an exercise to the user, bearing in mind that you must stop printing spaces after you've reached your number.
for(int i = 0; i <= userNum; i++) {
for(int j = 0; j < ?; j++) {
System.out.print(" ");
}
}
Let's analyse the task
In every line, we should print a number and different number spaces in the front of the number.
For that, we need two loops - one outer to iterate from 0 to N and one inner to add spaces in front of the number.
private static void method1(int userNum) {
int nummSpaces = 0;
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < nummSpaces; j++) {
System.out.print(" ");
}
nummSpaces++;
System.out.println(i);
}
}
In this solution, we have variable numSpaces which used to count the number of spaces in front of the number. It is unneeded - we can use variable i for that purpose.
private static void method2(int userNum) {
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
}
Let's analyses once again the output
- the fist line: printed zero spaces and number 0
- the second line: printed one space and number 1
- the third line: printed two spaces and number 2
- and so on
Finally, we can use just one variable, which contains spaces and after that print the length of it:
private static void method3(int userNum) {
for (String spaces = ""; spaces.length() <= userNum; spaces += " ") {
System.out.println(spaces + spaces.length());
}
}
C/C++
#include <iostream>
using namespace std;
int main() {
int userNum;
int i;
int j;
cin >> userNum;
for (i = 0; i <= userNum; ++i) {
for (j = 0; j < i; ++j) {
cout << " ";
}
cout << i << endl;
}
return 0;
}

Output of 50 - broken up to 10 numbers per line

I am struggling trying to find a way to output this array/loop so that only 10 outputs appear on a line.
public static void main(String[] args) {
double [] alpha = new double[50];
int num=1;
for (int i=0; i < alpha.length; i++) {
alpha[i] = num; //populate index 0-50 w/ 1-50
num++;
if (alpha[i] < 26) // first 25, print ^2
System.out.print(Math.pow(alpha[i],2)+ " ");
else // last 25, print value(3)
System.out.print(alpha[i]*3 + " ");
}
System.exit(0);
}
Add a conditional that prints a break line if i + 1 is multiple of 10.
for (int i=0; i < alpha.length; i++) {
//your code here...
if ( (i + 1) % 10 == 0) {
System.out.println();
}
}
Another way of doing it could be to iterate over the lines u want to print:
// Get the total number of lines you want
int lines = len(alpha) % 10;
for (int i=0; i < lines; i ++) {
for (int j = i * lines; j < i * lines + 10; j++) {
// Print the modified alpha[j]
System.out.print(alpha[j]);
}
System.out.println();
}

Print a diagonal triangle in java

I need to print out a triangle that looks like this:
*
**
***
****
The code I have right now
for(line = 0; line < size; line++){
for(count = 0; count < line; count++){
System.out.print("*");
for(space = 0; space < line; space++)
System.out.print(" ");
}
System.out.println();
}
I get this
*
**
***
****
*****
******
for(line = 0; line < size; line++){
for(space = 0; space < line; ++space)
System.out.print(" ");
for(count = 0; count < line; count++)
System.out.print("*");
System.out.println();
}
You're printing the spaces on the same line. Call System.out.println(); before printing the spaces.
Edit - Example:
for (line = 0; line < size; line++){
for(space = 0; space < line - 1; space++)
System.out.print(" ");
for (count = 0; count < line; count++)
System.out.print("*");
System.out.println();
}
You need to first print the prefix spaces. and then print the stars.
Have a try with this:
int line = 0;
int size = 6;
int count = 0;
int space = 0;
for (line = 0; line < size; line++) {
//print spaces
for (space = 0; space < line; space++)
System.out.print(" ");
//Print stars
//Note: here count condition should be count < line+1, rather than count < line
//If you do not do so, the first star with print as space only.
for (count = 0; count < line+1; count++) {
System.out.print("*");
}
System.out.println();
}
Output in console:
*
**
***
****
*****
******
class Pyramid
{
public static void main(String args[])
{
java.util.Scanner pyr=new java.util.Scanner(System.in);
System.out.println("type a no. to make Pyramid");
int n= pyr.nextInt();
for (int i=1; i<=n; i++)
{
for(int j=n; j>i; j--)
{
System.out.print(" ");
}
for(int k=1; k<=i; k++)
{
System.out.print("* ");
}
System.out.println();
}
}
Just printing the spaces before the asterisks would be fine.

Categories