Home | | Sitemap ||Page number :17

Examples

To achieve perfection in loops and if statements, you need to practice lots of programs. The more problems you solve, the better your skills become. I recommend that you should first try them out independently and then look at the solution. It might be possible that your logic was even better than mine.

Note: All of the programs mentioned in this chapter were written by me initially in C++. As most of you would be unfamiliar with this language, I have changed the code to Java. You must know that the logic remains same in programming, just the way of implementation defer.

Example 1.

/* Print pattern 12345 23456 34567 45678 56789 */ //author Nitish Upreti

class pat1 { public static void main(String args[]) { int c,c1,t;

for(c=1;c<=5;c++) { t=c; for(c1=c;c1<=t+4;c1++) System.out.print(+c1); System.out.println(); } } }

Example 2 /* Printing a pattern a bb bb ccc ccc ccc

dddd dddd dddd dddd /* //author Nitish Upreti // Try this program after reading the chapter on Arrays class pat2 { public static void main(String args[]) {

char ch[]={' ','a','b','c','d'}; int c,c1,c2,n=1;

for(c=1;c<=4;c++) { for(c1=1;c1<=n;c1++) { for(c2=1;c2<=n;c2++) System.out.print(ch[n]); System.out.println(); } n=n+1; }

} }

Example 3 /* A program that prints the following pattern 1234554321

1234 4321
123 321
12 21
1 1 */

// author Nitish Upreti

class pat3 { public static void main(String args[]) { int c,c1,i=5,d=5,c2,s,g=0; for(c=1;c<=5;c++) { for(c1=1;c1<=i;c1++) System.out.print(+c1);

i=i-1;

for(s=1;s<=g;s++) System.out.print(" "); g=g+2;

for(c2=d;c2>=1;c2--) System.out.print(+c2); d=d-1; System.out.println(); } } }

Example 4

/* A program that prints the following pattern

a

class pat4 {

public static void main(String args[])

{ int i,j,k,l,s=4; char ch[]={' ','I','N','D','I','A'};

for(i=1;i<=5;i++) { for(j=1;j<=s;j++) { System.out.print(" ");

} s=s-1; for(k=1;k<=i;k++) { System.out.print(ch[k]); } for(l=i;l>1;l--) { System.out.print(ch[l-1]); } System.out.println("\n");

} } }

Example 5. // A program to print the following pattern

    /* 7777777
        55555
        333
        1
        333
        55555
        7777777 /*
// author Nitish Upreti        
class pat5        
{        

public static void main(String args[]) { int c,c1,s,n=7;

for(c=1;c<=4;c++) {

for(s=1;s<c;s++) System.out.print(" ");

for(c1=1;c1<=n;c1++) System.out.print(+n);

n=n-2; System.out.println(); }

n=3; for(c=3;c>=1;c--) {

for(s=1;s<c;s++) System.out.print(" ");

for(c1=1;c1<=n;c1++) System.out.print(+n);

n=n+2; System.out.println();

} } }