chinna
chinna

Reputation: 19

If enter n is input and the output is in n digits and starting with (n-1)0 with 1 to (n-1)9's?

I have tried this program many times I didn't get the proper output till now please help me to solve this type of program.

input:n=3

output: 001 to 999

input:n=4

output:0001 to 9999

input:n=2

output:01 to 99

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();
    int sum=1,result=0;
    while(number!=0)
    {
        result=result+(9*sum);
        sum=sum*10;
        number--;
    }
    System.out.println(result);
    for(int i=1;i<=result;i++)
    {
        System.out.printf("%02d ",i);//here i manually mentioned the %02d  but i want to take user input
    }
}

Upvotes: 1

Views: 97

Answers (2)

Avvappa Hegadyal
Avvappa Hegadyal

Reputation: 273

Can you try below code ?

class Main
{
public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    String masked = "%0" + (num) + "d%n";
    int max = (int)Math.pow(10, num)-1;
    for (int k = 1; k <= max; k++)
        System.out.printf(masked, k);
}}

Upvotes: 2

Scary Wombat
Scary Wombat

Reputation: 44854

You can use this code

    int number = 3;
    String mask = "%0" + (number) + "d%n";
    int max = (int)Math.pow(10, number)-1;

    for (int x = 1; x <= max; x++)
        System.out.printf(mask, x); 

thanks to @RalfRenz

Upvotes: 2

Related Questions