Programming Problem Solving in Java | Example of String.format() in Java | AskTheCode
Problem: We've already tried printing out the squares of the values, right? But today, we shall overwrite the original values for every iteration in this problem, so you have to be careful with this one.
There's already a predefined array/list containing 5 integer values. Now, make a program that will accept an integer. Then, loop through each values for the same number of times as the inputted integer and for each iteration inside that loop, you have to square that number.
Finally, at the end of your program, print out all the final values of the numbers with at least 3 integer places.
Input Format:
A line containing an integer.
Output Format:
Multiple lines containing an integer.
Sample Input:
1
Sample Output:
001
004
009
016
025
EXPLANATION:
Keep squaring each of the elements of the list/array n times. Afterwards, print the array or list elements in three digits.
Code:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner in=new Scanner(System.in);
int arr[] = new int[5];
for(int i=1; i<=5; i++)
arr[i-1] = i;
int n = in.nextInt();
while(n-- > 0){
for(int i=1; i<=5; i++)
arr[i-1] = arr[i-1] * arr[i-1];
}
for(int i=1; i<=5; i++)
System.out.println(String.format("%03d", arr[i-1]));
}
}
תגובות