I need to write a method that accepts two ints as arguments, a min and a max. On the first line i need to print all numbers in that range (inclusive). On the next line I start with min+1, print all numbers up to max, and then go back to the front of the range and print min. Next line I start with min+2, and so on until I have repeated this starting with each number in the range.Very hard to explain, here's two examples: Say I pass 1 and 5 as the min and max arguments. I want the method to print this:
12345
23451
34512
45123
51234
Or if 3 and 9 were passed, I would expect this:
3456789
4567893
5678934
6789345
7893456
8934567
9345678
I've tried all kinds of things, I'm sure there is an easy way to do this that I am not realizing. I'm supposed to do this without arrays or arrayLists. I think I have a good base to work with, but I just can't figure out where to go from here. My base code prints this:
12345
2345
345
45
5
And this:
3456789
456789
56789
6789
789
89
9
I'm stumped. Here's my code:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
System.out.println();
}
}
You should think about how many values you want on each row, and then determine what those values should be. Its hard to make it any clearer without giving you the solution.
Let us know how you go.
Peter is right, and IMO is answering a homework question in the right manner. You know how many elements you want on each line, so you need an outer loop that gives you that many elements, this will stop you from getting the cascading behavior you're seeing now.
At that point you need to think about your inner loop(s), and you'll probably find this easiest using the modulus operator (%). This will allow you to iterate without ever going over your target.
You should be able to figure it out from there, and you're much better off figuring out the algorithm yourself than copying it from someone else, at least at this level of development. Good Luck!
Think about a way to print the missing numbers. The answer is below, if you cannot come up with it you can check it.
This should also print the missing parts:
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for (int k=0; k<i-min; k++){
System.out.print(min+k);
}
System.out.println();
}
}
I didn't run this one but it might work:
public void printSquare(int min, int max){
int dif = max - min;
for (int i=min; i<=max; i++){
for (int j=i; j <= i+dif ; j++){
int temp = j;
if ( temp > max ) temp = temp - max;
System.out.print(temp);
}
System.out.println();
}
}
try and just shift an array like so:
static void Main(string[] args)
{
// this will work equally well with numbers letters or other types of characters
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String a = "hello";
for (int i = 0; i < nums.Length; i++)
{
int j = 5;
int num = i;
while (j-- > 0)
{
if (num >= nums.Length)
{
num = 0;
}
// shift the loop
Console.Write(nums[num++]);
}
Console.WriteLine();
}
}
public class Test1{
public void printSquare(int min, int max){
for (int i=min; i<=max; i++){
for (int j=i; j<=max; j++){
System.out.print(j);
}
for(int k= min; k<i; k++){
System.out.print(k);
}
//System.out.print(i-1);
System.out.println();
}
}
public static void main(String[] args){
Test1 t = new Test1();
t.printSquare(1,5);
}
}
This is a very simple implementation. Hope this helps!
int n = max-min+1;
for (int i=0 ; i<n; i++){
for (int j=0; j<n; j++)
cout<<min + (i+j)%n;
cout<<"\n";
}
Output:
min = 3 | max = 9
3456789
4567893
5678934
6789345
7893456
8934567
9345678
Here's the code..
for i = 0 to max-min
for j = 0 to max-min
print min + (i+j)%n
Related
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!
I have to write a program where the user inputs 3 numbers into an array and then the output is the numbers subtracted from each other.
I have tried using a for loop for this but it just outputs the numbers added together then turns it negative eg : if i put in the numbers 1,2 and 3 it should output -4 but outputs -6.
this is my code : (the print line part is in another method )
int sub = 0;
for(int j =0; j < numbers.length;j++)
{
sub -= numbers[j];
}
return sub;
how do I get the numbers to subtract.
Also if anyone knows how to get the numbers to divide by each other that would be really helpful : )
Thanks in advance
int sub = numbers[0];
for(int j = 1; j < numbers.length;j++)
{
sub -= numbers[j];
}
return sub;
To divide, use /= instead of -=.
Change it to look like this:
int sub = numbers[0];
for (int j = 1; j < numbers.length; j++) {
sub -= numbers[j];
}
return sub;
Your code does
0 - numbers[0] - numbers[1] - numbers[2]
when what you want is
numbers[0] - numbers[1] - numbers[2]
It seems that you are assigning sub= 0 which is creating an issue. You need to assign the first value of array instead.
I have corrected the code for you:
public static void main (String[] args) throws java.lang.Exception
{
int a [] ={1, 2, 3};
int sub = a[0];
for(int j =1; j < a.length;j++)
{
sub = sub -a[j];
}
System.out.println (sub);
}
You may run this code here. You may find complete code here
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);
}
}
}`
I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.
I have this question:
The method accepts an integer array as its input and returns a new array which is a
permutation of the input array. The method fix34 rearranges the input array such
that every 3 is immediately followed by a 4 (e.g. if there is a 3 at position i, there will
be a 4 at position i+1). The method keeps the original positions of the 3s but may
move any other number, moving the minimal amount of numbers.
Assumptions regarding the input:
The array contains the same number of 3's and 4's (for every 3 there is a 4)
There are no two consecutive 3s in the array
The matching 4 for a 3 at some position i is at position j where j > i
ok, so this is what I wrote:
public class Fix34 {
public static void main(String[] args){
int [] args1 ={3,1,2,3,5,4,4};
int[] args11=fix34(args1);
for (int i = 0; i<=args11.length-1;i++ ){
System.out.print(args11[i]+" ");}}
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
public static int[] fix34(int[] nums){
for(int i = 0; i<=nums.length-1; i++){
if (nums[i] == 3){
nums[pos(nums)]=nums[i+1];
nums[i+1]=4;
}
}
return nums;
}
}
when I insert arrays such {3,2,1,4} it works, but with the array as written in the code, it gives me the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Fix34.pos(Fix34.java:15)
at Fix34.fix34(Fix34.java:25)
at Fix34.main(Fix34.java:6)
how come the arrays gets to -1 position?!
Thanks
you are setting it to -1 here:
i=-1;
Your issue in in this piece of code
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
If the last element in the array is 4 the while loop is never entered so arrays like 3, 1, 2, 4 are fine. Otherwise the loop is entered and i is set to -1. I think that you mean to decrement. In that case replace
i=-1
with
i--
or
i=i-1
and as mentioned in another answer make sure i doesn't go below 0.
I think you ment
i-= 1;
instead of that:
i=-1;
Whoa there that is a little overblown for this problem. Nested loops are they key hereā¦come take a look
public int[] fix34(int[] nums) {
for(int a = 0; a < nums.length; a++){ //we see 4's first
for(int b = 0; b < nums.length - 1; b++){ //then the nested loop finds a 3
//length - 1 to stay in bounds, although not needed here...
if(nums[a] == 4 && nums[b] == 3){
//swap
int tmp = nums[b + 1];
nums[b + 1] = nums[a];
nums[a] = tmp;
}
}
}
return nums;
}