Welcome To The World Of Java

This site will teach you the basics of Java. It is not necessary to have any prior programming experience.

Print Series 1, 12, 123, 1234, …………n in Java.

Somdeb Burman | 11:36:00 AM | 11 comments

import java.util.Scanner;
public class Series 
{
 public static void main(String args[]) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter the number of terms: ");
  int n = sc.nextInt();
  int s = 0, c;                       // s for terms of series, c for counter to generate n terms
  for (c = 1; c <= n; c++) {
   s = s * 10 + c;
   System.out.print(s + " ");
  }
 }
}


Output:
Enter the number of terms: 6
1,  12,  123,  1234,  12345,  123456....... 
BUILD SUCCESSFUL (total time: 3 seconds)

Java Resources are available for Download from below

Category: , , , ,

11 comments:

  1. Very very useful for me. Thanks a ton. Helped me a lot in preparing for my exams.

    ReplyDelete
  2. Its not working when used in bluej :(

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Explain how will it work if s=0 then s*10+c
    Zero. Will come again again

    ReplyDelete
    Replies
    1. s=s*10+c; //0*10+1=1
      The value of "s" becomes
      1, so next time,
      s=s*10+c; //1*10+2=12
      Now, value of "s" is
      12,so,
      s=s*10+c //12*10+3=123
      ("c" is the loop variable, so it's value is increasing)
      This will continue
      Hope you got it

      Delete
  5. thank you your site for all java solutions.

    ReplyDelete