❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Collections Tasks

By: Sugirtha
19 November 2024 at 01:55

TASKS:

  • // 1. Reverse an ArrayList without using inbuilt method
  • // 2. Find Duplicate Elements in a List
  • // 3. Alphabetical Order and Ascending Order (Done in ArrayList)
  • // 4. Merge Two Lists and Remove Duplicates
  • // 5. Removing Even Nos from the List
  • // 6. Array to List, List to Array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


public class CollectionsInJava {
	public static void main(String[] args) {
		// 1. Reverse an ArrayList without using inbuilt method
		// 2. Find Duplicate Elements in a List 
		// 3. Alphabetical Order and Ascending Order (Done in ArrayList)
		// 4. Merge Two Lists and Remove Duplicates
		// 5. Removing Even Nos from the List
		// 6. Array to List, List to Array
		ArrayList<String> names = new ArrayList<>(Arrays.asList("Abinaya", "Ramya", "Gowri", "Swetha",  "Sugi", "Anusuya", "Moogambigai","Jasima","Aysha"));
		ArrayList<Integer> al2 = new ArrayList<>(Arrays.asList(100,90,30,20,60,40));
		
		ArrayList<Integer> al =  insertValuesIntoAL();
		System.out.println("Before Reversing ArrayList="+ al);
		System.out.println("Reversed ArrayList="+ reverseArrayList(al));
		
		System.out.println("Duplicates in ArrayList="+findDuplicates(al));
		
		System.out.println("Before Order = "+names);
		Collections.sort(names);
		System.out.println("After Alphabetical Order = " + names);
		Collections.sort(al);
		System.out.println("Ascending Order = "+ al);
		
		System.out.println("List -1 = "+al);
		System.out.println("List -2 = "+al2);
		System.out.println("After Merging and Removing Duplicates="+mergeTwoLists(al,al2));
		System.out.println("After Removing Even Nos fromt the List-1 = "+removeEvenNos(al));
		
		arrayToListViceVersa(al,new int[] {11,12,13,14,15}); //Sending ArrayList and anonymous array
	}
	
	// 1. Reverse an ArrayList without using inbuilt method
	private static ArrayList<Integer> reverseArrayList(ArrayList<Integer> al) {
		int n=al.size();
		int j=n-1, mid=n/2;
		for (int i=0; i<mid; i++) {
			int temp = al.get(i);
			al.set(i, al.get(j));
			al.set(j--, temp);
		}
		return al;
	}
	
	// 2. Find Duplicate Elements in a List 
	private static ArrayList<Integer> findDuplicates(ArrayList<Integer> al) {
		HashSet<Integer> hs = new HashSet<>();
		ArrayList<Integer> arl = new ArrayList<>();
		for (int ele:al) {
			if (!hs.add(ele)) arl.add(ele);
		}
		return arl;
	}
	
	//4. Merge Two Lists into one and Remove Duplicates
	private static HashSet<Integer> mergeTwoLists(ArrayList<Integer> arl1,ArrayList<Integer> arl2) {
		ArrayList<Integer> resAl = new ArrayList<>();
		HashSet<Integer> hs = new HashSet<>();
		hs.addAll(arl1);
		hs.addAll(arl2);
		return hs;
	}
	
	// 5. Removing Even Nos from the List
	private static ArrayList<Integer> removeEvenNos(ArrayList<Integer> al) {
		ArrayList<Integer> res = new ArrayList<>();
		Iterator itr = al.iterator();
		while (itr.hasNext()) {
			int ele = (int)itr.next();
			if (ele%2==1) res.add(ele);
		}
		return res;
	}
	
	// 6. Array to List, List to Array
	private static void arrayToListViceVersa(ArrayList<Integer> arl, int[] ar) {
		Integer arr[] = arl.toArray(new Integer[0]);
		System.out.println("Convert List to Array = " + Arrays.toString(arr));
		List<Integer> lst = Arrays.asList(arr);
		System.out.println("Convert Array to List = " +  lst);
	}
	
	private static ArrayList<Integer> insertValuesIntoAL() {
		Integer[] ar = {30,40,60,10,94,23,05,46, 40, 94};
		ArrayList<Integer> arl = new ArrayList<>();
		Collections.addAll(arl, ar);
		//Collections.reverse(al);   //IN BUILT METHOD
		return arl;
			//Arrays.sort(ar);  
		//List lst = Arrays.asList(ar);    //TBD
		//return new ArrayList<Integer>(lst);
		
	}

}

OUTPUT:

Finding SubArray

By: Sugirtha
30 October 2024 at 11:23
package taskPkg;

import java.util.Scanner;

public class SubArray {

	public static void main(String[] args) {
		// FINDING SUBARRAY AND ITS POSITION
		System.out.println("Enter a sentence to search in.");
		Scanner scn = new Scanner(System.in);
		String sentn = scn.nextLine();
		System.out.println("Enter a word to be searched.");
		String word = scn.next();
		scn.close();
		char[] sentence = sentn.toCharArray();
		char[] key = word.toCharArray();
		int n = sentence.length, m = key.length;
		int i = 0, j = 0, st = 0; // i- maintain index in the sentence, j-maintain index in key
		boolean match = false;
		while (i < n && j < m) {// 
			//System.out.println("i=" + i + "     sentence[i]=" + sentence[i] + "    j=" + j + "   key[j]=" + key[j]);
			if (sentence[i] == key[j]) { //if it matches incrementing both pos
				i++;
				j++;
				if (j == m) { //if the key reaches end, made the match and exit
					match = true;
					break;
				}
			} 
			else {    // if no match move on to the next letter, but key should start from 0
				j = 0;
				i=st+1;
				st = i;  // this is to save the starting of the subarray
			}
		}
		if (match)
			System.out.println("SubArray is found at " + st);
		else
			System.out.println("SubArray is not found");
	}
}

OUTPUT:

2D Matrix Addition, Multiplication, Largest in EachRow, Is Descending Order

By: Sugirtha
27 October 2024 at 17:25
package taskPkg;

public class MatrixCalc {
	public static void main(String[] args) {
		// 1. MATRIX ADDITION ( A + B )
		// 2. MATRIX MULTIPLICATION ( C*D ) IF C is nxk AND D IS kxm RESULTANT MUST BE
		// nxm
		int[][] A = { { 4, 2, 5 }, { 6, 3, 4 }, { 8, 1, 2 } };
		int[][] B = { { 5, 1, 3 }, { 2, 3, 2 }, { 1, 6, 4 } };
		int[][] C = { { 4, 2 }, { 2, 1 }, { 5, 3 } };
		int[][] D = { { 1, 2, 3 }, { 3, 2, 5 } };
		int[] desc = { 9, 5, 2, 1 };
		int[][] M = new int[C.length][D[0].length];

		MatrixCalc matOp = new MatrixCalc();
		matOp.add(A, B);
		System.out.println("-------------------------");
		matOp.multiply(C, D, M);
		System.out.println("-------------------------");
		matOp.LargestInEachRow(M);
		System.out.println("-------------------------");
		matOp.isDescendingOrder(desc);
	}

	private void add(int[][] A, int[][] B) {
		int r = A.length, c = A[0].length;
		int[][] S = new int[r][c];
		for (int i = 0; i < r; i++) {
			for (int j = 0; j < c; j++) {
				S[i][j] = A[i][j] + B[i][j];
			}
		}
		print2Darray(A, "A");
		print2Darray(B, "B");
		System.out.println("SUM : S = A+B");
		print2Darray(S, "S");
		System.out.println();
	}

	private void multiply(int[][] C, int[][] D, int[][] M) {
		int n = C.length, q = D.length, m = D[0].length;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				for (int k = 0; k < q; k++) {
					M[i][j] += C[i][k] * D[k][j];
				}
			}
		}
		print2Darray(C, "C");
		print2Darray(D, "D");
		System.out.println("MULTIPLY : M = CxD");
		print2Darray(M, "M");
	}

	private void LargestInEachRow(int[][] M) {
		int L[] = new int[M.length];
		System.out.println("LARGEST IN EACH ROW OF : M ");
		System.out.print("[");
		for (int i = 0; i < M.length; i++) {
			L[i] = M[i][0];
			for (int j = 0; j < M[0].length; j++) {
				L[i] = L[i] < M[i][j] ? M[i][j] : L[i];
			}
			System.out.print(" " + L[i] + " ");
		}
		System.out.println("]");
	}

	private void isDescendingOrder(int[] des) {
		boolean desc = true;
		System.out.print("Array des [");
		for (int i = 0; i < des.length; i++) {
			System.out.print(" " + des[i] + " ");
			if (i > 0 && desc && des[i - 1] < des[i])
				desc = false;
		}
		System.out.println("]");
		if (desc)
			System.out.println("Given Array des is In Descending Order");
		else
			System.out.println("Given Array des is NOT In Descending Order");
	}

	private void print2Darray(int[][] ar, String arName) {
		System.out.print("Array " + arName + " : ");
		for (int i = 0; i < ar.length; i++) {
			if (i > 0)
				System.out.print("          ");
			System.out.print("[");
			for (int j = 0; j < ar[0].length; j++) {
				System.out.print(" " + ar[i][j] + " ");
			}
			System.out.println("]");
		}
		System.out.println();
	}

}

OUTPUT:

Simple Student Mark List

By: Sugirtha
27 October 2024 at 10:08

import java.util.Scanner;

public class Array2DstudentsMarks {
	Scanner scn = new Scanner(System.in);
	String stud[];
	int[][] marks;
	int[] tot, highestScorer;
	int subj, totHighStud;
	public static void main(String[] args) {
		// STUDENTS MARKS WITH TOTAL - 2D ARRAY
		Array2DstudentsMarks twoDArray =  new Array2DstudentsMarks();
		twoDArray.studentMarksTotal();
		twoDArray.dispMarkAndTotal();
	}

	private void studentMarksTotal() {
		System.out.println("Enter no. of Students");
		int n = scn.nextInt();
		System.out.println("Enter no. of Subjects");
		subj = scn.nextInt();
		stud = new String[n];
		marks = new int[n][subj];
		tot = new int[n];
		highestScorer= new int[subj];
		int maxTot = 0, highScore=0;
		for (int i=0; i<n; i++) {
			System.out.println("Enter Student name.");
			stud[i] = scn.next(); 

			System.out.println("Enter "+subj+" subjects marks of "+stud[i]+" one by one.");
			for (int j=0; j<subj; j++) {
				marks[i][j] = scn.nextInt();
				tot[i] += marks[i][j];
				if (marks[highestScorer[j]][j] < marks[i][j]) {
					highestScorer[j] = i;
					//highScore = marks[i][j];
				}
			}
			if (maxTot < tot[i]) {
				maxTot = tot[i];
				totHighStud = i;
			}
		}
	}
	private void dispMarkAndTotal() {
		System.out.println("------------------------------------------------------------------------");
		System.out.println("                       STUDENTS MARK LIST                               ");
		System.out.println("------------------------------------------------------------------------");
		for (int i=0; i<stud.length; i++) {
			System.out.println("Student Name : "+stud[i]);
			for (int j=0; j<subj; j++) {
				System.out.println("Subject-"+(j+1)+" = "+marks[i][j]);
			}
			System.out.println();
			System.out.println("Total Marks = "+tot[i]);
			System.out.println("Percentage = "+(tot[i]/subj)+ "%");	
			System.out.println("------------------------------------------------------------------------");
		}
		for (int i=0; i<highestScorer.length; i++) {
			int student = highestScorer[i];
			System.out.println("Subject-"+(i+1)+" Highest Mark is "+marks[student][i]+" achieved by "+stud[student]);
		}
		System.out.println("------------------------------------------------------------------------");
		System.out.println("Over All Highest Total "+tot[totHighStud]+" achieved By "+stud[totHighStud]);
		System.out.println("------------------------------------------------------------------------");
	}
}

OUTPUT:

Playing with Char Array

By: Sugirtha
24 October 2024 at 09:23
    // 1. REMOVING UNWANTED SPACE
    // 2. CAPITALIZE EACH WORD
package taskPkg;

import java.util.Scanner;

public class PlayingWithCharAr {

	public static void main(String[] args) {
		// 1. REMOVING UNWANTED SPACE
		// 2. CAPITALIZE EACH WORD
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a sentence...");
		String sentence = scn.nextLine();
		scn.close();
		char[] sen = sentence.toCharArray();
		PlayingWithCharAr obj = new PlayingWithCharAr();
		obj.removeSpace(sen);
		obj.wordStartWithCaps(sen);
	}

	private void removeSpace(char[] words) {
		int k = 0, n = words.length;
		System.out.print("Removed unwanted spaces :");
		while (k < n && words[k] == ' ')
			k++;
		for (; k < n - 1; k++) {
			if (!(words[k] == ' ' && words[k + 1] == ' '))
				System.out.print(words[k]);
		}
		if (words[n - 1] != ' ')
			System.out.print(words[n - 1]);
		System.out.println();
	}

	private void wordStartWithCaps(char[] words) {
		int i = 0, n = words.length;
		System.out.print("Capitalize Each Word :");
		if (words[i] != ' ')
			System.out.print((char) (words[i] - 32));
		for (i = 1; i < n; i++) {
			if (words[i - 1] == ' ' && words[i] != ' ' && (words[i] >= 'a' && words[i] <= 'z'))
				System.out.print((char) (words[i] - 32));
			else
				System.out.print(words[i]);
		}
	}

}

OUTPUT:

Password Validator

By: Sugirtha
23 October 2024 at 18:17
import java.util.Scanner;

public class PasswordValidator {

	public static void main(String[] args) {
		// PASSWORD MUST CONTAIN MIN 8 CHARS, MAX 12 CHARS, ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT, 1 SPL CHAR 
		Scanner scn = new Scanner(System.in);
		int maxLen = 12, minLen=8;
		System.out.println("Enter a password to validate");
		String pwd = scn.next();
		scn.close();
		int n = pwd.length();
		if (n<minLen || n>maxLen) {
			System.out.println("Password length must be between 8 to 12 characters");
			return;
		}
		char[] pw = pwd.toCharArray();
		int cntLower=0, cntUpper=0, cntDigit=0, cntSpl=0;
		for (int i=0; i<n; i++) {
			char ch = pw[i];
			if (ch>='A' && ch<='Z') cntUpper++;
			else if (ch>='a' && ch<='z') cntLower++;
			else if (ch>='1' && ch<='9') cntDigit++;
			else if (ch=='!' || ch=='Β£' || ch=='$' || ch=='%' || ch=='^' || ch=='&' || ch=='*' || ch=='-' || ch=='_' || ch=='+' || ch=='=' || ch==':' || ch==';' || ch=='@'|| ch=='#'|| ch=='~'|| ch=='>'|| ch=='<'|| ch=='?'|| ch=='.') cntSpl++; 
		}
		if (cntLower>0 && cntUpper>0 && cntDigit>0  && cntSpl>0) System.out.println("Password is valid...");
		else {
			System.out.println("Password is NOT VALID");
			System.out.println("PASSWORD MUST CONTAIN ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT AND 1 SPL CHAR FROM ! Β£ $ % ^ & * - _ + = : ; @ ~ # ?");
		}
	}

}

Arrays Task

By: Sugirtha
22 October 2024 at 18:29
  1. First Letter Occurrence, Last Letter Occurrence in the given Word
  2. Print Reversed Array
  3. Cricketers array and their best score array – Give name as input and get the high score.
package taskPkg;
import java.util.Scanner;
public class ArraysBasics {
//1. PRINTING 1ST LETTER OF THE CHAR ARRAY
//2. PRINT REVERSED A CHAR ARRAY	
//3. 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArraysBasics obj = new ArraysBasics();
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a name to find its first and Last Letter.");
		String nam =  scn.next();
		char[] name = nam.toCharArray();
		System.out.println("First Letter of "+nam+" is repeated at "+obj.findFirstLtr(name));
		System.out.println("Last Letter of "+nam+" is repeated at "+obj.findLastLtr(name));
		obj.printReversedArray(name);
		System.out.println();  
		
		String[] cricketers = {"Rohit","Suryakumar","Ashwin", "Jadeja","Yashasvi"}; 
		int[] scores = {100,120,86,102,98};
		System.out.println("Enter one cricketer name to get his high score");
		String givenName = scn.next();
		System.out.println("Score for " + givenName+  " is "+obj.getScore(cricketers,scores,givenName));
		
		
	}
	private int findFirstLtr(char name[]) {
		char ch = name[0];
		for (int i=1; i<name.length; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private int findLastLtr(char name[]) {
		char ch = name[name.length-1];
		for (int i=0; i<name.length-1; i++) {
			if (ch==name[i]) return i;
		}
		return -1;
	}
	private void printReversedArray(char[] name) {
		System.out.println("Reversed Array = ");
		for (int i=name.length-1; i>=0; i--) {
			System.out.println(" "+name[i]);
		}
	}
	private int getScore(String[] name, int[] score, String givenName) {
		int n = name.length;
		for(int i=0; i<n; i++) {
			if(name[i].equals(givenName)) return score[i];
		}
		return 0;
	}
	
}

OUTPUT:

CALCULATOR

By: Sugirtha
21 October 2024 at 13:01
<html>
<head>
    <title>Simple Calculator</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Sugirtha">
    <meta name="description" content="Calculator using HTML, CSS, JavaScript">   
    <link rel="stylesheet" href="calc.css">
</head>
<body>
    <h2 align="center">CALCULATOR</h2>
<div class="borderContainer">
<div class="container" >
<div class="resultsContainer" ><input type="text" id="results" name="results" class="result" readonly></div>
<div class="numPadContainer">
    <p>
    <input type="button" value="7" class="button black" onclick='calc("7")'>
    <input type="button" value="8" class="button black" onclick='calc("8")'>
    <input type="button" value="9" class="button black" onclick='calc("9")'>
    <input type="button" value="/" class="button opr" onclick='calc("/")'>
    </p>
    <p>
    <input type="button" value="4" class="button black" onclick='calc("4")'>
    <input type="button" value="5" class="button black" onclick='calc("5")'>
    <input type="button" value="6" class="button black" onclick='calc("6")'>
    <input type="button" value="*" class="button opr" onclick='calc("*")'>
   </p>
    <p>
    <input type="button" value="1" class="button black" onclick='calc("1")'>
    <input type="button" value="2" class="button black" onclick='calc("2")'>
    <input type="button" value="3" class="button black" onclick='calc("3")'>
    <input type="button" value="-" class="button opr" onclick='calc("-")'>
    </p>
    <p>
    <input type="button" value="0" class="button black" onclick='calc("0")'>
    <input type="button" value="00" class="button black" onclick='calc("00")'>
    <input type="button" value="." class="button black" onclick='calc(".")'>
    <input type="button" value="+" class="button opr" onclick='calc("+")'>

    </p>
    <p>
    <input type="button" value="mod" class="button opr" onclick='calc("%")'>
    <input type="button" value="C" class="button red" onclick='results.value=""'>
    <input type="button" value="=" class="button orange" onclick='doOper()' >

   </p>
</div>
</div>
</div>
<script>
    var answered=false;
    function calc(val) 
    {
        optrs = "+-*/%"
        if (answered && !optrs.includes(val)) 
        {
         
                //alert("not included opr - clearing ans")
                document.getElementById("results").value="";
                
            
        }
        document.getElementById("results").value += val;
        answered=false;
    }
    function doOper()
    {
        try
        {
            dispAns(eval(document.getElementById("results").value));
            
        }
        catch
        {
            dispAns("Input Error");
        }
    }
    function dispAns(output) 
    {
        document.getElementById("results").value = output;
        answered=true;
    }

</script>
</body>
</html>
body 
{
    background-color:black;
    color:lightgrey;
}



.borderContainer 
{
    position:relative;
    top:10px;
    left:36%;
    width:370;
    height:500;
    background-color: lightgrey;
}
.container
{
    position:relative;
    left:8%;
    top:25px;
    width:310px;
    height:450px;
    background-color:#3d4543;
    border-radius:3px;
}
.numPadContainer
{
    position:relative;
    left:25px;
    top:40px; 
}
.result
{
    position:relative;
    left:24px;
    top:28px;
    background-color:#bccd95;
    color:black;
    text-align:right;
    height:40px;
    width:260px;
    border-radius:10px;
    border-color:white;
}
.button
{
    position:relative;
    color:white;
    border:none;
    border-radius:8px;
    cursor:pointer;
    width:48px;
    height:42px;
    margin-left:10px;
}
.button.black
{
    background-color:#303030; 
    border-radius:8px;
    border-bottom:black 2px solid;  
    border-top:2px 303030 solid; 
}
.button.red
{
    background-color:#cf1917;  
    border-bottom:black 2px solid; 
    font-weight:bold;
}
.button.opr
{
    background-color:grey;  
    border-bottom:black 2px solid; 

}
.button.orange
{
    background-color:orange;
    border-bottom:black 2px solid;
    width:110px;
    font-weight:bold;
}

OUTPUT:

Pattern Printing – Others

By: Sugirtha
21 October 2024 at 02:01
public class Patterns {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//PRINTING 1's and 0's IN SPECIFIC PATTERN
		int n=5;
		Patterns ptn = new Patterns();
		ptn.pattern1(n);
		System.out.println();
		ptn.pattern2(n);
		System.out.println();
		ptn.pattern3("SUGIRTHA");
	}
	private void pattern1(int n) {
		int val=0;
		for (int r=1; r<=n; r++) {
			val = r%2==0?0:1;
			for (int c=1; c<=n-r+1; c++) {
				System.out.print(" "+val);
				val=1-val;
			}
			System.out.println();
		}
	}
	private void pattern2(int n) {
		int val=1;
		for (int r=1; r<=n; r++) {
			for (int c=1; c<=n-r+1; c++) {
				System.out.print(" "+val);
			}
			val=1-val;
			System.out.println();
		}
	}
	private void pattern3(String name) {
		int n = name.length();
		for (int r=1; r<=n; r++) {
			for (int c=0; c<r; c++) {
				System.out.print(" "+name.charAt(c));  //TBD 
			}
			System.out.println();
		}
	}

}

OUTPUT:

Patterns – Printing Numbers 0-9

By: Sugirtha
20 October 2024 at 17:01
package taskPkg;

public class PatternsPrintNos {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PatternsPrintNos ptnNos = new PatternsPrintNos();
		int n=9;
		for (int i=0; i<=9; i++) {
			ptnNos.printNo(i,n);
			System.out.println();
		}
	}
	private void printNo(int num, int n) {
		int m=n/2+1;
		switch(num) {
		case 0:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || c==1 || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;			
		case 1:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (c==m) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 2:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || (r<=m && c==n) || (c==1 && r>=m)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 3:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || c==n) System.out.print(" *"); 
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 4:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if ((c==1 && r<=m) || c==m ||  r==m ) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 5:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==n || r==m || (r<=m && c==1) || (c==n && r>=m)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 6:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (c==1  ||  r==n || r==m || (r>m && c==n)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 7:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || (c==n-r+1)) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;
		case 8:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==m || r==n || c==1 || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;		
		case 9:
			for (int r=1; r<=n; r++) {
				for (int c=1; c<=n; c++) {
					if (r==1 || r==m || (c==1 && r<=m) || c==n) System.out.print(" *");
					else  System.out.print("  ");
				}
				System.out.println();
			}
			break;				
		}

	}
}

Output:

Patterns – Printing Name

By: Sugirtha
20 October 2024 at 15:03
public class PatternMyName {
	//  MY NAME - IN PATTERN PRINTING

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PatternMyName pattern = new PatternMyName();
		int n=9;
		pattern.printLtr("S",n);
		pattern.printLtr("U",n);
		pattern.printLtr("G",n);
		pattern.printLtr("I",n);
		pattern.printLtr("R",n);
		pattern.printLtr("T",n);
		pattern.printLtr("H",n);
		pattern.printLtr("A",n);
	}
	private void printLtr(String ltr,int n) {
		int m=n/2 +1;
		switch(ltr) {
			case "S":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if (r==1 || r==n || r==m || (c==1 && r<m) || (c==9 && r>m)) {
							if ((c==1 && r==1) || (r==n && c==n) || (r==m && (c==1 || c==n))) System.out.print("  ");
							else System.out.print(" *");
						}
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
				
			case "U":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ((c==1 && r<n)|| (c>1 && c<n && r==n) || (r<n && c==n))
								System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
			
			case "G":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ((r==1 && c!=1) || (c==1 && r!=1 && r!=n) || (r==n && c!=1 && c!=n) || (c==n && r>=m && r!=n) || (r==m && c>m)) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;

			case "I":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ( c==m || r==1 || r==n) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
				
			case "R":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ( (c==1 && r!=1) || (r==1 && c!=n && c!=1) || (c==n && r<m && r!=1) || (r==m && c!=n) || (r>m && c==m+(r-m))) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
				
			case "T":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ( c==m || r==1 ) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
				
			case "H":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ( c==1 || c==n || r==m) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;
			
			case "A":
				for (int r=1; r<=n; r++) {
					for (int c=1; c<=n; c++) {
						if ( (r<=m && (c==m-r+1 || c==m+r-1)) || r==m || (r>m && (c==1 || c==n))) System.out.print(" *");
						else System.out.print("  ");
					}
					System.out.println();
				}
				System.out.println();
				break;

		}
	}
}

OUTPUT:

Task – For Loop – Playing with Numbers

By: Sugirtha
17 October 2024 at 14:46
Armstrong, Neon, Perfect, Prime, emirP, Strong, Triangle Series
import java.util.Scanner;

public class forLoopPlayWithNos {
// USING FOR LOOP
//Code for Armstrong, Neon, Perfect, Prime, emirP, Strong Numbers
// Factorial, SumOfDigits, ReverseDigits, CountOfDigits, Power also used.
//Triangular Series : 1,3,6,10,15,21,28,....
	    // FOR PRINTING 
		private static void print(int n, String numType, boolean matched) {
			if (matched) System.out.println(n+"  is a " + numType +" Number.");
			else System.out.println(n+"  is not a " + numType +" Number.");
		}

		public static void main(String[] args) {
			// TODO Auto-generated method stub
			forLoopPlayWithNos loop = new forLoopPlayWithNos();
	        System.out.print("Enter a Number to Play = ");
	        Scanner scn = new Scanner(System.in);
	        int num = scn.nextInt();
	        scn.close();
			
	        forLoopPlayWithNos.print(num, "ArmStrong",loop.isArmstrongNo(num));
	        forLoopPlayWithNos.print(num, "Neon", loop.isNeonNo(num));
	        forLoopPlayWithNos.print(num, "Perfect",loop.isPerfectNo(num));
	        forLoopPlayWithNos.print(num, "Prime",loop.isPrimeNo(num));
	        forLoopPlayWithNos.print(num, "emirP",loop.isemirPNo(num));
	        forLoopPlayWithNos.print(num, "Strong",loop.isStrong(num));
			loop.tringangularSeries(num);
		}
		
		private boolean isArmstrongNo(int n) {
			//Sum of (each digit to the power of (No of digits)) == n
			// Ex. 371, 153 == 1^3 + 5^3 + 3^3 = 1+125+27
			int powSum=0, nod = countDigits(n);
			for (int num=n; num>0; num/=10) {
				powSum += findPower((num%10),nod);
			}
			if (n == powSum) return true;
			return false;
		}
		
		private boolean isNeonNo(int n) {
			//Neon = (Sum of digits of a squared number == number)
			// Ex 1,9,45,55
			int sqNum = n*n;
			if (n == sumOfDigits(sqNum)) return true;
			return false;
		}
		
		private boolean isPerfectNo(int n) {
			//Sum of its divisors (excluding n) == n
			//Ex. 6,28,496
			int sum=1;
			for(int i=2; i<n; i++) {
				if (n%i == 0) sum+=i; // Adding Divisors
			}
			if (sum==n) return true;
			return false;
		}
		
		private boolean isPrimeNo(int n) {
			// N number that can be divided exactly only by itself, ie n's divisors are 1 and n
			// Ex 2,3,5,7,11,13
			switch(n) {
			case 0,1:
				return false;
			case 2,3:
				return true;
			default:
				if (n%2 == 0) return false;
				else {
					for (int i=3; i*i<n; i+=2) {
						if (n%i == 0) {
							return false;
						}
					}
				}
			}
			return true;
		}
		
		private boolean isemirPNo(int n) {
			// A number and revereDigits of that number are prime
			int rev = reverseDigits(n);
			return (isPrimeNo(n) && isPrimeNo(rev))? true:false;
		}
		
		private boolean isStrong(int n) {
			//sum of the factorial of its digit is equal to number itself
			// Ex. 145 = 1!+4!+5!
			int sum = 0, num=n;
			for (num=n; num>0; num/=10) {
				sum += factorial(num%10);
			}
			return (n == sum)? true:false; 
		}
		
		private int findPower(int base, int pr) {
			// finding base to the power pr
			int res=1;
			for (; pr>=1; pr--) {
				res *= base;
			}
			return res;
		}
		
		private int reverseDigits(int num) {
			int rev = 0;
			for (; num>0; num/=10) {
				rev = rev*10 + num%10;
			}
			return rev;
		}
		private int countDigits(int num) { //Counting No. of Digits
			int cnt=0;
			for (; num>0; num/=10,cnt++); 
			return cnt;
		}
		private int sumOfDigits(int n) {
			int sum=0;
			for (; n>0; n/=10) {
				sum += n%10;
			}
			return sum;
		}
		
		private int factorial(int n) {
			int fact=1;
			for (int i=1; i<=n; i++) {
				fact *= i;
			}
			return fact;
		}	
		
		private void tringangularSeries(int n) {
			System.out.print("Tringangular Series : ");
			for (int tri=1, i=2; tri<=n; i++) {
				System.out.print(tri+" ");
				tri+=i;
			}
		}
}

OUTPUT:

Task – While Loop – Armstrong, Neon, Perfect, Prime, emirP, Strong

By: Sugirtha
13 October 2024 at 18:19
package taskPkg;

import java.util.Scanner;
public class PlayingWithNumbers {
//Code for Armstrong, Neon, Perfect, Prime, emirP, Strong Numbers
// Factorial, SumOfDigits, ReverseDigits, CountOfDigits, Power also used.
    	// FOR PRINTING 
	private static void print(int n, String numType, boolean givenNumType) {
		if (givenNumType) System.out.println(n+"  is a " + numType +" Number.");
		else System.out.println(n+"  is not a " + numType +" Number.");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PlayingWithNumbers loop = new PlayingWithNumbers();
        System.out.print("Enter a Number to Play = ");
        Scanner scn = new Scanner(System.in);
        int num = scn.nextInt();
        scn.close();
		

		PlayingWithNumbers.print(num, "ArmStrong",loop.isArmstrongNo(num));
		PlayingWithNumbers.print(num, "Neon", loop.isNeonNo(num));
		PlayingWithNumbers.print(num, "Perfect",loop.isPerfectNo(num));
		PlayingWithNumbers.print(num, "Prime",loop.isPrimeNo(num));
		PlayingWithNumbers.print(num, "emirP",loop.isemirPNo(num));
		PlayingWithNumbers.print(num, "Strong",loop.isStrong(num));
		
	}
	
	private boolean isArmstrongNo(int n) {
		//Sum of (each digit to the power of No of digits) == n
		int num=n, powSum=0, nod = countDigits(num);
		while (num > 0) {
			powSum += findPower((num%10),nod);
			num/=10;
		}
		if (n == powSum) return true;
		return false;
	}
	
	private boolean isNeonNo(int n) {
		//Neon = (Sum of digits of a squared number == number)
		int sqNum = n*n;
		if (n == sumOfDigits(sqNum)) return true;
		return false;
	}
	
	private boolean isPerfectNo(int n) {
		//Sum of its divisors (excluding n) == n
		int i=2, sum=1;
		while (i<n) {
			if (n%i == 0) sum+=i; // Adding Divisors
			i++;
		}
		if (sum==n) return true;
		return false;
	}
	
	private boolean isPrimeNo(int n) {
		// N number that can be divided exactly only by itself, ie n's divisors are 1 and n
		if (n<=1 || n%2 == 0) return false;
		if (n<=3) return true;
		int i=3;
		while (i < n) {
			if (n%i == 0) {
				return false;
			}
			i+=2;
		}
		return true;
	}
	
	private boolean isemirPNo(int n) {
		// A number and revereDigits of that number are prime
		int rev = reverseDigits(n);
		return (isPrimeNo(n) && isPrimeNo(rev))? true:false;
	}
	
	private boolean isStrong(int n) {
		//sum of the factorial of its digit is equal to number itself
		// Ex. 145 = 1!+4!+5!
		int sum = 0, num=n;
		while (num>0) {
			sum += factorial(num%10);
			num/=10;
		}
		return (n == sum)? true:false; 
	}
	
	private int findPower(int base, int pr) {
		// finding base to the power pr
		int res=1;
		while (pr>=1) {
			res *= base;
			pr--;
		}
		return res;
	}
	
	private int reverseDigits(int num) {
		int rev = 0;
		while (num>0) {
			rev = rev*10 + num%10;
			num/=10;
		}
		return rev;
	}
	private int countDigits(int num) { //Counting No. of Digits
		int cnt=0;
		while (num>0) {
			num/=10;
			cnt++;
		}
		return cnt;
	}
	private int sumOfDigits(int n) {
		int sum=0;
		while (n>0) {
			sum += n%10;
			n/=10;
		}
		return sum;
	}
	
	private int factorial(int n) {
		int i=1,fact=1;
		while (i<=n) {
			fact *= i;
			i++;
		}
		return fact;
	}	

}


Output:

Task-Password Validation

By: Sugirtha
9 October 2024 at 00:59

Code: TBD

<html>
    <head>
        <title> Password Validation </title>
        <style>
            body {
                background-color:black;
                color:green;
            }
            h1 {
                text-align:center;
                text-decoration:underline;
            }
           .inputTxt{
                color:black;
                background-color:lightgrey;
                border:green 2px solid;
                padding-left:10px;
                width:170px;
                height:24px;
                }
            .lbl {
                 padding:25px;
                 font-weight:bold;
                   
                }
            
            .button {
                background-color:lightgreen;
                color: black;
                border:2px solid green;
                border-radius:15px;
                font-size: 15px;
                vertical-align:9px;
                font-family:"sans-serief";
                font-variant:small-caps;
                font-weight:bold;
                width:170px;
                height:30px;
                text-align:center;
            }
            
        </style>
    </head>
    
    <body>
        <h1 > Password Validation </h1>
            <div align="center">
                <br>
                <form id="frmPw">
                    <table align="center">
                    <tr> 
                        <td> <label for = "idPw" class="lbl"> Password</label> </td>
                        <td> <input type="Password" name="namPw" id="idPw" class="inputTxt" placeholder="Pls enter the Password" minlength=8 maxlength=12>  </td>
                    </tr>
                    </table>
                <br><br>
                <input type="button" value="CLEAR" class="button" onclick="doClear()">&nbsp;&nbsp;
                <input type="submit" value="SUBMIT" class="button" onclick="validatePw()">
                </form>
            </div>
    </body>

    <script>
        function validatePw() {
            const pw = document.getElementById("idPw").value;
            var msg="";
            if (pw.length>12) msg += "Max 12 characters.  Limit exceeded....";
            else if (pw.length<8) msg += "Min 8 characters needed...";
            var containsNumbers = /\d/.test(pw); //TBD
            if (!containsNumbers) msg += "Atleast one digit expected    ";
            var containsUcaseAlphabet = /[A-Z]/.test(pw);  
            if (!containsUcaseAlphabet) msg+="Atleast one Upper Case Alphabet expected  ";
            var containsSpecial = /[!@#$%^&*]/.test(pw); 
            if (!containsSpecial) msg+="Atleast one Special Character expected";             
            if (msg  !== null && msg!='')  //TBD
            {
                alert(msg);
                return false;
            }
            else 
            {
                alert("Password Validation passed successfully...");
                return true;
            }
        }

        function doClear() {
            document.getElementById("frmPw").reset();      
        }
    </script>
</hmtl>

Output:

Task – ToDo List

By: Sugirtha
6 October 2024 at 17:08
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scaler=1">
    <style>
        body {
            background-color:black;
            color:green;
        }
        h1 {
            text-align:center;
            font-family:"courier";
            font-size:3em;
        }
        .inputTxt{
            background-color:lightgrey;
            width:250px;
            height:30px;
            color:black;
            border:green 2px solid;
            position:absolute;
            top:85px;
            left:560px;
            padding-left:10px;
            font-size:20px;
            font-family:"courier";
        }
        .todoList {
            border:solid 2px white;
            background-color:lightgreen;
            color:black;
            width:250px;
            position:fixed;
            top:115px;
            left:558px;
        }
        .lstitm {
             border:solid 0.5px green;
        }
        .delBtn {
            background-color:darkgreen;
            color:white;
            cursor:pointer;
            border:solid 2px black;
        }
        .paraText {
            padding:15px;
           // font-weight:bold;
            font-size:20px;
            font-family:"courier";
         }

    </style>
</head>
<body>
    <h1> TO-DO LIST</h1>
    <div id="divToDo" class="todoList"></div>
    <input id="txtInput" class="inputTxt" placeholder="Type your Task">  
    <script>
        var cnt=0;   //Maintain cnt for number of tasks here initialize to 0
        const input = document.getElementById("txtInput");     //Taking text control and assigning in input
        input.addEventListener("keydown",
            function(event) 
            {
                if (event.key=="Enter" && !input.value=="")   //Enter key pressed and textbox is not empty
                {
                    const para = document.createElement("para");
                    para.className="paraText";
                    para.textContent = input.value;           //assigning input value into para

                    const del = document.createElement("span"); //Delete button "x"
                    del.textContent = "X";          
                    del.className = "delBtn";

                    const listitem = document.createElement("div"); //creating parent container for both para(input text) and del
                    listitem.className="lstitm";
                    listitem.appendChild(del);
                    listitem.appendChild(para);

                    const list = document.getElementById("divToDo");  //adding that div listitem into another parent div(id=divToDo)
                    list.appendChild(listitem);
                    cnt++;                              //while adding the listitem, increment the count
                    input.value = "";
    
                    del.addEventListener("click",
                        function() 
                        {
                            cnt--;          //del button pressed, so count decremented and listitem removed
                            this.parentElement.remove();
                            if (cnt==0) 
                            {
                                alert("Wow!  Awesome!!! You have completed all Works!!! Now Plant a Tree...");
                            }
                        });           
                }
            });
    </script>

</body>
</html>

Output:

Task – SSLC Marks Total

By: Sugirtha
29 September 2024 at 12:22
<html>
    <head>
        <title> SSLC Marks </title>
        <style>
            body 
            {
                background-color:black;
                color:pink;
                font-family:arial;
            }
            h1 
            {
            text-align:center;
            color:pink;
            font-variant:small-caps;
            }

            th {
                background-color:pink;
                color:black;
                font-size: 20px;
                font-variant:small-caps;
               }
           .inputTxt{
                color:black;
                background-color:lightgrey;
                border:green 2px solid;
                padding-left:10px;
                width:170px;
                height:30px;
                font-size:20px;
                font-family:"Arial";
                }
            .lbl {
                 padding:25px;
                 font-weight:bold;
                   
                }
            
            .button {
                background-color:lightgrey;
                color: black;
                border:2px solid pink;
                border-radius:15px;
                font-size: 15px;
                vertical-align:9px;
                font-family:"sans-serief";
                font-variant:small-caps;
                font-weight:bold;
                width:170px;
                height:30px;
                text-align:center;
            }
            .output {
                font-family:"Arial";
                font-size:20px;
                font-weight:bold;
                padding-left:25px;
            }


            
        </style>
    </head>
    
    <body>
        <h1> SSLC Marks </h1>
        <table border="1" align=center>
            <thead>
                <th>Subjects</th> <th>Marks</th> 
            </thead>
            <tbody>
            <form id="frmMarks">
            <tr> 
                <td > <label for = "idTamil" class="lbl"> Tamil</label> </td>
                <td> <input type="text" name="txtTamil" id="idTamil" class="inputTxt">  </td>
            </tr>
            <tr> 
                <td> <label for = "idEng"  class="lbl"> English</label> </td>
                <td> <input type="text" name="txtEng" id="idEng" class="inputTxt"> </td>
            </tr>
            <tr> 
                <td> <label for = "idMath" class="lbl"> Maths</label> </td>
                <td> <input type="text" name="txtMath" id="idMath" class="inputTxt"> </td>
            </tr>
            <tr> 
                <td> <label for = "idSci"  class="lbl"> Science</label> </td>
                <td> <input type="text" name="txtSci" id="idSci" class="inputTxt"> </td>
            </tr>
            <tr> 
                <td> <label for = "idSS"  class="lbl"> Social Science</label> </td>
                <td> <input type="text" name="txtSS" id="idSS" class="inputTxt"> </td>
            </tr>
            <tr><td></td></tr<tr><td></td></tr>
             <tr> 
                <td> <label for = "idTot" class="output">Total Marks</label> </td>
                <td align="center"><output name="totMarks" id="idTot" class="output" form="frmMarks"></output</td>
            </tr>  
             <tr> 
                <td > <label for = "idPercent" class="output">Percentage %</label> </td>
                <td align="center"><output name="percent" id="idPercent" class="output" form="frmMarks"></output</td>
            </tr>  
        </tbody>
        </table>
        <br><br>
        <div align="center">
            <input type="button" value="CLEAR" class="button" onclick="doClear()"> &nbsp;&nbsp;&nbsp;
            <input type="button" value="CALC TOTAL & %"  class="button" onclick="calcTot()">
        </div>
        </form>

    </body>
    
    <script>
        function calcTot() {
            const tot = parseInt(document.querySelector("#idTamil").value) + parseInt(document.querySelector("#idEng").value) + parseInt(document.querySelector("#idMath").value) + parseInt(document.querySelector("#idSci").value) + parseInt(document.querySelector("#idSS").value);
            document.querySelector("#idTot").innerHTML = tot;
            alert(tot/5);
            document.getElementById("idPercent").innerHTML = Math.round((tot/5)*100)/100+"%";
        }
        function doClear() {
            document.querySelector("#frmMarks").reset();
            document.querySelector("#idTot").innerHTML="";    
            document.getElementById("idPercent").innerHTML="";       
        }
    </script>
</hmtl>

Output:

❌
❌