Lab 5 - Sol
Lab 5 - Sol
Test Data:
Input number of terms: 5
Expected Output:
The even numbers are :2 4 6 8 10
The Sum of even Natural Number upto 5 terms : 30
import java.util.*;
public class Example {
public static void main(String[] args) {
Test Data:
Enter N: 4
Expected Output:
Sum is: 2.08333333333
import java.util.*;
public class Example {
public static void main(String[] args) {
double sum=0;
for(int i=1; i<=n;i++)
sum+=1.0/i;
System.out.println("Sum is: "+sum);
}
}
if(n<0)
System.out.println("Please enter a
postive number");
else {
float p=1;
for(int i=1; i<=n;i++)
p=p*x;
System.out.println(x+" raised to the
power "+ n+" is:"+p);
}
}
}
2. Write a program in Java to display the pattern like a right angle triangle
with a number. The pattern like :
1
22
333
4444
55555
3. Write a Java program that writes a wedge of stars. The user enters the
initial number of stars, and the program writes out lines of stars. Each line
has one few star than the previous line:
Test Data:
Initial number of stars: 7
Expected output:
*******
******
*****
****
***
**
*
import java.util.*;
public class Example {
public static void main(String[] args) {
for(int i=1;i<=n;i++){
for (int j=n; j>=i;j--)
System.out.print("*");
System.out.println();
}
}
}
A college offers a course that prepares students for a state licensing exam. You’ve
been given a list of 10 students. Next to each name is written a 1 if the student
passed the exam or a 2 if the student failed. Write a Java program to:
- Count the number of test results of each type.
- Display a summary of the test results.
- If more than eight students passed the exam,
display “Raise tuition.”
While loop:
import java.util.*;
public class Example {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int passes = 0; // number of passes
int failures = 0; // number of failures
int counter = 1; // student counter
int result; // one exam result from user
while ( counter <= 10 ) {
System.out.print("Enter result (1 = pass, 2 = fail): ");
result=input.nextInt();
if ( result == 1 )
passes = passes + 1;
else
failures = failures + 1;
counter++;
}
System.out.println( "Passed: "+passes+"\nFailed: "+ failures );
if ( passes > 8 )
System.out.println( "Raise Tuition" );
}
}
For loop:
import java.util.*;
public class Example {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int passes = 0; // number of passes
int failures = 0; // number of failures
int result; // one exam result from user
for (int counter =1; counter <= 10; counter++ ) {
System.out.print("Enter result (1 = pass, 2 = fail): ");
result=input.nextInt();
if ( result == 1 )
passes = passes + 1;
else
failures = failures + 1;
}
System.out.println( "Passed: "+passes+"\nFailed: "+ failures );
if ( passes > 8 )
System.out.println( "Raise Tuition" );
}
}