Sunday, December 14, 2008

Java source code-3

Program 21

/* Write a program to generate Harmonic Series.

Example :

Input - 5

Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

double result = 0.0;

while(num > 0){

result = result + (double) 1 / num;

num--;

}

System.out.println("Output of Harmonic Series is "+result);

}

}

Program 22

/*Write a program to find average of consecutive N Odd no. and Even no. */

class EvenOdd_Avg{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;

while(n > 0){

if(n%2==0){

cntEven++;

sumEven = sumEven + n;

}

else{

cntOdd++;

sumOdd = sumOdd + n;

}

n--;

}

int evenAvg,oddAvg;

evenAvg = sumEven/cntEven;

oddAvg = sumOdd/cntOdd;

System.out.println("Average of first N Even no is "+evenAvg);

System.out.println("Average of first N Odd no is "+oddAvg);



}

}

Program 23

/* Display Triangle as follow : BREAK DEMO.

1

2 3

4 5 6

7 8 9 10 ... N */

class Output1{

public static void main(String args[]){

int c=0;

int n = Integer.parseInt(args[0]);

loop1: for(int i=1;i<=n;i++){

loop2: for(int j=1;j<=i;j++){

if(c!=n){

c++;

System.out.print(c+" ");

}

else

break loop1;

}

System.out.print("\n");

}

}

}

Program 24

/* Display Triangle as follow

0

1 0

1 0 1

0 1 0 1 */

class Output2{

public static void main(String args[]){

for(int i=1;i<=4;i++){

for(int j=1;j<=i;j++){

System.out.print(((i+j)%2)+" ");

}

System.out.print("\n");

}

}

}

Program 25

/* Display Triangle as follow

1

2 4

3 6 9

4 8 12 16 ... N (indicates no. of Rows) */

class Output3{

public static void main(String args[]){

int n = Integer.parseInt(args[0]);

for(int i=1;i<=n;i++){

for(int j=1;j<=i;j++){

System.out.print((i*j)+" ");

}

System.out.print("\n");

}

}

}

Post a Comment

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP