I am new to Java and now I want to learn better for loop. I made some examples , but I don't know how to do a triangle that look like this:
for n=6:
111111
22222
3333
444
55
6
My code until now:
class Pyramid
{
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++) {
System.out.print(i); }
System.out.print("\n");
}}}
But what I managed to do it looks like this:
1
22
333
4444
55555
666666
How to make it in reverse order ?
We can use is a function int numberForRow(int row) that will perform a suitable transformation. Then the function can be used like r = numberForRow(i); print(r). It needs to map this:
row (i) -> display number (r)
6 1
5 2
4 3
3 4
2 5
1 6
I think you can write it :)
Look at the relationship between the input (i) and output (r) - it might be useful to note that they always add up to the same value so a little bit of math should do the trick.
(While a function isn't strictly required I find that such functions can help break down a problem and, especially in this case, illustrate a transformation well - it also works in case of a "more advanced" transformation, such as was in the original question ;-)
Your issue is that your outer for loop was going from 6 to 1, so you need to reverse that.
Change
for(i=n;i>=1;i--) {
To
for(i = 1; i <= n; i++) {
Further explanation, so you understand what is happening inside a for loop:
A for loop operates on three clauses: where you start, the condition that the loop runs, and what to do after it runs.
------v
for(i = 1; i <= n; i++) {
This is the assignment. You set a variable to a number, which is where the loop starts. In this case, we start with i = 1, since we want to print only one 1 on the first line. In the third clause, we will increment it (read: add one to it), and run the loop again.
--------------v
for(i = 1; i <= n; i++) {
This is the condition. The loop will run whenever this condition evaluates to true. In other words, if n = 6, this loop will run when i <= 6.
--------------------v
for(i = 1; i <= n; i++) {
This is what will happen each time the loop is executed. After it runs through once when i = 1, we will increment i, so now i = 2. This will happen until the condition (i <= n) evaluates to false, i.e. when i = 7. If the condition is false, the loop will terminate.
public class Pyramid {
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
//for(j=1;j<=i;j++) {
for(j=n;j>=i;j--) {
System.out.print(i);
}
System.out.print("\n");
}
}
}
This should help.
Can be done using below method:
public class Main {
public static void main(String[] args) {
int n = 6;
int m =n;
for (int i = 1; i <= n; i++,m--) {
for (int j = 1; j <= m; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
If you want to print the triangular numbers then use the following code
`public class Triangular{
public static void main(String[] args) {
int i = 0;
int j =0;
int count =0;
for (i=1;i<=10;i++){
count = 0; // This is a program to print triangular numbers in JAVA
for(j=1;j<=i;j++){
count = count + j;
}
System.out.println(count);
}
}
}`
Related
In my program in certain function i have to fill 3x3 square of 9x9 array. At first glance it seems to be as trivial as it sounds but somehow one for() loop is not working properly. I asked two friends of mine and checked the code several times but still cant find any mistake everything seems to be working just fine if we do not count one for function. I tried to change it to other loop and it also didnt work. Below i give you my code and the outcome.I tried to serch the web for similar problem but also couldnt find one. Thank you in advance!
Code:
import java.util.Random;
public class ttabela
{
public static void main(String[] args) {
boolean bylo[] = new boolean[10];
int tabela[][] = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tabela[i][j] = 0;
}
}
wypelnianiePrzekatnych(bylo, tabela,0,2);
clear(bylo);
System.out.println("");
for(int i=0;i<3;i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tabela[i][j]+" ");
}
System.out.println();
}
System.out.println("");
for(int x=0;x<9;x++)
System.out.print(tabela[0][x]+" ");
}
static int RandomBeetween ( int min, int max)
{
Random random = new Random();
int a1 = random.nextInt(max - min);
int a2 = a1 + min;
return a2;
}
static void wypelnianiePrzekatnych(boolean[] bylo, int[][] tabela,int i,int j){//i=0 j=2
int a = i,b=i ;
for (;a < (j+1);a++) { //This one doesnt make any difference
for (;b < (j+1); b++) {
System.out.println("p "+a+" "+b+" k");
tabela[a][b] = RandomBeetween(1, 10);
System.out.println(tabela[a][b]);
if (bylo[tabela[a][b]] == true) {
do {
tabela[a][b] = RandomBeetween(1, 10);
}while (bylo[tabela[a][b]] == true);
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
else {
if (bylo[tabela[a][b]] == false)
bylo[tabela[a][b]] = true;
System.out.println(tabela[a][b]);
}
}
}
}
static void clear(boolean[] bylo)
{
for(int h=0;h<10;h++)
bylo[h]=false;
}
/*public static void wypelnianieReszty()
{
}*/
}
Outcome:
p 0 0 k
7
7
p 0 1 k
8
8
p 0 2 k
3
3
7 8 3
0 0 0
0 0 0
7 8 3 0 0 0 0 0 0
The problem is that your inner for loop will only execute once, so the outer loop has nothing to run after the first iteration.
I'll explain in more detail.
You start with:
int a = i,b=i ;
Let's say we passed in (..., 0, 2) as you have done. So a = 0, b = 0.
The outer for loop will run just fine exactly as expected - the code will run until a > (j+1) and there's nothing wrong here.
The problem is actually with your second for loop:
for (;b < (j+1); b++) {
For the first iteration, this will run as expected. But any time after that, it will never run - because you have already incremented b, such that b == (j+1).
I believe there is a fairly simple solution, assuming I've interpreted your requirements correctly:
int a = i;
int b;
for (;a < (j+1);a++) { //This one doesnt make any difference
b = i
for (;b < (j+1); b++) {
This works because it resets the value of b before each iteration of the for loop, so it won't halt immediately.
I hope this helps! Feel free to ask any questions in the comments.
I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!
As a beginner and in java, I'm having some trouble with the output of my code. The code only prints the values of "a","b" and "c" for the value I put into running the code. How would I amend this for it to print all values up to and including the value I put into running the code
Could someone help please? Thank you!
class Numbers
{
public static void main (String[] args)
{
for ( int i = 0; i < args.length; i++)
{
int a = Integer.parseInt(args[i]);
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
So did I get it right in your comment? You want to pass a number that tells you how many iterations the loop should run. And for any iteration you want to write a incrementing number, its square and its cube?
class Numbers {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println("Please specify number.");
return;
}
int iterationCount = Integer.parseInt(args[0]);
for ( int i = 0; i < iterationCount; i++) {
int a = i;
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
Please try this
javac Numbers.java
java Numbers 1 2 3
This should work. In first iteration of your for loop, the a variable will be 1, so it will print 1, 1 and 1. In second iteration, your a variable will be 2, so it will print 2, 4 and 8 and in your third iteration, your a variable will be 3, so it will print 3, 9 and 27.
The loop just runs once because your argument is 3. So args.length is 1. And that is why 3, 9, and 27 are printed.
For the loop to run three times you might evaluate the String passed as args[0] as an int. In that case you need something like (no exception handling here):
int numLoops = Integer.parseInt(args[0]);
for ( int i = 0; i < numLoops; i++)
System.out.print(i);
System.out.print(i*i);
System.out.println(i*i*i);
}
For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.
This question already has an answer here:
How to iterate through array combinations with constant sum efficiently?
(1 answer)
Closed 9 years ago.
I have 12 products at a blend plant (call them a - l) and need to generate varying percentages of them, the total obviously adding up to 100%.
Something simple such as the code below will work, however it is highly inefficient. Is there a more efficient algorithm?
*Edit: As mentioned below there are just too many possibilities compute, efficiently or not. I will change this to only having a maximum of 5 or the 12 products in a blend and then running it against the number of ways that 5 products can be chosen from the 12 products.
There is Python code that some of you have pointed to that seems to work out the possibilities from the combinations. However my Python is minimal (ie 0%), would one of you be able to explain this in Java terms? I can get the combinations in Java (http://www.cs.colostate.edu/~cs161/Fall12/lecture-codes/Subsets.java)
public class Main {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
for(int a=0;a<=100;a++){
for(int b=0;b<=100;b++){
for(int c=0;c<=100;c++){
for(int d=0;d<=100;d++){
for(int e=0;e<=100;e++){
for(int f=0;f<=100;f++){
for(int g=0;g<=100;g++){
for(int h=0;h<=100;h++){
for(int i=0;i<=100;i++){
for(int j=0;j<=100;j++){
for(int k=0;k<=100;k++){
for(int l=0;l<=100;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+f+" "+g+" "+h+" "+i+" "+j+" "+k+" "+l);
}}}}}}}}}}}}}
}
}
Why make it so difficult. Think simple way.
To explain the scenario simpler, consider 5 numbers to be generated randomly. Pseudo-code should be something like below.
Generate 5 random number, R1, R2 ... R5
total = sum of those 5 random number.
For all item to produce
produce1 = R1/total; // produce[i] = R[i]/total;
Please, don't use nested for loops that deep! Use recursion instead:
public static void main(String[] args) {
int N = 12;
int goal = 100;
generate(N, 0, goal, new int[N]);
}
public static void generate(int i, int sum, int goal, int[] result) {
if (i == 1) {
// one number to go, so make it fit
result[0] = goal - sum;
System.out.println(Arrays.toString(result));
} else {
// try all possible values for this step
for (int j = 0; j < goal - sum; j++) {
// set next number of the result
result[i-1] = j;
// go to next step
generate(i-1, sum + j , goal, result);
}
}
}
Note that I only tested this for N = 3 and goal = 5. It absolutely makes no sense to try generating all these possibilities (and would take forever to compute).
Let's take your comment that you can only have 5 elements in a combination, and the other 7 are 0%. Try this:
for (i = 0; i < (1<<12); ++i) {
if (count_number_of_1s(i) != 5) { continue; }
for (j = 0; j < 100000000; ++j) {
int [] perc = new int[12];
int val = j;
int sum = 0;
int cnt = 0;
for (k = 0; k < 12; ++k) {
if (i & (1 << k)) {
cnt++;
if (cnt == 5) {
perc[k] = 100 - sum;
}
else {
perc[k] = val % 100;
val /= 100;
}
sum += perc[k];
if (sum > 100) { break; }
}
else { perc[k] = 0; }
}
if (sum == 100) {
System.out.println(perc[0] + ...);
}
}
}
The outer loop iterates over all possible combinations of using 12 items. You can do this by looping over all numbers from 1:2^12, and the 1s in the binary representation of that number are the elements you're using. The count_number_of_1s is a function that loops over all the bits in the parameter and returns the number of 1s. If this is not 5, then just skip this iteration because you said you only want at most 5 mixed. (There are 792 such cases).
The j loop is looping over all the combinations of 4 (not 5) items from 0:100. There are 100^4 such cases.
The inner loop is looping over all 12 variables, and for those that have a 1 in their bit-position in i, then it means you're using that one. You compute the percentage by taking the next two decimal digits from j. For the 5th item (cnt==5), you don't take digits, you compute it by subtracting from 100.
This will take a LONG time (minutes), but it won't be nearly as bad as 12 nested loops.
for(int a=0;a<=100;a++){
for(int b=0;b<=50;b++){
for(int c=0;c<=34;c++){
for(int d=0;d<=25;d++){
for(int e=0;e<=20;e++){
for(int f=0;f<=17;f++){
for(int g=0;g<=15;g++){
for(int h=0;h<=13;h++){
for(int i=0;i<=12;i++){
for(int j=0;j<=10;j++){
for(int k=0;k<=10;k++){
for(int l=0;l<=9;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
// run 12 for loops for arranging the
// 12 obtained numbers at all 12 places
}}}}}}}}}}}}}
In Original approach(permutation based), the iterations were 102^12 = 1.268e24. Even though the 102th iteration was false, it did check the loop terminating condition for 102th time.
So you had 102^12 condition checks in "for" loops, in addition to "if" condition checks 101^12 times, so in total, 2.4e24 condition checks.
In my solution(combination based),No of for loop checks reduces to 6.243e15 for outer 12 loops, &
if condition checks = 6.243e15.
Now, the no of for loops(ie inner 12 for loops) for every true "if" condition, is 12^12 = 8.9e12.
Let there be x number of true if conditions. so total condition checks
=no of inner for loops*x
= 8.9e12 * x + 6.243e15
I'm not able to find the value of x. however, I believe it wouldnt be large enough to make total conditon checks greater than 2.4e24