-
September 21st, 2010, 02:44 PM
#1
Nested for loops
My code is this
public class temp
{
public static void main(String[] args)
{
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 6; j++)
{
System.out.print((i*j)*4-3 + " ");
}
System.out.println();
}
}
}
I'm getting:
1 5 9 13 17 21
5 13 21 29 37 45
9 21 33 45 57 69
13 29 45 61 77 93
The output should be:
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 13 16 20 24
Can't figure out what I'm doing wrong.
Please help
Thanks,
Jeff
-
September 21st, 2010, 03:37 PM
#2
Re: Nested for loops
When posting code please use code tags.
Can't figure out what I'm doing wrong
Try debugging your program. Step through the code by hand writing down the values for i & j as you go and then do the calculation and see what the answer is. Repeat this until you get to the part where it all goes wrong.
Once you have done that and realised your calculation is wrong you need to look at what you are trying to achieve and work out how to achieve it. Start with how to calculate the values in the first column only (hint it might be easier if j started from 0).
-
September 21st, 2010, 04:56 PM
#3
Re: Nested for loops
Norm
-
September 25th, 2010, 05:28 PM
#4
Re: Nested for loops
This how I did and get it right:
public static void main(String[] args)
{
for (int i = 1; i <= 4; i++)
{
System.out.print(i + " " );
for (int j = 1; j <= 5; j++)
{
System.out.print(i+j+j+j+j + " " );
}
System.out.println();
}
}
}
output:
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|