126k views
2 votes
Write a while (or for) statement to print all the digits of an int type variable x, one digit per line. For example, if int x

1 Answer

0 votes

Complete Question:

Write a while (or for) statement to print all the digits of an int type variable x, one digit per line For example, if int x 38625, then the output should be in 5 lines as 60 (Hint: You may use built-in method to get a String representation of x then print out each character in String)

***** Java *****

Answer:

import java.util.*;

public class Main{

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");

int x = input.nextInt();

String str = Integer.toString(x);

for(int i =0;i<str.length();i++) {

System.out.println(str.charAt(i));

}

}

}

Step-by-step explanation:

This line prompts user for input

System.out.print("Enter an integer: ");

This line gets user input

int x = input.nextInt();

This line converts user input to string

String str = Integer.toString(x);

The following loop iterates through the converted string

for(int i =0;i<str.length();i++) {

This prints each character on the string

System.out.println(str.charAt(i));

}

User Hrishikesh Kokate
by
5.2k points