Print a triangle of number - java

How can I print this?
1
1 2
1 2 3
1 2 3 4
I tried this but it doesn't work
public static void printNumber(int x) {
for (int i = 1; i <= x; i++) {
System.out.println(i);
System.out.println(i + " " +(i + 1));
}
}

2 for loop is a good solution .but if you want by just one loop.you can use string concatenate like this .but string concatenate inside a big loop is not good.string builder can be used instead string
String s="";
for (int i = 0; i <= 3; i++) {
s += " " + (i + 1);
System.out.println(s);
}
output
1
1 2
1 2 3
1 2 3 4

Just call your print statement once for each line of output you want. For each line, create or clear a StringBuilder and populate it with the numbers, with a space after each number, then call System.out.println(sb.toString());
for(int i = 1; i <= 4; i++)
{
StringBuilder sb = new StringBuilder();
for(int j = 1; j <= i; j++)
{
sb.append(j);
sb.append(" ");
}
System.out.println(sb.toString());
}
gives the following:
1
1 2
1 2 3
1 2 3 4

Use two loops to print it.
1) First to control the number of rows.
2) To print the numbers.
for(int x=1;x<=4;x++){
for(int y=1;y<=x;y++){
System.out.print(y+" ");
}
System.out.println("");
}

Related

Generate a number-pattern in Java beginning with different numbers

I am preparing for my exam from programming. And I am stuck on this task, I understand logic of patterns ( at least I think so ) but I can't figure out how to solve this.
Output for input a = 6 needs to be like :
012345
123456
234567
345678
456789
567890
Output for input a = 3 needs to be like :
012
123
234
Output for input a = 4 needs to be like :
0123
1234
2345
3456
But I'm getting this :
0 1 2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Here's my code:
for (int i = 0; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(j + " ");
}
System.out.println();
}
You need to make these changes to get the required output:
Termination conditions of the outer for loop should be i < a;
Termination conditions of the inner for loop should be j < a + i;
The number you're printing should be not j but j % 10 to satisfy the data sample you've provided (for input a=6 it prints 0 as the last number on the very last line instead of 10, that means we need not j, but only its rightmost digit which is the remainder of division by 10).
That's how it can be fixed:
public static void printNumbers(int a) {
for (int i = 0; i < a; i++) {
for (int j = i; j < a + i; j++) {
System.out.print(j % 10 + " ");
}
System.out.println();
}
}
Observations:
Since it is a 2 dimensional output, we will need 2 loops ( one inside the other ).
Also, the starting point for each line is the value from which the last line starts +1 .
If the value crosses 10, then we will keep the unit digit value only ( like in the last line). ( therefore we use modulus operator % that helps to extract the unit digit)
Code :
class Main {
public static void main(String[] args) {
int n = 6;
pattern(n);
}
private static void pattern(int n) {
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j < k + n; j++) {
System.out.print(j % 10);
}
k = i + 1;
System.out.println();
}
}
}
and the answer is :
012345
123456
234567
345678
456789
567890

How to print a array with different conditions

I'm trying to print values by mapping one to another array. Below is my sample code.
int k;
int m=0;
int NUMBER_OF_TIME = 2; // this value will be constant won't change
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A, B"};
System.out.println("-----------------"+"\n");
for (k=0; k < array1.length; k++) {
inner: for (; m < timeReadings.length; m++) {
if(m==NUMBER_OF_TIME && k!=0) {
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
break inner;
}else
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
}System.out.println("-----------------"+"\n");
}
Expected output is:
When user NUMBER_OF_TIME =2, the output should be like this.
--------------------
A
1 2 3 4 5 6
--------------------
B
7 8 9 10 11 12
--------------------
If i correctly understood what you want, this should work :
int NUMBER_OF_TIME = 2;
int n = 1;
boolean bool = true;
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A", "B"};
System.out.print("-----------------"+ System.lineSeparator());
System.out.print(array1[0] + System.lineSeparator());
for(int i : timeReadings) {
System.out.print(i + " ");
if(n > (timeReadings.length / NUMBER_OF_TIME) - 1 && bool) {
System.out.println(System.lineSeparator()+"-----------------");
System.out.print(array1[1] + System.lineSeparator());
bool = false;
}
n++;
}
System.out.println(System.lineSeparator()+"-----------------");
If this doesn't work for you, please provide more output examples, as others already asked.
Edit : Modified the code to output what you expect.

Remove a duplicate word sentence in an array

Given a problem that determines the output of the word, length of each word, and the number of times the word repeats, I have the following code capable to determine the word and length of each word below:
String sentence;
String charSentence;
String[] wordOutput;
private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];
// Increment a single repeat
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
// Increment when repeated.
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
}
}
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}
When I run the program, I get the following output:
Equal 5 2
Equal 5 1 <- This is a duplicate word and should not be here when it repeats.
Does anyone know where my problem is? Is it something relating that deals with my repeats array?
The first problem is that in the inner for loop you are looping from i+1 to length-1. You need to loop till length. Second you will need to determine if there are any occurrences of the word in the String, and if so use a continue statement. You can do:
outer:
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
for(int index = i-1; index >= 0; index--) {
if(words[i].equals(words[index])) {
continue outer;
}
}
...
}
However the problem with this is that there will be null values at the end of the list, as you specify an Array with the same length as the number of words. To solve this you can do:
wordOutput = Arrays.stream(wordOutput).filter(e-> e!= null).toArray(String[]::new);
Which will filter out the null values
Output:
(With the input String: "This is a String is a with a lot lot of this repeats repeats")
This 4 2
is 2 2
a 1 3
String 6 1
with 4 1
lot 3 2
of 2 1
this 4 1
repeats 7 2
Instead of incrementing count at all index store the count only in last occurence of word, in other case, have the count value of 0. at the end traverse the count array, if its greater than zero, print the value and its count
private void analyzeWords(String s) {
String[] words = sentence.split(" ");
wordOutput = new String[words.length];
int[] repeats = new int[words.length];
for (int i = 0; i < words.length; i++) {
int count =1;
int index = i;
for (int j = i + 1; j < words.length - 1; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
count++;
index = j;
}
}
if(repeats[index]==0){
repeats[index]=count; // update repeat array only for last occurence of word
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[index];
}
}
First, as GBlodgett mention you should check all left words for repeats, your current solution skips last word. Update second loop termination condition to j < words.length.
Second, if you want to print duplicates only once you need a condition in your solution. One of the example:
boolean[] duplicates = new boolean[words.length];
// Increment a single repeat
for (int i = 0; i < words.length; i++) {
repeats[i] = 1;
// Check for duplicates,
// If the word was not marked as duplicate
if (!duplicates[i]) {
// Increment when repeated.
for (int j = i + 1; j < words.length; j++) {
if (words[i].equalsIgnoreCase(words[j])) {
repeats[i]++;
duplicates[j] = true;
}
}
wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
}
}
There is a Java 8+ solution, for example:
Map<String, Long> m = Arrays.stream(s.split(" ")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map will have pairs of word and it occurrences.

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

How to use printf to print out in a certain format

How do I use the command printf to print my output the same way in the attached output file?
this is my code currently:
else if (args[0].equals("fib")) {
for (int i = 0; i < (Integer.parseInt(args[1]) + 1); ++i) {
System.out.println(getFib(i));
}
}
How do i change it to make it print like the attached picture?
Thank you guys for your help!
Here is an example.
Instead of instant printing add all numbers into a list:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= number; i++) {
numbers.add(fibonacci(i));
}
Then make a pattern for printf():
String pattern = "%" + (numbers.get(numbers.size()-1).toString().length() + 10) + "d";
where (numbers.get(numbers.size()-1).toString().length() + 10) is the sum of the number of characters in the largest number plus 10 spaces between columns.
Then print all elements of the list. The counter is needed in order to have no more than 6 columns:
int counter = 0;
for (Integer integer : numbers) {
if (counter == 6) {
System.out.println(" ");
counter = 0;
}
System.out.printf(pattern, integer);
counter++;
}

Categories

Resources