basam nath basam nath - 5 months ago 8
Java Question

How to remove carriage return while printing in a for loop in java

The output of the following code comes as:
3
5
10
17
7

But I want the results to be printed in a single line like : 3 5 10 17 7
Here is the code:

public class BubbleSort
{

public static void main(String[] args)
{
//array
int[] myArray = {3, 5, 10, 17, 7};
System.out.println( "Array elements before sort");
//before sort
for( int i = 0 ; i < myArray.length ; i ++ )
{

System.out.println(myArray[i] );

}

Answer

Replace

System.out.println(myArray[i]);

with

System.out.print(myArray[i] + " ");

The difference between println and print is that println emits (void methods don't return anything) a newline character (the result of pressing the "enter" key on a keyboard) after printing out whatever was in the parentheses while print does not emit a newline character

Comments