draw figure(numbers) with for loops - java

I'm just getting started with Java and my teacher asked me to draw the following shape of numbers:
123456654321
2345665432
34566543
456654
5665
66
5665
456654
34566543
2345665432
123456654321
image
So far I was able to draw first line and part of the middle using this code:
int sz = 6;
for (int i =1;i<=sz;i++)
System.out.print(i);
for(int j =sz;j>1;j--)
System.out.print(j);
for(int i =1; i<=sz;i++){
System.out.println(i);
for(int j=0;j<=i;j++){
System.out.print(" ");
}
}
I'm having trouble the rest of the middle body.
Can anyone help me out drawing that one, by using nested for loops?

You have to go line by line,because after println(),you cannot go back there.
For the upper half of the pattern you can use this.
int sz = 6;
for(int d = 1;d<=sz;d++){
for (int i = d;i <= sz;i++) //for increasing numbers
System.out.print(i);
for(int j=sz;j>=d;j--) //for decreasing numbers
System.out.print(j);
System.out.println(); //for newline
for(int m=0;m<d;m++) // for spaces
System.out.print(" ");
}

First you build an array, then traverse the lines and build them:
int currentItem = 1;
int items[] = new int[12];
for (int index = 0; index < items.length; index++) {
items[index] = (index < 6) ? currentItem++ : currentItem--;
}
for (int index2 = 0; index2 < 12; index2++) {
String line = "";
int limit = (index2 < 6) ? index2 : (12 - index2);
for (int index3 = 0; index3 < items.length; index3++) {
line += ((index3 >= limit) && (index3 < items.length - limit)) ? " " : items[index3];
}
System.out.println(line);
}

Related

Using nested For Loops to create a table of numbers and stars

I need to print a table that looks like this if the user entered a 5 using nested for loops:
****5
***45
**345
*2345
12345
I've been working on this for hours and the closest I got was:
int size = scan.nextInt();
for (int i = 1; i <= size; i++)
{
for (int star = size-1; star >= i; star--)
System.out.print("*");
for (int k = 1; k <= i; k++)
System.out.print(i);
System.out.println();
}
Which outputs this:
****1
***12
**123
*1234
12345
You have too many loops; I find it easier to reason about zero based looping so I'm going to use that. Iterate i and j from 0 to size. If j + 1 is greater than size - i - 1 then we want to print j + 1. Otherwise, we want a star. Like,
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (j + 1 > size - i - 1) {
System.out.print(j + 1);
} else {
System.out.print('*');
}
}
System.out.println();
}
For size = 5 that outputs (as requested)
****5
***45
**345
*2345
12345
If you simply must have one based indices, that would be
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
if (j > size - i) {
System.out.print(j);
} else {
System.out.print('*');
}
}
System.out.println();
}
If you want to keep your loops and avoid if statements, you can tweak last loop by changing
for (int k = 1; k <= i; k++)
into
for (int k = 1+size-i; k <= size; k++)
Btw I also find it way easier to start loops from 0, so updated code would look like this:
int size = scan.nextInt();
for (int i = 0; i < size; i++)
{
for (int star = size-1; star > i; star--)
System.out.print("*");
for (int k = size-i; k <= size; k++)
System.out.print(k);
System.out.println();
}
I hope it helps

My X's are being placed 1 space off in my histogram

import java.util.*;
public class HistogramGenerator {
public int getHeightOfHistogram(int[] occurences) {
// occurences = {1,0,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0]
int max = occurences[0];
for (int i = 1; i < occurences.length; i++) {
if (occurences[i] > max) {
max = occurences[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line: ");
String sentenceEntered = sc.nextLine();
System.out.println("Letter Histogram");
HistogramGenerator histogram = new HistogramGenerator();
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Map of all the characters
int[] occurences = new int[letters.length()]; //max size of all possible matches
// loop through sentenceEntered to find occurences of each character
for (int i = 0; i < sentenceEntered.length(); i++) {
int charValue = sentenceEntered.charAt(i);
int index = letters.indexOf(charValue); // index of the character we are searching for
if (index < 0)
continue;
occurences[index]++;
}
int heightOfHistogram = histogram.getHeightOfHistogram(occurences);
String[][] histogramArray = new String[heightOfHistogram][letters.length()]; //[2][26]
for (int j =0; j < occurences.length; j++) {
int numXtoInsert = occurences[j];
while(numXtoInsert > 0){
histogramArray[heightOfHistogram - numXtoInsert][j] = "X";
numXtoInsert--;
}
}
// print 26 dashes (length of letters)
for(int k=0; k < letters.length(); k++){
System.out.print("-");
}
System.out.println();
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print("");
continue;
}
System.out.print(histogramArray[row][col] + " ");
}
System.out.println();
}
System.out.println();
// print 26 dashes ( length of letters)
for(int u=0; u < letters.length(); u++){
System.out.print("-");
}
System.out.println();
// print all characters in letters
System.out.print(letters);
}
}
basically whatever word i put in it prints out something close to it, but not really correctly, if i type in apple for example it'll print out an X close to A, and X on P and an X close to P, and and X close to l and E.
maybe there's something wrong with the logic? I don't know, need some quick help!
The issue is with the printing logic. When you find a null value, you need to print a space. When you don't find a null value, you should not add an extra space. See below for the updated working logic:
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print(" ");
continue;
}
System.out.print(histogramArray[row][col]);
}
System.out.println();
}
System.out.println();

replace every second line of my triangle with a blank line for loops

instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this
5
555
55555
This is my code:
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("5");
}
System.out.println();
}
you need small modification in your code and you can get what you want.
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
if(i%2==0)
System.out.print("*");
}
System.out.println();
}
check it out.
Just test for i % 2
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print(i % 2 == 0 ? "*" : " ");
}
System.out.println();
}
edit
If you want to print 5 instead or * then modify the code to use 5
Check this:
int num= 5; // 'num' denotes the number of lines
int numOfSpaces;
for(int i = 1; i <= num; i++) {
if( i%2 != 0) // checks whether the line number is odd. If odd, prints '*'
{
numOfSpaces = (num-i) / 2; // find the number of blank spaces
for(int j = 1; j <= numOfSpaces; j++) {
System.out.print(" ");
}
for(int k = 1; k <= i; k++) { // number of '*'s to be printed = current line number = i
System.out.print("*");
}
System.out.println();
}
else{
System.out.println(); // leaves every second line blank (ie.,if line number is even.)
}
}
//try this code. It may help you to achieve your output
[Check screen shot for the output of the below code][1]
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5 - i; j++)
{
System.out.print(" ");
}
for (int k = 0; k <= i; k++)
{
if(i%2!=0)
{
System.out.print(" ");
}
else{
System.out.print("* ");
}
}
System.out.println();
}
The Code below is Working now.
A simple if condition will solve your problem. Just check if the
value of i is divisible by 2. If it is true then print a
blank line. Else Print * and you are done!
* will be printed on 1st, 3rd and 5th lines.
Blank Space will be printed on 2nd and 4th lines.
public class PrintPattern{
public static void main(String []args){
int lineNo=0; // New Variable for Line Number (Can Use variable 'i' also)
for(int i = 0; i < 5; i++) {
lineNo++;
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
if(lineNo%2!=0){
for(int k = 0; k <= (i*2); k++)
System.out.print('*'); // Will print '*' (or '5') Sequence for Odd Lines - 1st, 3rd, 5th Lines
System.out.println();
}
else
System.out.println();// Will print Blank Line for Even Lines - 2nd and 4th Lines
}
}
}
Try this
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("5"); //Use 5 instaed of * to draw
}
System.out.println();
System.out.println(); //This one will solve your problem
}
Output will be:
5
555
55555
5555555
555555555
I think that you can just enter one more print statement inside the loop:
for(int i = 0; i < 5; i++) {
System.out.println();
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("*");
}
System.out.println();
}
Output
*
***
*****
*******
*********

Printing diamonds from *'s

I am trying to System.out.print() a diamond out of *'s. So far I have spent a good 5 hours on trying to figure out how to reverse print the bottom triangle of the diamond.
I can worry about the spacing to complete the diamond later. (I have it worked for the most part).
If someone could explain to me what I am doing wrong and how the right way works I would greatly appreciate it.
private static void diamond()
{
int numLines = 0;
System.out.println("How many lines would you like in the Diamond?");
numLines = scan.nextInt();
if (numLines / 2 == 0) //if number is even, make odd.
{
numLines++;
}
for(int i = 0; i <= numLines ; i++) // Controls #Lines
{
if(i <= numLines / 2)
{
for(int j = 0; j < i * 2 - 1; j++) // Controls #Stars small upright triangle
{
System.out.print("*");
}
}
else
{
for(int k = numLines; k > i / 2; k--) // Controls # of spaces
{
System.out.print("*");
}
/*for(int j = numLines/2 - i, l = i; l > j; j++) // Controls #Stars small upright triangle
{
String stars = "*";
System.out.print(stars);
}*/
}
System.out.println("");
}
}
`
What happens to your attempt is that you loop through the half (of the lines) of your diamond [the number of lines in second/first half] times.
You'd want to do a if-statement each loop, not an if and a for in each loop
Probably you want this
Just adjust it for user input values
public static void main(String[] args) {
System.out.print("Reverse diamond: \n");
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
System.out.print("\n\nDiamond from starts: \n");
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
}
output:

Asterisk in Nested loops, Java

I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}

Categories

Resources