Using nested for loops - java

I have a specification as below:
Write a program that prints out all the permutations of two numbers that add up to 7. Hint: you can use two nested for loops.
I have done this but I know this is not correct. What numbers should I put in?
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=3; i++) {
for(int j=1; j<=i; j++) {
System.out.println(i+ " " +j);
}
}
}
}

Try this (I am assuming you want non-negative numbers, otherwise you have infinite possibilities):
for(int i=0; i<=7, i++)
{
System.out.println(i + "+" + (7-i));
}
No need for two for loops.
If instead of non-negative you require positive numbers, this would become:
for(int i=1; i<7, i++)
{
System.out.println(i + "+" + (7-i));
}

You are almost there. Here are the things that you need to consider:
Assuming that the numbers are required to be positive, the outer loop should go from 1 to 6, inclusive, not from 1 to 3.
Numbers do not need to be in order. Hence, you should not stop the inner loop at i, also going from 1 to 6, inclusive
You need to add an if check before printing i and j.
Once you fix the three things above, your program should work. Good luck!

Your loops should both loop between 1 and 7. Then inside the last for loop you need to check if the sum of i and j equals 7. If it does, print those two numbers.

You really don't need a nested loop.
for (ii = 0; ii<8; ii++) {
System.out.printf("(%d, %d)\n",ii,7-ii);
}
Keep it simple.
I know the "hint" said you could use two nested loops; but in my experience a little bit of cleverness should not be ignored. When your problem gets much larger, being O(n) rather than O(N^2) is a huge difference...

Try this:
for(int i=0;i<7;i++){ //First Loop
for(int j=7;j>0;j--){//Send loop
if((i+j)==7) System.out.println(i+" , "+j); //Permutations printed to terminal
}
}
I guess it's self explaining, two loops going towards each other. Run it and see the lovely result ;)
In mathematics, the notion of permutation relates to the act of permuting (rearranging) objects or values.

A couple of adjustments: I'm taking the liberty of posting a solution but please make sure you understand it!
for (int i = 0; i <= 7/*Need to consider all numbers from 0 to 7*/ ; ++i) {
for (int j = 0; j <= i /*Don't overoptimise: this is good enough and will not generate duplicates*/; j++) {
if (i + j == 7){
System.out.println(i+ "," +j);
}
}
}
It's not the fastest way; spend some time optimising once you have a solution.

public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=7; i++) {
for(int j=1; j<i; j++) {
if (i + j == 7 ) {
System.out.println(i+ " " +j);
}
}
}
}
}

Check if they add up to 7
if (i+j == 7)
{
//then they add to 7
}
They should both be between 1 and 7 though if you want all numbers between 1 and 7 that add up to 7. If you want to include 0 then start there.
for (int i=1; i<=7; i++)
...and you may want to exclude duplicates
for(int i=1; i<=7; i++) {
for(int j=i; j<=7; j++) { //starts at i, not 1
/* Only check j against numbers equal to or lower than itself
/* to avoid duplicates
*/
}
}
Additionally
Class names should start with a capitol letter, by convention, and in camel case (each word in a phrase has capitol letters
NestedFor

Related

Check number of character from command line

I am trying to solve this question: Write a program that passes a string to the command line and displays the number of uppercase letters in the string.
The test is ProgrammingIsFun, so the count would be three.
Here is what I have so far
public static void main(String[] args) {
int count = 0;
for(int i = 0; i < args.length;i++) {
for(int j = 0; j >= i; j++)
if(Character.isUpperCase(args[i].charAt(j)))
count++;
}
System.out.print("The number of upper cases are: " + count);
}
when this runs it does count the correct number of uppercases but it runtimes when it reaches the end of the characters(16). I can't figure out how to stop the loop right after the last character. I know the count is correct because I can see it in the debug. I can see something called arg0 in the variables. That has the correct number of characters but I can't use it.
I am still learning and I can't use objects or anything like that for now.
Any help would be appreciated. or if you could point me somewhere I could read. I tried the docs but it was a lot and I got overwhelmed fairly quickly.
You have an error in the inner loop:
for(int j = 0; j >= i; j++)
Note that the outer loop is run for each of the command line argument and the inner loop is run for each character of an argument given by i.
So change it to
for(int j = 0; j < args[i].length(); j++)
for(int j = 0; j < args[i].length(); j++)?
This will sum all uppercases for all strings passed as arguments.
Your code could be simpler if you only expect one string.
To make your code easier to read (and write) you should use foreach loops, one for each string in the args array, and one for each character in the array that we get by doing foo.toCharArray().
The syntax of a foreach loop is as follows:
for (type var : iterable) {
// Code here
}
Where iterable is something with the Iterable interface (usually an array or ArrayList).
We can switch out these in your code and make it a lot easier to read:
String[] args = {"ProgrammingIsFun!", "When It Works..."};
int count = 0;
for (String e : args) {
for (char f : e.toCharArray()) {
if (Character.isUpperCase(f)) {
count++;
}
}
}
System.out.print("The number of upper cases are: " + count);

Printing Simple Patterns in Java

Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
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++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

Array is printing more numbers than intended?

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!

Grouping similar numbers into brackets

I have recently got into java and I need help with a basic program:
public static void main(String[] args) {
Random gen = new Random();
int roll = gen.nextInt(6) + 1;
int[] array = new int[20];
// Replacing all the numbers of the array to random ones
for (int i=0; i<20; i++){
roll = gen.nextInt(6) + 1;
array[i] = roll;
}
// Bracketing all repeating numbers
for (int i=0; i<19; i++){
if (array[i] == array[i++]){
System.out.print("(");
}
System.out.print(array[i]);
if (array[i] == array[i--]){
System.out.print(")");
}
}
}
}
All this code does is take the random die roll and bracket all the numbers that are the same:
13(66)5(2222)(66)71
However, all it does with this code is bracket all the numbers instead of the ones that are the same:
(1)(3)(6)(6)(5)(2)(2)(2)(2)(6)(6)(7)(1)
What am I doing wrong?
Your code is only checking numbers immediately prior to and immediately after the indexed number in array[i].
You could create a second loop inside the first to iterate over all of the numbers in the array to check for a match.
If you do so, you'll need to keep track of the matching numbers with some other mechanism. Immediately printing out a parenthesis as you're currently doing will be problematic with an inner loop.
A simple method to consider is another array that keeps track of whether there was a match or not.
If you are recently got into Java try to avoid i++ and ++i within square brackets. You can solve this problem with a boolean variable that indicates if there is already a bracket open.
After generate random numbers, try this:
boolean openBracket=false;
for (int i=0; i<array.length-1; i++){
if (array[i] == array[i+1] && !openBracket){
System.out.print("(");
openBracket=true;
}
System.out.print(array[i]);
if(array[i] != array[i+1] && openBracket){
System.out.print(")");
openBracket=false;
}
}

Printing out series of numbers in java

hi guys i am just doing some reading for myself to learn java and came across this problem and is currently stuck.
i need to print out series of number based on the input given by the user.
for example, if input = 5, the output should be as follows
#1#22#333#4444#55555
import java.util.*;
public class ex5{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for(int i=0;i<input;i++){
if(input==1){
System.out.print("#1");
}
if(input==2){
System.out.print("#1#22");
}
}
}
}
this doesnt seem to be working because this is the output i get
Please type a #:
2
#1#22#1#22
im not sure what to put inside the for loop right now and i dont think i am using the for loop here very well either...
any help guys?
for (int i=1; i<=5; i++){
System.out.print("#");
for (int j=1; j<=i; j++) System.out.print(i);
}
out
#1#22#333#4444#55555
you're going to need a nested for-loop to solve this problem.
Yeah, this isn't how you want to do it. You're going to want to build the string inside the for loop.
Start with a new string
String s = "";
As you loop, add to that string.
for(int i=1;i<=input;i++){
s += #;
for(int j=0; j<i; j++) {
s+=i;
}
}
You need to use a nested for loop.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for (int i = 1; i <= input; i++) {
System.out.print("#");
for (int k = 0; k < i; k++) {
System.out.print(i);
}
}
}
It is because you are checking for the numbers 1 and 2 in the if statement. It is hard coded to only check for these two numbers and would not work once you go past the values that you have an if statement for
What you want to do is to output the value of your iterator (in your case, i) i times (hint, you can use another loop inside the big loop) and then ad an # sign at the end of the string.
I will try to not give you any code so you can learn it yourself, but feel free to ask more questions.
You are trying to print given number - given number of times?
Then you'll need two loops for this - outer loop for iterating the number and inner - for iterating -times the given number.
It would be something like this:
for(int i = 0; i < input; ++i) {
System.out.print("#");
for(int j = 0; j < i; ++j) {
System.out.print(i);
}
}

Categories