0% found this document useful (0 votes)
208 views

Java Programming Lab Assignment 1: Basic Programs

This document contains 8 Java programming assignments on basic concepts like arrays, loops, methods, and conditionals. The assignments include: 1. Sorting an array with the maximum value first, then minimum, then second maximum, etc. 2. Separating even and odd numbers in an array so that evens precede odds. 3. Removing duplicate elements from an array and returning the new length. 4. Finding two elements in an array whose sum equals a given integer. The document provides sample code solutions for each assignment to demonstrate concepts like looping through arrays, comparing values, and modifying arrays. It is a lab assignment on basic Java skills for students new to programming.

Uploaded by

Sanjana chowdary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
208 views

Java Programming Lab Assignment 1: Basic Programs

This document contains 8 Java programming assignments on basic concepts like arrays, loops, methods, and conditionals. The assignments include: 1. Sorting an array with the maximum value first, then minimum, then second maximum, etc. 2. Separating even and odd numbers in an array so that evens precede odds. 3. Removing duplicate elements from an array and returning the new length. 4. Finding two elements in an array whose sum equals a given integer. The document provides sample code solutions for each assignment to demonstrate concepts like looping through arrays, comparing values, and modifying arrays. It is a lab assignment on basic Java skills for students new to programming.

Uploaded by

Sanjana chowdary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

JAVA PROGRAMMING

LAB ASSIGNMENT 1

BASIC PROGRAMS

1. Read the radius and print the area of a circle

Code:
import java.util.Scanner;

class f1{

public static void main(String[] args)


{

double pi=3.14, a;

Scanner sc=new Scanner(System.in);

int r=sc.nextInt();

a= pi*r*r;
System.out.println("The area of the circle is"+a);

}
}

Output:

2. Read the number and check whether it is divisible by 3 and 5


import java.util.Scanner;

code
class q {

private static Scanner sc;


public static void main(String[] args)
{
int number;
sc = new Scanner(System.in);

System.out.print(" Please Enter any Number to Check whether it is


Divisible by 3 and 5 : ");
number = sc.nextInt();
if((number % 3 == 0) && (number % 5 == 0))
{
System.out.println("\n Given number " + number + " is Divisible by
3 and 5");
}
else
{
System.out.println("\n Given number " + number + " is Not
Divisible by 3 and 5");
}
}
}

3. Display Subject Name based on room number. If the user enters 604 then display
Java Programming , If the user enters 605 then display Python programming for any
other input display Invalid input to the user

Code

import java.util.*;

class f3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

if(n==604)
{

System.out.println("java programming");

elseif(n==605){
System.out.println("python programming");

else{
System.out.println("Invalid Input");

4. Print the sum of first n numbers. If n is 3 then print the sum of 1+2+3 to the user. Get n from
the user
import java.util.Scanner;
public class naturalnum {

public static void main(String[] args) {

int num, count, total = 0;

System.out.println("Enter the value of n:");

Scanner scan = new Scanner(System.in);

num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}

5. Print the sum of the series 1^ 2 +2^ 2 +3^ 2 up to n terms 6. Print the multiplication table by
getting the n from the user.

code:
import java.util.Scanner;

public class squaresum {

static void println(String string) {


System.out.println(string);
}

static void print(String string) {


System.out.print(string);
}

static void printSeries(int n, int total) {


int i = 1;
for (i = 1; i < n; i++) {
print(i + "^2 +");
}
print(i + "^2 = " + total);
}

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
//get value of n from user
println("Enter value of 'n' : ");
int n = scanner.nextInt();

//calculate the sum of the series


int sum = (n * (n + 1) * (2 * n + 1 )) / 6;

//print the series


printSeries(n,sum);

}
}

6. Print the multiplication table by getting the n from the user

code:

import java.util.Scanner;
class mul
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of " + n);

for (c = 1; c <= 10; c++)


System.out.println(n + "*" + c + " = " + (n*c));
}
}
7. Provide the option of adding two numbers to the user until the user wants to exit. 8.
Print this pattern for n lines

Code:
port java.util.Scanner;
public class add
{
public static void main(String[] args)
{
int m, n, opt, add;
double div;
Scanner s = new Scanner(System.in);
System.out.print("Enter first number:");
m = s.nextInt();
System.out.print("Enter second number:");
n = s.nextInt();
while(true)
{
System.out.println("Enter 1 for addition");

System.out.println("Enter 2 to Exit");
opt = s.nextInt();
switch(opt)
{
case 1:
add = m + n;
System.out.println("Result:"+add);
break;

case 5:
System.exit(0);
}
}
}
}

8. Print this pattern for n lines


a)
public class firstpattern{
public static void main(String[] args) {
int rows = 4;
for(int i = 1; i <= rows; ++i) {
for(int j = 1; j <= i; ++j) {
System.out.print(" * ");

System.out.println(" ");
}
}
}

b)
import java.util.Scanner;

public class secondpattern


{
public static void main(String[] args)
{
// Create a new Scanner object
Scanner scanner = new Scanner(System.in);

// Get the number of rows from the user


System.out.println("Enter the number of rows to print the pattern ");

int rows = scanner.nextInt();

System.out.println("");

for (int i = rows; i >= 1; i--)


{
for (int j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
}
}
c)
import java.util.Scanner;

public class thirdpattern


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

//Taking rows value from the user

System.out.println("Number of rows:");

int rows = sc.nextInt();

System.out.println("Output pattern");

//Printing upper half of the pattern

for (int i = 1; i <= rows; i++)


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

System.out.println();
}
//Printing lower half of the pattern

for (int i = rows; i >= 1; i--)


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

System.out.println();
}

//Closing the resources

sc.close();
}
}
Exercise programs Based on Array

1. Write a Java program to sort an array of positive integers of an given array, in the sorted array
the value of the first element should be maximum, second value should be minimum value,
third should be second maximum, fourth second be second minimum and so on.

import java.util.Scanner;

public class array{

public static void main (String[] args)

int b=0;

Scanner s=new Scanner(System.in);

int n=s.nextInt();
int a[]=new int[n];

for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[j]<a[i])
{

b=a[j];
a[j]=a[i];
a[i]=b;
}
}
}

for(int i:a)
{
System.out.println("The sorted array is"+i);
}
}
}

2. Write a Java program to separate even and odd numbers of a given array of integers. Put all
even numbers first, and then odd numbers.
// Java program to segregate even and odd elements of array
import java.io.*;
import java.util.*;
class evenodd
{
static void segregateEvenOdd(int arr[])
{
/* Initialize left and right indexes */
int left = 0, right = arr.length - 1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left]%2 == 0 && left < right)
left++;

/* Decrement right index while we see 1 at right */


while (arr[right]%2 == 1 && left < right)
right--;

if (left < right)


{
/* Swap arr[left] and arr[right]*/
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}

public static void main (String[] args)


{
int arr[] = { 786, 54, 222, 87, 411, 46, 763};

segregateEvenOdd(arr);

System.out.print(" ");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
}
3. Write a Java program to remove the duplicate elements of a given array and return the
new length of the array
public class RemoveDuplicate{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1])
{ temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

public static void main (String[] args)


{ int arr[] =
{89,52,45,89,51,32,51,23};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}

4. Write a Java program to find the sum of the two elements of a given array which is equal to a
given integer.
import java.util.*;
public class sumg
{
public static ArrayList<Integer> two_sum_array_target(final List<Integer> a, int b) {

HashMap<Integer, Integer> my_map = new HashMap<Integer, Integer>();


ArrayList<Integer> result = new ArrayList<Integer>();
result.add(0);
result.add(1);
for(int i = 0; i < a.size(); i++)
{ if(my_map.containsKey(a.get(i))){
int index = my_map.get(a.get(i));
result.set(0, index );
result.set(1, i );
break;
}
else{
my_map.put(b - a.get(i), i);
}
}

return result;
}

public static void main(String[] args){


ArrayList<Integer> my_array = new ArrayList<Integer>();
my_array.add(1);
my_array.add(2);
my_array.add(4);
my_array.add(5);
my_array.add(6);
int target = 6;
ArrayList<Integer> result = two_sum_array_target(my_array, target);
for(int i : result)
System.out.print("Index: "+i + " ");
}
}
5. Display the sum of rows in a matrix

import java.util.*;
import java.io.*;
public class sumrow
{
public static void main(String[] args) {
int rows, cols, sumRow, sumCol;

int a[][] = {
{87, 90, 71},
{79, 54, 58},
{73, 80, 94}
};

//Calculates number of rows and columns present in given matrix


rows = a.length;
cols = a[0].length;

//Calculates sum of each row of given matrix


for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++)
{ sumRow = sumRow + a[i]
[j];
}
System.out.println("Sum of " + (i+1) +" row: " + sumRow);
}

//Calculates sum of each column of given matrix


for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++)
{ sumCol = sumCol + a[j][i];
}
System.out.println("Sum of " + (i+1) +" column: " + sumCol);
}
}
}

6. Display the addition of two matrix


public class addmat{
public static void main(String args[]){
//creating matrix
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}}
7. Display the transpose of a matrix
import java.util.Scanner;
class TransposeAMatrix
{
public static void main(String args[])
{
int m, n, c, d;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();

int matrix[][] = new int[m][n];

System.out.println("Enter elements of the matrix");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
matrix[c][d] = in.nextInt();

int transpose[][] = new int[n][m];

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
transpose[d][c] = matrix[c][d];

System.out.println("Transpose of the matrix:");

for (c = 0; c < n; c++)


{
for (d = 0; d < m; d++)
System.out.print(transpose[c][d]+"\t");

System.out.print("\n");
}
}
}
8. Write a program to demonstrate the knowledge of students in multidimensional arrays and
looping constructs. Eg., If there are 4 batches in BTech - “CSE1007” course, read the count of the
slow learners (who have scored

importjava.util.Scanner;

public class arr {

public static void main(String[] args) {

int i, j;

double t;

int arr[][] = new int[4][];

// input for each batch

Scanner sc = new Scanner(System.in);

for(i = 0; i < arr.length; i++){

System.out.print("Enter number of students for batch " + (i+1) + ": ");


t = sc.nextDouble();

arr[i] = new int[(int)Math.ceil(t/4)];

for(j = 0; j < arr[i].length; j++)

if(t >= 4)

arr[i][j] = 4;

else

arr[i][j] = (int)t;

t = t - 4;

sc.close();

int cfour = 0;

System.out.println("Contents of 2D Jagged Array");

for (i = 0; i < arr.length; i++) {

for (j = 0; j < arr[i].length; j++) {

System.out.print(arr[i][j] + " ");

if(arr[i][j] == 4)

cfour++;

System.out.println();

System.out.println("Number of tutors with 4 students are: " + cfour );

}
}
PROGRAMS BASED ON CLASSES AND OBJECTS

1. Design a class named Rectangle to represent a rectangle. The class contains: Two
double data fields named width and height that specify the width and height of the
rectangle. The default values are 1 for both width and height.
(i)A default constructor that creates a default rectangle.

(ii)A constructor that creates a rectangle with the specified width and
height.

(iii)A method named getArea() that returns the area of this

rectangle. (iv)A method named getPerimeter() that returns the

perimeter.

Implement the class. Write a test program that creates two Rectangle objects—one
with width 5 and height 50 and the other with width 2.5 and height 45.7. Display
the width, height, area, and perimeter of each rectangle in this order

CODE:
public class Rectangle {
// variable declarations
private double height;
private double width;
// default constructor
public Rectangle(double wid, double high){
height = high;
width = wid;
}
// parametrized constructor
public Rectangle(){
height = 1;
width = 1;
}
// return area of rectangle

public double getArea(){


return height*width;

}
// returns parameter of a rectangle
public double getPerimeter()
{ return 2*(height + width);
}
// returns width
public double getWidth(){
return width;
}
// returns height
public double getHeight(){
return height;
}
public static void main(String[] args){
// creating objects
Rectangle box1 = new Rectangle(4, 40);
Rectangle box2 = new Rectangle(3.5, 35.9);
// calling methods
System.out.println("Width: " + box1.getWidth());

System.out.println("Height: " + box1.getHeight());

System.out.println("Perimeter: " + box1.getPerimeter());

System.out.println("Area: " + box1.getArea() + "\n");

System.out.println("Width: " + box2.getWidth());

System.out.println("Height: " + box2.getHeight());

System.out.println("Perimeter: " + box2.getPerimeter());

System.out.println("Area: " + box2.getArea());


}
}

2. Write a Java program to create a class called Student having data members Regno,
Name, Course being studied and current CGPA. Include constructor to initialize
objects. Create array of objects with at least 10 students and find 9-pointers.

class ObjectArray{
public static void main(String args[]){

Studentdetails obj=new Studentdetails();


for ( int i=0; i<10; i++) {

obj[i]=new Student();
}

obj[0].setreg(1);
obj[1].setcourse("CSE2001");
obj[2].setcgpa(8.5);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element
1"); obj[1].showData();
}
}
class Student{
int x;
String y;
String w;
int v;
public void setregno(int c){
x=c;
public void setcourse(String b){
y=b;

public void setname(String d){


w=d;
}
public void setcgpa(int b){
v=b;

public void showData()


{ System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}

3. Write a Java program that displays that displays the time in different formats in
the form of HH,MM,SS using constructor Overloading.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {

public static void getCurrentTimeUsingDate() {


Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);

String formattedDate= dateFormat.format(date);


System.out.println("Current time of the day using Date - 12 hour format: " +
formattedDate);
}
public static void main (String[] args) {

CurrentTimeDateCalendar dw = new CurrentTimeDateCalendar();


System.out.println("Student Age is: "+dw.getCurrentTimeUsingDate());

}
}

You might also like