For loop java making the output into 2 columns - java

Hi I'm a beginner and I'm still learning and if someone could help me in this one thx in advance my code is:
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
and the output should be like this:
0 1
2 3
4 5
6 7
8 9

Just use next line only for odd numbers:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
System.out.format("%2d", i);
else
System.out.format(" %2d\n", i);
}
Output:
0 1
2 3
4 5
6 7
8 9
P.S. For more general usage, I would extract it into separate method
public static void printTwoColumns(int min, int max) {
int width = String.valueOf(max).length();
for (int i = min; i < max; i++) {
String str = String.format("%" + width + 'd', i);
if (i % 2 == 0)
System.out.print(str);
else {
System.out.print(' ');
System.out.println(str);
}
}
}

You can do something like this:
for (int i = 0; i < 10; i++) {
System.out.print(i);
System.out.println(++i);
}
The first print uses the current i value and using System.out.print.
The second
print is using println so it goes one line down and also takes ++i so it will advance i by 1 and will also print the new value.
Each loop iteration is printing two values and advances i by total of 2.

To do what you want you can either do something like this:
for(int i = 0; i < 10; i ++){
if(i % 2 == 0){
System.out.print(i); //Only for evens
}else{
System.out.println(i); //Only for odds
}
}
Or you could simplify it even more with something like this:
for(int i = 0; i < 5; i += 2){
System.out.println(i + " " + (i + 1));
}

Related

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

Program that takes user input and lists multiples of 7 according to that number (Java)

Here is my code to create a program that takes a user input and lists multiples of 7 that relate to that number.
For example: The user inputs 3, I need the output to be "7, 14, 21".
Currently if I enter a number less than 7, the program complies without printing an output, but as soon as I enter 7 or any number higher than 7 then the program compiles and prints exactly what I need it to.
So the problem I need to fix is to be able to enter a number lower than 7 and recieve the correct output.
Thanks in advance!
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args){
int j = 0;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(j = 1; j <= n; j++){
if(j % 7 == 0){
System.out.print(j + " ");
for (int counter = 0 ; counter < n ; counter++) {
System.out.print(j*(2 + counter) + " ");
}
}
}
}
Don't overthink the loop here. As alternatives, both which mean you can delegate the % check, consider
for (j = 0; j < n; ++j){
// output (j + 1) * 7;
}
or, the less elegant due to your having to write 7 in three places
for (j = 7; j <= n * 7; j += 7){
// output j
}
This code is preventing your programm from printing anythingk, when you enter a number below 7:
if(j % 7 == 0){
% is the modulo operator.
It says: do what is in the brackets if the number I have counted to (j) has no reminder if I divide it by 7.
So what you have to do is count to the number entered (using a for loop) and print the mulitplication of the current number times 7.
It's not printing anything because when the number you inputted is less than seven and greater than zero, the code inside
if(j%7==0)
does not get executed. I think your code should be like this.
for (j = 1; j <= n; j++) {
if (j % 7 == 0) {
System.out.print(j + " ");
}
for (int counter = 0; counter < n; counter++) {
System.out.print(j * (2 + counter) + " ");
}
}
import java.util.Scanner;
public class MultiplesOfSeven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for(int j = 1; j <= n; j++) {
System.out.print(7*j + " ");
}
}
}
This is simple solution of your problem. This will work for all cases. Keep code simple good luck.

can't find how to program this number pattern

Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
And this one for rc = 3:
1 2 3
6 4 5
8 9 7

What is the logic to print the below mentioned number pattern

class Num {
public static void main(String[] args) {
for(int i=1;i<=5;i++) {
for(int j=1;j<=i;j++) {
if(j==1) {
System.out.print(i);
}
else if(j==2) {
System.out.print(" "+(i+j+2));
}
else {
System.out.print(" "+(i+j+4));
}
}
System.out.println(" ");
}
}
}
Output:
1
2 6
3 7 10
4 8 11 12
5 9 12 13 14
Expected:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
I tried so much and came up with this logic
when j=1 then i
when j=2 then i+j+2
when j=3 then i+j+4
when j>=4 then i+j+5
there are totally 4 conditions here, how do i get do this in nested for loop. Any other logic is also appreciable.
int lineCount = 5;
for (int i = 1; i <= lineCount; i++) {
int value = i;
for (int j = 1; j <= i; j++) {
System.out.print(value + " ");
value += lineCount -j;
}
System.out.println("");
}
you forgot your j = 3 case
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1) {
System.out.print(" " + i);
} else if (j == 2) {
System.out.print(" " + (i + j + 2));
}
else if(j == 3){
System.out.print(" " + (i + j + 4));
}
else {
System.out.print(" " + (i + j + 5));
}
}
}
I am not a java developer, so sending you solution in C#. You will have to replace "using System;" with some import statement and Console.WriteLine statements with appropriate System.out.print or println.
using System;
class Program
{
static void Main()
{
PrintNumbers(1, 5);
}
static void PrintNumbers(int level, int MaxLevel)
{
if( MaxLevel < level )
{
return;
}
int num = 0;
for(int i = 0, diff=MaxLevel; i < level; i++)
{
num += (i == 0)?level:(diff-i);
Console.Write("{0} ",num);
}
Console.WriteLine("");
PrintNumbers(level+1, MaxLevel);
}
}
I advise and believe that it would be better that our codes be dynamic, meaning it would work on any input of user.Suppose if the question was to change from 5 rows to 6 rows,you have to change the for constructs as well add an additional if construct.
Secondly it would not be a better idea to keep as many if constructs w.r.t the columns you need.
Take the no. of rows the user wants to a variable say 'noofrows'. Then its just the same as your code with little changes:
int noofrows;
Scanner s=new Scanner(System.in);
System.out.println("\nGive the no. of rows needed:\n");
noofrows=(int)s.nextInt();
System.out.println("Number give is:"+noofrows);
int emptyspaces;
for(int i = 1; i <= noofrows; i++)
{
for (int j = 1; j <= i; j++)
{
emptyspaces=(j)*(j-1)/2; //counting the no. of emptspace which is an arithmetic progression
System.out.print(((j-1)*noofrows+i)-emptyspaces +" ");
}
System.out.print("\n");
s.close(); //edited version
Please let me know incase anything went wrong
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=5;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
if(j==1)
cout<<i<<" ";
else
cout<<i+j+j<<" ";
}
cout<<endl;
}
}
/*OUTPUT :-
1
2 6
3 7 9
4 8 10 12
5 9 11 13 15
*/

Print an array elements with 10 elements on each line

I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".\n");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.
Why do you use 2 nested loops where you only need to remember at which places you need to output a linebreak? Also using the same variable i for both loops will not do what you expect.
How about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
All you are going to have to do is to print out a newline after every ten numbers.
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}
I know this is an old question, but I just wanted to answer. In java 8 you can do this in one line. Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\n"));

Categories

Resources