Print Series 1, 12, 123, 1234, …………n in Java.
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)
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: Core Java, Interview Question, Programs, Series, Written Test
Very very useful for me. Thanks a ton. Helped me a lot in preparing for my exams.
ReplyDeleteThanks a lot....
ReplyDeleteIts not working when used in bluej :(
ReplyDeleteThanku
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThanks
ReplyDeleteG O
ReplyDeleteGuru
Explain how will it work if s=0 then s*10+c
ReplyDeleteZero. Will come again again
s=s*10+c; //0*10+1=1
DeleteThe 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
thank you your site for all java solutions.
ReplyDeleteif s=10 11 12 13 ???
ReplyDelete