Program to find out sum of digits

🔢 Find the Sum of Digits of a Number (Java)

🧩 What problem are we solving?

We often need to find the sum of digits in a number — for example, to check whether a number is divisible by 3 or 9, or as a simple exercise in integer manipulation.

Given a number (like 111), the goal is to extract each digit, add them together, and display the total.
For 111, the result is 1 + 1 + 1 = 3.


⚙️ How it works (step by step)

  1. Start with a number, say a = 111.

  2. Initialize sum = 0.

  3. Repeat while a > 0:

    • Get the last digit using the modulo operator: d = a % 10

    • Add it to sum: sum = sum + d

    • Remove the last digit from the number using integer division: a = a / 10

  4. When a becomes 0, print the sum.


🧠 Example Walkthrough

Let’s trace the steps for a = 111:

Stepa    a % 10 (digit)    sum after addition    a / 10 (next a)
1111            1            1            11
211            1            2            1
31            1            3            0

✅ Final sum = 3


Main program

package com.vinod.test;


/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindSumOfDigits {
public static void main(String[] args) {
{
int sum, d;
int a = 111;
sum = 0;
for (int i = 1; i <= 10; i++) {
d = a % 10;
a = a / 10;
sum = sum + d;
}
System.out.println("Sum of Digit =" + sum);
}
}

}

Ouput

Sum of Digit =3


How to find out common elements between two arrays

🔗 Find Common Numbers Between Two Arrays (Java)

🧩 What problem are we solving?

Given two arrays of integers, the goal is to find and print all the numbers that appear in both arrays — i.e., the common elements or intersection of the two arrays.

For example:
If we have

Array 1 = [12, 13, 14, 15, 16, 17] Array 2 = [12, 18, 29, 15, 7, 17]

then the numbers common to both are 12, 15, and 17.


⚙️ How it works (step by step)

  1. Start with two arrays of integers.

  2. Loop through each element of the first array (array1).

  3. For each element in array1, loop through the second array (array2).

  4. If a match is found (array1[i] == array2[j]), print or store that number.

  5. Continue until all elements have been compared.

This approach compares every element in array1 with every element in array2, ensuring all common numbers are identified.


🧠 Example Walkthrough

StepCompareMatch?Common Numbers Found
112 vs 1212
213 vs all12
314 vs all12
415 vs 1512, 15
516 vs all12, 15
617 vs 1712, 15, 17

Output:

12 15 17


package com.vinod.test;


/**
 * Class to find common numbers from two arrays
 *
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindCommonNumbers {

public static void main(String[] args) {
int array1[] = { 12, 13, 14, 15, 16, 17 };
int array2[] = { 12, 18, 29, 15, 7, 17 };

for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
System.out.println(array1[i]);
}
}
}

}

}

Output

12
15
17


Program to find out Largest and Smallest Value in an Array

🔺 Find the Largest and Smallest Number in an Array (Java)

🧩 What problem are we solving?

Given an array of numbers, we need to identify the largest and smallest values without sorting the array.
This is one of the most fundamental problems in programming — often used to teach how to iterate, compare, and track state within a loop.

Example:
If we have

[35, 21, 44, 55, 22, 1, 7]

Then:
Largest value = 55
Smallest value = 1


⚙️ How it works (step by step)

  1. Initialize two variables:

    • largest = first element in the array (numbers[0])

    • smallest = first element in the array (numbers[0])

  2. Iterate through the array starting from the second element (index 1).

  3. For each element:

    • If the element is greater than largest, update largest.

    • If the element is smaller than smallest, update smallest.

  4. After scanning all elements, print both values.


🧠 Example Walkthrough

Let’s trace the logic for:

numbers = [35, 21, 44, 55, 22, 1, 7]
StepCurrent NumberLargestSmallest
Start353535
1213521
2444421
3555521
4225521
51551
67551

✅ Final Output:

Largest value 55 Smallest value 1


package com.vinod.test;

/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindLargestAndSmallestNumber {

public static void main(String[] args) {

int numbers[] = new int[] { 35, 21, 44, 55, 22, 1, 7 };
int smallest = numbers[0];
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest value " + largest);
System.out.println("Smallest value " + smallest);
}
}

Output

Largest value 55
Smallest value 1

 

Program to reverse a String without using StringBuilder

🔁 Reverse a String in Java (Without Using StringBuilder.reverse())

🧩 What problem are we solving?

The goal is to reverse the characters of a given string manually — without using built-in helper methods like StringBuilder.reverse().

This exercise helps understand string manipulation, loops, and index-based access in Java.

For example:
If the input is

"My Name is Vinod"

Then the output will be

"doniV si emaN yM"

⚙️ How it works (step by step)

  1. Start with an input string, e.g. "My Name is Vinod".

  2. Initialize an empty string reverse = "".

  3. Loop backward from the end of the string (str.length() - 1) to the beginning (0).

  4. For each character:

    • Append it to reverse.

  5. Once the loop completes, reverse will contain the reversed text.

  6. Print the reversed string.


🧠 Example Walkthrough

StepCurrent IndexCharacterReverse String
115dd
214odo
313ndon
412idoni
511VdoniV
610(space)doniV
Final0MdoniV si emaN yM

Final Output:
doniV si emaN yM


package com.vinod.test;


/**
 * Example to reverse a String without using StringBuilder reverse method.
 *@authorvinodkariyathungalkumaran
 *
 */
public class ReverseStringExample {

public static void main(String[] args) {
String str = "My Name is Vinod";
System.out.println("Input=" + str);
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
System.out.println("Output=" + reverse);
}

}

Ouput

Input=My Name is Vinod
Output=doniV si emaN yM

Algorithm and program to find out duplicate character in a String

🧮 Find Duplicate Characters in a String (Java)

🧩 What problem are we solving?

The goal is to analyze a given string and determine how many times each character appears — effectively identifying duplicate or repeating characters.

For example, given:

"My name is Vinod"

the output should display how often each character occurs:

Character : Count : 3 Character : a Count : 1 Character : s Count : 1 Character : d Count : 1 Character : e Count : 1 Character : V Count : 1 Character : y Count : 1 Character : i Count : 2 Character : M Count : 1 Character : m Count : 1 Character : n Count : 2 Character : o Count : 1

This problem is useful for understanding:

  • How to work with maps (HashMap)

  • How to iterate characters in a string

  • How to count frequencies of elements efficiently


⚙️ Algorithm (Step-by-Step)

  1. Create a HashMap<Character, Integer>
    → To store each character as a key and its count as the value.

  2. Convert the string into a character array
    → Use toCharArray() to easily loop through characters.

  3. Iterate through the character array
    → For each character:

    • If it’s already in the map → increment the count.

    • If not → add it with count = 1.

  4. Display the results
    → Print each key-value pair to show how many times each character occurs.


🧠 Example Walkthrough

Let’s trace through the string:
"My name is Vinod"

StepCharacterAlready in Map?ActionUpdated Count
1MAdd M=11
2yAdd y=11
3(space)Add space=11
4nAdd n=11
5aAdd a=11
6mAdd m=11
7eAdd e=11
8(space)Increment2
9iAdd i=11
10sAdd s=11
11(space)Increment3
12VAdd V=11
13iIncrement2
14nIncrement2
15oAdd o=11
16dAdd d=11

✅ Final Map contents printed in iteration order:

(space)=3, a=1, s=1, d=1, e=1, V=1, y=1, i=2, M=1, m=1, n=2, o=1

📘 Java Implementation

package com.vinod.test;

import java.util.HashMap;
import java.util.Map;

/**
 * FindDuplicateCharactorInString
 *
 * Problem:
 *   Count and identify duplicate characters in a given string.
 *
 * Algorithm:
 *   1. Create a HashMap to store each character and its frequency.
 *   2. Convert the input string into a char[] array.
 *   3. Iterate through the array:
 *        - If the character exists in the map, increment its count.
 *        - Otherwise, add it to the map with count = 1.
 *   4. Print all characters and their counts.
 *
 * Example:
 *   Input:  "My name is Vinod"
 *   Output:
 *     Character :   Count : 3
 *     Character : a Count : 1
 *     Character : s Count : 1
 *     Character : d Count : 1
 *     Character : e Count : 1
 *     Character : V Count : 1
 *     Character : y Count : 1
 *     Character : i Count : 2
 *     Character : M Count : 1
 *     Character : m Count : 1
 *     Character : n Count : 2
 *     Character : o Count : 1
 *
 * Time Complexity:
 *   O(n) – Each character is processed once.
 *
 * Space Complexity:
 *   O(k) – Where k is the number of unique characters.
 *
 * Author: Vinod Kariyathungal Kumaran
 */
public class FindDuplicateCharactorInString {

    public static void main(String[] args) {
        Map duplicateMap = new HashMap<>();

        String str = "My name is Vinod";
        char[] chrs = str.toCharArray();

        for (Character ch : chrs) {
            if (duplicateMap.containsKey(ch)) {
                duplicateMap.put(ch, duplicateMap.get(ch) + 1);
            } else {
                duplicateMap.put(ch, 1);
            }
        }

        duplicateMap.forEach((k, v) ->
            System.out.println("Character : " + k + " Count : " + v)
        );
    }
} 
 
Character :   Count : 3
Character : a Count : 1
Character : s Count : 1
Character : d Count : 1
Character : e Count : 1
Character : V Count : 1
Character : y Count : 1
Character : i Count : 2
Character : M Count : 1
Character : m Count : 1
Character : n Count : 2
Character : o Count : 1
 

Algorithm and program to reverse a Number in java

🔢 Reverse a Number in Java (Without Using Built-in Reverse Methods)

🧩 What problem are we solving?

The goal is to reverse the digits of an integer — for example, converting 122 into 221.
This is a classic example to understand how to work with loops, integer division, and the modulo operator in Java.


⚙️ Algorithm (Step by Step)

We want to rebuild the number by extracting its last digit and adding it to a new reversed number in each step.

Formula:

Reverse = (Reverse * 10) + (Number % 10) Number = Number / 10

Step-by-Step Example

Let’s take the input number 122:

StepNumberReverse CalculationReverse ResultNew Number
1122(0 × 10) + (122 % 10)212
212(2 × 10) + (12 % 10)221
31(22 × 10) + (1 % 10)2210

Final Output: 221


🧠 Key Concept

  • % (modulo) gives the last digit of a number.
    122 % 10 = 2

  • / (integer division) removes the last digit.
    122 / 10 = 12

  • Multiplying the current reverse by 10 shifts digits left to make room for the next digit.


📘 Java Implementation


package com.vinod.test;

/**
 * ReverseNumberExample
 *
 * Problem:
 *   Reverse the digits of an integer without using built-in reverse functions.
 *
 * Algorithm:
 *   1. Initialize reverse = 0.
 *   2. Repeat while number != 0:
 *        - Extract the last digit using number % 10.
 *        - Multiply reverse by 10 and add the extracted digit.
 *        - Divide number by 10 to remove the last digit.
 *   3. Print the reversed number.
 *
 * Example:
 *   Input:  122
 *   Output: 221
 *
 * Time Complexity:
 *   O(log10(n)) → proportional to the number of digits.
 *
 * Space Complexity:
 *   O(1)
 *
 * Author: Vinod Kariyathungal Kumaran
 */
public class ReverseNumberExample {
    public static void main(String[] args) {
        int reverse = 0;
        int number = 122;

        System.out.println("Input number = " + number);
        System.out.println("Intermediate steps:");

        while (number != 0) {
            reverse = (reverse * 10) + (number % 10);
            System.out.println("Reverse = " + reverse);
            number = number / 10;
            System.out.println("Number = " + number);
        }

        System.out.println("Reversed number = " + reverse);

        // Alternative method using StringBuilder
        StringBuilder sb = new StringBuilder(String.valueOf(122));
        System.out.println("Reversed number using StringBuilder = " + sb.reverse().toString());
    }
} 

🧩 Output

Input number = 122
Intermediate steps:
Reverse = 2
Number = 12
Reverse = 22
Number = 1
Reverse = 221
Number = 0
Reversed number = 221
Reversed number using StringBuilder = 221

How to find duplicate number between 1 to n th Numbers

Sample program and Algorithm

package com.vinod.test;


import java.util.ArrayList;
import java.util.List;


/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindDuplicateNumber {


public static void main(String a[]) {
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i <= 50; i++) {
numbers.add(i);
}
numbers.add(11);
FindDuplicateNumber duplicateNumber = new FindDuplicateNumber();
System.out.println("Duplicate Number in the list: " + duplicateNumber.findDuplicateNumber(numbers));
}

/**
     * Algorithm to find out the duplicate number from 1 to n th value
     *
     *1)First find out the sum of the all values in the array list
     *
     *2)Find out the sum of the 1 to n th values
     *
     *3) duplicate value = Frist step value- Second step value
     *
     *
     *@param numbers
     *@return
     */
public int findDuplicateNumber(List<Integer> numbers) {
int highestNumber = numbers.size() - 1;
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
int duplicate = sum - (highestNumber * (highestNumber + 1) / 2);
return duplicate;
}


}

Output

Duplicate Number in the list: 11

 

 

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts