i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}
Related
Write a program that prints a part of the sequence:
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...
(the number is repeated as many times, to what it equals to).
I've used two for loops, however, I can't get 1 to print once, 2 to print twice, instead, I get
1 2 3 4 5 6 1 2 3 4 5 6, etc.
You need two for loops for this.
for (int i = 0; i <= 5; i++) { // This will loop 5 times
for (int j = 0; j < i; j++) { //This will loop i times
System.out.print(i);
}
}
As I remember the goal is to print n numbers (for example 1 2 2 3 3 3 4 for n = 7), diveded by space. Sorry for my java)), I wrote it in Kotlin, tried to change for Java, but main idea is clear. BTW n – the number of the elements, you need to read with Scanner.
int count = 0 //Idea is to create a counter, and to increment it each time of printing
for (int i = 0; i <= n; i++) { //Loops n times
for (int j = 0; j < i; j++) { //Loops i times
if (int count < int n) {
System.out.print(" "+i+" ");
int count++ //Prints 1 one time, 2 two times, etc. stops if reached n number
}
}
}
How about this :
for(int i=1;i<=num;i++){
for(int j=1;j<=i;j++){
System.out.print(" "+i+" ");
}
}
where, num = 1,2,....n
(Also we wont be able to tell why you got that output unless you attach the code. Please attach the code snippets for such questions :) !
As the title suggests, I have code for a Fibonacci series and my goal is to replace multiples of numbers (3, 5, 7 and combinations of them) in the series with a word. I was suggested to use a flag in my if loop to check for the printed phrase, and if the phrase is printed, to skip that number. Essentially, what I want the output to look like is:
1 1 2 skip 8 13 skip 34 55
(this is replacing multiple of three only, for now).
Instead, what I am getting is:
1 1 2 3 skip5 8 13 21 skip34 55
Here is my code as of now:
int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
}
for (int i = 0; i < febCount; i++) {
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Any and all help is appreciated!
Let's walk through the code you have provided and attempt to understand why it's not working.
//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
//Here we print out the fibonacci number we are on, unconditionally.
//This means that every fibonacci number will be printed no matter what number it is
//we don't want that.
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
//After we print the number, we check to see if it is a multiple of three.
//maybe we should be waiting to print until then?
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Now that we have walked through the code, we can propose a new solution.
Let's try updating the loop so that it wait's to print the fibonacci number until AFTER we've checked to see if it meets our conditions.
for (int i = 0; i < febCount; i++) {
if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
System.out.println(" Skip ");
} else { //if it's not a multiple, then print the number
System.out.println(" " + feb[i]);
}
}
I have written a code that is generating random numbers based on user input. For example, if the user says they want the program to generate 3 random digits for them, and they want it to do it 3 times, the output will look like this:
1 4 5
2 6 5
3 4 5
The code that I've written would display this as:
1
4
5
2
6
5
3
4
5
How do I make them display as 3 numbers wide? Here's my code:
if (gameType == 3)
//for loop to generate random numbers
for (int i = 1; i <=numGames; i = i + 1){
for(int j = 1; j <= numGames * 3; j = j + 1 ){
ranNums = randomGenerator.nextInt(9);
//Print random numbers to user
System.out.println(ranNums);
As always, thank you! - I added to the post to help you understand more of what I need. Please let me know if you require more info to help me!
Generally loop should look like:
for (int i = 1; i <= numGames; i = i + 1) {
for (int j = 1; j<= gameType; j = j + 1) {
int ranNums = randomGenerator.nextInt(9);
System.out.print(ranNums + " ");
}
System.out.println();
}
Hey guys so I'm working on a problem where I need to print
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
public class Set_5_P5_18b {
public static void main(String[] args) {
int x;
String y;
x = 1;
y = "";
System.out.println("Pattern B:");
while (x < 7) {
y = y + x + " ";
x++;
}
System.out.println(y);
}
}
What I wrote above print's the first line but I can't figure out how to modify it to print the second, could anyone help me please?
Yuo need the outer for loop to run for say x ranging from values 6 to 1. For each value of x you need a inner loop that runs for values 1 ... x and prints out values in a line.
Keep this in mind and try to come up with pseudo code first and then the implementation code.
you'd have to reset the variables x, when you quit while :P
So commonly when you are writing a for loop and you realize that you want a certain aspect of the for loop to change each time the program iterates, 9/10 times you want to use nested for loops (for loop within a for loop).
So essentially every time that you iterate through the for loop you want to have the duration of the for loop decrease. So...
for (int num =1; num < <number that you want to change>; num++) {}
Here is the code method.
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
This is how you would do call the method.
public class print
{
public static void print(int x) {
for (int lengthOfFor = x; lengthOfFor > 0; lengthOfFor--) {
for (int num = 1; num <= lengthOfFor; num++) {
System.out.print(num + " ");
}
System.out.print("\n");
}
}
public static void main (String[] args) {
print(6);
}
}
Your output can be observed like a 2-dimensional array where:
index i grows top-to-bottom and represents row index
index j grows left-to-right and represents column index
What you are doing right now is iterating over the columns of the first row and that is it.
As mentioned in the comments, you should add a second loop to iterate over the rows as well.
Here is how you can achieve this with two for loops:
int colSize = 6;
int rowSize = 6;
for(int i = 1; i <= rowSize; i++) {
for(int j = 1; j <= colSize; j++) {
System.out.print(j + " "); // print individual column values
}
System.out.println(); // print new line for the next row
colSize--; // decrement column size since column size decreases after each row
}
java-8 solution:
public static void printPattern(int rows) {
IntStream.range(0, rows).map(r -> rows - r).forEach(x -> {
IntStream.rangeClosed(1, x).forEach(y -> {
System.out.print(String.format("%3d", y));
});
System.out.println();
});
}
Usage:
printPattern(9);
Output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
I understand that there is a similar post to this one, but based on the answers I can not both apply the answers to my current class, or understand the rest of the answers.
I need to create a program using nested "for loops" that creates an output like this one (just symmetrical). I have been trying to get this to work for two whole evenings now, and can't figure it out...
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I would GREATLY appreciate any help!!!
public class PyramidOfDoom {
public static void main(String[] args)
int k = 2;
int totalWidth = 8;
for (int row = 1; row <= totalWidth; row++) {
for (int col = 1; col <= totalWidth; col++) {
if (col <= totalWidth - row) {
System.out.print(" ");
} else {
System.out.print(k);;
}
}
System.out.println();
}
}
}
I thinks it can be done in simple steps as 1. print leading spaces 2. print increasing numbers 3. print decreasing number 4. print trailing spaces 5 print new line.
Sample code(concept) as below.
int row = 10;
for(int i=1; i<=numRow ; i++){
int num = 1;
for(int j=0; j<numRow- i; j++ ){
System.out.print(" ");
}
for(int j=numRow-i+1; j<=numRow ; j++ ){
System.out.print(num+" ");
num=num*2;
}
num=num/2;
for(int j=numRow+1; j<numRow+i; j++ ){
num=num/2;
System.out.print(num+" ");
}
for(int j=numRow+i+1; j<=numRow*2; j++ ){
System.out.print(" ");
}
System.out.print("\n");
}
You're not changing k at all. You need to keep multiplying it by 2 until you get to the middle of the row, then start dividing it by 2. As it stands, in your System.out.println(k), how can you expect it to print anything but 2 if you never manipulate it? :)
Also, you have two semicolons in your System.out.println(k);;. That seems odd to me, but I suppose it actually makes sense that it would compile.