Programming Problems and Solutions in Java


Problem #1


Write a program in Java which accept 2 integer start & repeat and print the pattern such that starting and ending number of pattern is - start and total numbers or rows in the pattern is equal to (repeat*2). Number in the pattern should be increase by 1 in each rows till the middle of the rows and then decrease by 1 till end of the rows.

For example- If start = 4 and repeat = 4 then
  1. start = 4 -> Starting number of pattern,
  2. (repeat * 2) = (4*2)= 8 -> number of rows to print in the pattern

   4
   55
   666
   7777
   7777
   666
   55
   4

Possible Solution


 void printPattern(int start, int repeat) {
  int k = repeat;
  for (int i = 0; i < 2 * repeat; i++) { // loop 1 start
   for (int j = 0; (j <= i && j < k); j++) { // loop 2
    System.out.print(start);
   } // end loop 2
   if (i < repeat - 1) {
    start = start + 1;
   }
   if (i > repeat - 1) {
    start = start - 1;
    k = k - 1;
   }
   System.out.println();
  } // end loop 1
 }

Output:
 
Test 1: (Start = 5 , repeat = 6)

5
66
777
8888
99999
101010101010
101010101010
99999
8888
777
66
5


Test 2: (Start = 3 , repeat = 4)

3
44
555
6666
6666
555
44
3