Tuesday, 30 July 2024

Duck Number - Java

A Duck number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. For example 3210, 1260, 70910 are all duck numbers whereas 03210, 025980 are not.

Let's see the Java program to determine if a number is DUCK Number or not.

import java.util.Scanner;

class HelloWorld 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String n;
        char ctr = 0;
        char chr = ' ';
        System.out.println("Enter a number");
        n = sc.nextLine();
        int length = n.length();
        for(int i = 1;i<length;i++)
        {
            chr = n.charAt(i);
            if(chr == '0')
            {
                ctr++;
            }
        }
        char firstindex = n.charAt(0);
        if(ctr > 0 && firstindex!='0')
        {
            System.out.println("Duck number");
        }
        else
        {
            System.out.println("Not a Duck number");
        }
    }
}


Sunday, 28 July 2024

Bubble Sorting in Java

Bubble sort is a sorting algorithm that works by repeatedly iterating through the array comparing each pair of adjoining elements and swapping them if they are in the wrong order.

Let us understand how Bubble sorting works with diagrammatic representation:

Say for example, if we have array elements as shown below:

65, 47, 70, 9

Pass 1:

To begin with, the element at 0th and 1st index are compared. Their positions are swapped, if element at 0th index is greater than element at 1st index.

Since, 65 is greater than 47, swap occurs.

Now, elements at 1st and 2nd index are compared.
Since, 65 is less than 70, no swap required.

Now, elements at 2nd and 3rd index are compared.

Since, 70 is greater than 9, swap occurs and now, the list will look like this.

In the next pass, the second highest number is placed in the second last position and so on.  This process will keep on repeating until the entire array is sorted.

Below program will teach you how to sort the numbers in an array using Bubble Sorting.

class BubbleSort
{
    public static void main(String[]args)
    {
        int list[] = {65,47,40,9,37,72,45,17};
        int len = list.length;
        for(int i = 0;i<len-1;i++)
        {
            for(int j = 0;j<len-i-1;j++)
            {
                if(list[j]>list[j+1])
                {
                    //swapping of adjacent elements done here
                    int tmp = list[j];
                    list[j] = list[j+1];
                    list[j+1] = tmp;
                }
            }
        }
        System.out.println("Sorted array is");
        for(int i = 0;i<len-1;i++)
        {
            System.out.println(list[i]);
        }
    }
}

Demonstration:

1. A class namely BubbleSort have been defined.
2. A main method have been defined.
3. An array namely list of int data type has been declared and unsorted elements are stored in it.
4. Stores the length of list in len variable.
5. The outer loop iterates through the entire array.

6. Inner loop iterates through the remaining unsorted array only. It is done by subtracting the value of counter variable i in inner loop test condition (len-i-1).
7. Compares two adjacent elements, i.e. element at jth position and that as (j+1)th position.
8. Stores the value of the current element in a temporary variable.
9. Stores the value of the next element of the array in the current element.
10. Stores the value of the temporary variable in the next element

Lead Number in Java



If the sum of even digits is equal to the sum of odd digits, then such numbers are called lead numbers.

Example: 3669,3544 etc

Say for example, if you have 3669 then sum of even numbers in the given number

6+6 = 12

Sum of odd numbers in the given number

3+9 = 12

As it can be seen that sum of even numbers and sum of odd numbers are equal. Hence, it is a Lead number.

Let's see the Java program to determine if a number is LEAD Number or not.


import java.util.Scanner;
class LEAD 
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        int n, sum1 = 0,sum2 = 0;
        System.out.println("Enter a number");
        n = sc.nextInt();
        while(n!=0)
        {
            int d = n%10;
            if(d%2==0)
            {
                sum1 = sum1+d;
            }
            else
            {
                sum2 = sum2+d;
            }
        n = n/10;
        }
        if(sum1 == sum2)
        {
            System.out.println("Given number is a lead number");
        }
        else
        {
            System.out.println("Given number is not a lead number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely LEAD have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type
7. Then, two different variables namely
    a) sum1 - This variable will store the sum of even digits. First, it is initialized with 0.
    b) sum2 - This variable will store the sum of odd digits. First, it is initialized with 0.

Now, let us see the working:

while(n!=0)

This loop iteration will continue till the index position doesn't becomes 0.

Refer to the below diagram for clear understanding.

As it can be seen that loop will start its operation from index position 3 and the element at index 3 is 9. It will continue till index position 0 reaches.

For example, in first loop iteration, first element 9 will be extracted, then with the help of if else statement, it will be examines if 9 is divisible by 2 or not. If it is divisible by 2, then the number will be added to the sum1 variable or else it will be added to the sum2 variable. In this case, 9 is not divisible by 2 and hence, it will be added to the sum2 variable.

Like this, it will keep on checking the individual numbers until the index position does not reaches 0.

n = n/10; will ensure that the number is deleted permanently deleted.

In previous operation, we have seen that the first extracted number using n%10 was 9. Immediately, after the if...else operation, n = n/10; will be executed which means 3669 is now going to be divided by 10 resulting to 366.9. This operation will permanently delete this 9 from n variable. so that in next iteration, 9 doesn't gets counted during execution of the while loop. Like this, it will keep on deleting the digits from n variable.

Here is the final outcome of the program:

As 3669 is taken as the example, hence

sum1 is carrying = 12 (i.e. 6+6)
sum2 is carrying = 12 (i.e. 3+9)

Now, with the help of if...else conditional statement outside the while loop, it is getting identified if the numbers contained within sum1 and sum2 variables are equal or not. If they are equal, it is a Lead number or else, it is not a lead number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......


Monday, 22 July 2024

String case conversion and replacing vowel with next character following it




Write a Java Program to accept a string from user, convert it into uppercase and then replace the vowels with the next character following it.


Hint:
Input: Computer
Output: CPMPVTFR

Answer:

import java.util.Scanner;
class Vowelreplace
{
    public static void main(String[]args)
    {
        Scanner sr = new Scanner(System.in);
        int i,len;
        String word,newword = "";
        char ch;
        System.out.println("Enter a Word:");
        word = sr.nextLine();
        word = word.toUpperCase();
        len = word.length();
        for(i = 0;i<len;i++)
        {
            ch = word.charAt(i);
            if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
            {
                char nextchar = (char)(ch+1);
                newword = newword+nextchar;
            }
            else
            {
                newword = newword+ch;
            }
        }
        System.out.println("The converted string is:"+newword);
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely Vowelreplace have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. To accept and store the word, a variable namely word has been defined of String data type.
6. Another variable namely newword has been declared for holding the converted string and a blank space has been assigned to it using "".
7. The variable ch will contain the individual characters in a string on basis of index positions.
8. A word has been demanded from user by giving a message.
9. The user input will get stored into word namely variable.
10. Then, the entered word will be converted to uppercase letters using string accessor method.
11. Then, length of the entered word will be stored in an integer variable namely len.
12. Then, a for loop will iterate and iteration will start for the variable namely i which is assigned with the value of 0. It means that loop will start from 0 index position and it will keep on executing till i doesn't reach less than length of the word.
13. In each loop iteration, ch will contain the individual character from the 1st index position.
14. Then, with the conditional statement, it will be determined if ch is containing any vowel or not.
15. Then, another character variable namely nextchar has been declared and with typecasting, character has been incremented by 1 which means, if any vowel is detected, then, that vowel will be added by 1 which in turn will display next character following that vowel.
16. Then, newword variable will add the previous blank space with the value at nextchar.
17. If any vowel doesn't gets detected, then the statement at the else block will get executed.
18. Finally, the entire converted word gets stored in newword variable which has been displayed outside the if...else block as it can be seen in the program.

Now, write this program and test it with various words and increase your knowledge.

Happy Coding.......


NEON Number - Java





A neon number is a number where the sum of digits of the square of the number is equal to the number.

Example: 0,1 and 9

Say for example, if you have 9 then square of 9 is 81.

8+1 = 9

As it can be seen that sum of digits of the square of the number is equal to the number. Hence, it is a NEON number.

Let's see the Java program to determine if a number is NEON Number or not.

import java.util.Scanner;

class NEON

{

    public static void main(String[]args)

    {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a number");

        int n = sc.nextInt();

        int sum = 0,temp = n, square;

        square = n*n;

        while(square!=0)

        {

            sum+=square%10;

            square/=10;

        }

        if(sum == n)

        {

            System.out.println("It is a NEON number");

        }

        else

        {

            System.out.println("It is not a NEON number");

        }

    }

}


Demonstration:

1. First, Scanner class is imported.
2. A class namely NEON have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type
7. Then, three different variables namely
    a) sum - This variable will store the sum of digits in the variable square. First, it is initialized with 0.
    b) temp - This variable will hold the number given by user on temporary basis.
    c) square - This variable will store the square of the number given by user.

Now, let us see the working:

square = n*n;

This above operation will evaluate the square of the number given by user. Say for example, user gave 9. Here, first square of 9 will be evaluated using this statement.

while(square!=0)

This loop will continue its iteration until value of square doesn't become equals to 0.

Square of 9 is 81. So, first 1 will be extracted, then 8 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.




sum+ = square%10;

Here, we need to understand few things.

First, individual digits from number is getting extracted using square%10.
As in case of 81, the first extracted number using square%10 will be 1.
Then, this number will get added to the variable sum.
Similarly, second number using square%10 will be 8 and it will also be added to sum.

Now, sum is containing 1+8 = 9

square/=10;

In previous operation, we have seen that the first extracted number using square%10 was 1. Immediately, after this operation, square/=10; will be executed which means 81 is now going to be divided by 10 resulting to 8.1. This operation will permanently delete this 1 from square variable. so that in next iteration, 1 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from square variable.

Here is the final outcome:

sum is now containing sum of square of number i.e. 8+1 = 9
n variable is containing the number i..e 9

Finally, with the conditional statement using if-else, it is determined if sum is equal to n or not as it can be seen in the program. If sum is equal to n, then it is displaying that the number is a NEON number. Otherwise, it is displaying that the number is not a NEON number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......


Sunday, 21 July 2024

Dudeney Number - Java

A Dudeney number is a positive integer for which the sum of its digits is equal to the the cube root of the number itself.

For example - 512

5+1+2=8

83 = 512

Here is the java code for determining if a number is Dudeney or not.

import java.util.Scanner;
class Dudeney
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        int sum = 0,temp = n, cube = 0;
        while(temp!=0)
        {
            sum+=temp%10;
            temp/=10;
        }
        cube = sum*sum*sum;
        if(cube == n)
        {
            System.out.println("It is a Dudeney number");
        }
        else
        {
            System.out.println("It is not a Dudeney number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely Dudeney have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type
7. Then, three different variables namely
    a) sum - First, the individual digits will be extracted due to the presence of temp%10. Then, these individual digits shall get added to sum.
    b) temp - This variable will hold the number given by user on temporary basis. Actually, entire operation will be done with temp variable. temp = n means the value stored in n namely variable is getting assigned to temp. It means that throughout the entire operation, original value stored in n namely variable will remain safe.
    c) cube - This variable will hold the cube of the number that is stored in sum.

Now, let us see the working:

while(temp!=0)

This loop will continue its iteration until value of temp doesn't become equals to 0. Say for example, user gave 512. Here, first 2 will be extracted, then 1 and at last, 5 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.



sum+ =temp%10;

Here, we need to understand few things.

First, individual digits from given number is getting extracted using temp%10 and getting stored in sum.
As in case of 512, the first extracted number using temp%10 will be 2.
Similarly, second number using temp%10 will be 1 and it will also be added to sum.
At last, third number using temp%10 will be 5 and it will also be added to sum.

N
ow, sum is containing 2+1+5 = 8

temp/=10;

In previous operation, we have seen that the first extracted number using temp%10 was 2. Immediately, after this operation, temp/=10; will be executed which means 512 is now going to be divided by 10 resulting to 51.2. This operation will permanently delete this 2 from temp variable. so that in next iteration, 2 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from temp variable.


Here is the final outcome:

sum is now containing sum of digits i.e. 5+1+2 = 8
n variable is containing 512

cube = sum*sum*sum;

This operation outside the while loop will find the product of sum variable and that product will be assigned to cube.

Now, cube is containing 512

Finally, with the conditional statement using if-else, it is determined if cube is equal to n or not as it can be seen in the program. If cube is equal to n, then it is displaying that the number is a Dudeney number. Otherwise, it is displaying that the number is not a Dudeney number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......


























Armstrong Number - Java






Armstrong Number is a number that is equal to the sum of cubes of its digits.

Example - 0,1,153,370,371 etc.

For example, if you have 153, it is an Armstrong number because 13+53+33 = 153;

Let's see the java program for determining if a number is Armstrong Number or not.

import java.util.Scanner;
class Armstrong
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        int sum = 0,temp = n, arm = 0;
        while(temp!=0)
        {
            arm =temp%10; 
            sum+= Math.pow(arm,3); 
            //It can also be written as sum+= (arm*arm*arm);
            temp/=10;
        }
        if(sum == n)
        {
            System.out.println("It is an Armstrong number");
        }
        else
        {
            System.out.println("It is not an Armstrong number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely Armstrong have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type
7. Then, three different variables namely
    a) sum - This variable will store the cubes of each digit in number. First, it is initialized with 0.
    b) temp - This variable will hold the number given by user on temporary basis. Actually, entire operation will be done with temp variable. temp = n means the value stored in n namely variable is getting assigned to temp. It means that throughout the entire operation, original value stored in n namely variable will remain safe.
    c) arm - This variable will hold the individual digit in a number given by user.

Now, let us see the working:

while(temp!=0)

This loop will continue its iteration until value of temp doesn't become equals to 0. Say for example, user gave 153. Here, first 3 will be extracted, then 5 and at last, 1 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.

Armstrong Number


arm =temp%10;
sum+= Math.pow(arm,3);  

Here, we need to understand few things.

First, individual digits from given number is getting extracted using temp%10 and getting stored in arm.
As in case of 153, the first extracted number using temp%10 will be 3.
Then, with the pow method of the Math class, cube of the number will be determined and it will be added to the variable sum.
Similarly, second number using temp%10 will be 5 and its will cube will also determined by pow method of Math class and then, it will be added to sum.
At last, third number using temp%10 will be 1 and its will cube will also determined by pow method of Math class and then, it will be added to sum.

N
ow, sum is containing 27+125+1 = 153

temp/=10;

In previous operation, we have seen that the first extracted number using temp%10 was 3. Immediately, after this operation, temp/=10; will be executed which means 153 is now going to be divided by 10 resulting to 15.3. This operation will permanently delete this 3 from temp variable. so that in next iteration, 3 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from temp variable.


Here is the final outcome:

sum is now containing cube of digits i.e. 1+125+27 = 153
n variable is containing 153

Finally, with the conditional statement using if-else, it is determined if sum is equal to n or not as it can be seen in the program. If sum is equal to n, then it is displaying that the number is a Armstrong number. Otherwise, it is displaying that the number is not an Armstrong number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......



Friday, 19 July 2024

Multiplication Table - Java

Multiplication table in java - ICSE



This java program will guide you on how to create a multiplication table of a number that is given by the user in the form of an input. In this program, I have taken for loop to demonstrate the whole process.

Below is the java code for printing the multiplication table.

import java.util.Scanner;
class Multiplication_table
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int number = sc.nextInt();
        for(int i = 1;i<=10;i++)
        {
            System.out.println(number+" X "+i+" = "+number*i);
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely Multiplication_table have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.

6. To accept and store the number, a variable namely number has been defined of int data type.
7. Used for loop and initialized an int variable namely i by 1 and given the condition as i<=10 that means, loop will keep on executing from 1 to 10.
8. Within for loop block, System.out.println(number+" X "+i+" = "+number*i); is mentioned which means:
    a) First value in number variable will be displayed. This is the number given by user.
    b) Then, X will be displayed. During final output, you will understand its purpose.
    c) Then, present value of i will be displayed. Due to loop, it will keep on executing from 1 to 10.
    d) Finally, product of number and i will get displayed.



Output of the code will be as displayed in the below diagram. As it can be seen that as per demanded by the program to enter a number, we have given 15 which means that multiplication table of 15 needs to be displayed.

Display Screen


Immediately, after pressing enter, the following output will come:

Display


Now, type the program in BlueJ or any other Online Java compiler and run the code and test it with different numbers.

Happy Coding ........

Thursday, 18 July 2024

NIVEN Number - Java

 



A NIVEN or HARSHAD number is a number which is divisible by the sum of its digits.

Example:

18 is a NIVEN number

1+8 = 9

18%9 = = 0

Let's start the code of determining if a number is NIVEN or not.

Below is the code for determining if a number is NIVEN.

import java.util.Scanner;
class SUPERSPY
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        int sum = 0,temp = n;
        while(temp!=0)
        {
            sum+=temp%10;
            temp/=10;
        }
        if(n%sum == 0)
        {
            System.out.println("It is a NIVEN number");
        }
        else
        {
            System.out.println("It is not a NIVEN number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely NIVEN have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type

7. Then, two different variables namely
    a) sum - This variable will store the sum of digits. First, it is initialized with 0.
    b) temp - This variable will hold the number given by user on temporary basis. Actually, entire operation will be done with temp variable. temp = n means the value stored in n namely variable is getting assigned to temp. It means that throughout the entire operation, original value stored in n namely variable will remain safe.

Now, let us see the working:

while(temp!=0)

This loop will continue its iteration until value of temp doesn't become equals to 0. Say for example, user gave 18. Here, first 8 will be extracted and at last, 1 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.


sum+ = temp%10;

Here, we need to understand few things.

First, individual digits from given number is getting extracted using temp%10.
As in case of 18, the first extracted number using temp%10 will be 8.
Then, this number will get added to the variable sum.
At last, second number using temp%10 will be 1 and it will also be added to sum.

Now, sum is containing 8+1 = 9


temp/=10;

In previous operation, we have seen that the first extracted number using temp%10 was 8. Immediately, after this operation, temp/=10; will be executed which means 18 is now going to be divided by 10 resulting to 1.8. This operation will permanently delete this 8 from temp variable. so that in next iteration, 8 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from temp variable.


Here is the final outcome:

sum is now containing sum of digits i.e. 1+8 = 9
n is containing 18

Finally, with the conditional statement using if-else, it is determined if n mod(%) sum is equal to 0 or not as it can be seen in the program. If n mod(%) sum is equal to 0, then it is displaying that the number is a NIVEN number. Otherwise, it is displaying that the number is not a NIVEN number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......



SPY Number ICSE Computer Science

SPY Number - ICSE

 

A number is called SPY if the sum of the digits equals the product of the digits.

Example:

123 is a SPY number

1+2+3 = 6

1*2*3 = 6

Let's start the code of determining if a number is SPY or not.

Below is the code for determining if a number is SUPERSPY.

import java.util.Scanner;
class SPY
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        int sum = 0,temp = n, mul = 1;
        while(temp!=0)
        {
            sum+=temp%10;
            mul*=temp%10;
            temp/=10;
        }
        if(sum == mul)
        {
            System.out.println("It is a SPY number");
        }
        else
        {
            System.out.println("It is not a SPY number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely SPY have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type

7. Then, three different variables namely
    a) sum - This variable will store the sum of digits. First, it is initialized with 0.
    b) temp - This variable will hold the number given by user on temporary basis. Actually, entire operation will be done with temp variable. temp = n means the value stored in n namely variable is getting assigned to temp. It means that throughout the entire operation, original value stored in n namely variable will remain safe.
    c) mul - This variable will store the sum of digits. First, it is initialized with 1.

Now, let us see the working:

while(temp!=0)

This loop will continue its iteration until value of temp doesn't become equals to 0. Say for example, user gave 123. Here, first 3 will be extracted, then 2 and at last, 1 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.


sum+ = temp%10;

Here, we need to understand few things.

First, individual digits from given number is getting extracted using temp%10.
As in case of 123, the first extracted number using temp%10 will be 3.
Then, this number will get added to the variable sum.
Similarly, second number using temp%10 will be 2 and it will also be added to sum.
At last, third number using temp%10 will be 1 and it will also be added to sum.

Now, sum is containing 3+2+1 = 6

Next operation is mul* = temp%10;

Here, again we need to understand few things.

First, individual digits from given number is getting extracted using temp%10.
As in case of 123, the first extracted number using temp%10 will be 3.
Then, this number will get multiply by the variable mul.
Similarly, second number using temp%10 will be 2 and it will also get multiply by the variable mul.
At last, third number using temp%10 will be 1 and it will also get multiply by the variable mul.

Now, mul is containing 3*2*1 = 6


temp/=10;

In previous operations, we have seen that the first extracted number using temp%10 was 3. Immediately, after these operations, temp/=10; will be executed which means 123 is now going to be divided by 10 resulting to 12.3. This operation will permanently delete this 3 from temp variable. so that in next iteration, 3 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from temp variable.


Here is the final outcome:

sum is now containing sum of digits i.e. 1+2+3 = 6
mul is now containing product of digits i..e 1*2*3 = 6

Finally, with the conditional statement using if-else, it is determined if sum is equal to mul or not as it can be seen in the program. If sum is equal to mul, then it is displaying that the number is a SPY number. Otherwise, it is displaying that the number is not a SPY number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......




Wednesday, 17 July 2024

SUPERSPY Number ICSE Computer Science

SUPERSPY


A number is called SUPERSPY if the sum of the digits equals the number of the digits.

Example:

1021 is a SUPERSPY number

1+0+2+1 = 4

Number of digits = 4

Let's start the code of determining if a number is SUPERSPY or not.

Below is the code for determing if a number is SUPERSPY.

import java.util.Scanner;
class SUPERSPY
{
    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = sc.nextInt();
        int sum = 0,temp = n, no = 0;
        while(temp!=0)
        {
            sum+=temp%10;
            temp/=10;
            no++;
        }
        if(sum == no)
        {
            System.out.println("It is a SUPERSPY number");
        }
        else
        {
            System.out.println("It is not a SUPERSPY number");
        }
    }
}

Demonstration:

1. First, Scanner class is imported.
2. A class namely SUPERSPY have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely n has been defined of int data type
7. Then, three different variables namely
    a) sum - This variable will store the sum of digits. First, it is initialized with 0.
    b) temp - This variable will hold the number given by user on temporary basis. Actually, entire operation will be done with temp variable. temp = n means the value stored in n namely variable is getting assigned to temp. It means that throughout the entire operation, original value stored in n namely variable will remain safe.
    c) no - This variable will count the total number of digits in a number given by user.

Now, let us see the working:

while(temp!=0)

This loop will continue its iteration until value of temp doesn't become equals to 0. Say for example, user gave 128. Here, first 8 will be extracted, then 2 and at last, 1 will get extracted as it is in index 0. Refer to the below diagram for clear understanding.
sum+ = temp%10;

Here, we need to understand few things.

First, individual digits from given number is getting extracted using temp%10.
As in case of 128, the first extracted number using temp%10 will be 8.
Then, this number will get added to the variable sum.
Similarly, second number using temp%10 will be 2 and it will also be added to sum.
At last, third number using temp%10 will be 1 and it will also be added to sum.
Now, sum is containing 8+2+1 = 11

temp/=10;

In previous operation, we have seen that the first extracted number using temp%10 was 8. Immediately, after this operation, temp/=10; will be executed which means 128 is now going to be divided by 10 resulting to 12.8. This operation will permanently delete this 8 from temp variable. so that in next iteration, 8 doesn't gets added to the sum variable again. Like this, it will keep on deleting the digits from temp variable.

no++;

In each iteration, value of no will get incremented by 1. In case of 128, the loop will iterate for 3 times and every time, value of no will increment by 1 and therefore, final value of no will become 3.

Here is the final outcome:

sum is now containing sum of digits i.e. 1+2+8 = 11
no variable is now containing count of digits i..e 128 = 3

Finally, with the conditional statement using if-else, it is determined if sum is equal to no or not as it can be seen in the program. If sum is equal to no, then it is displaying that the number is a SUPERSPY number. Otherwise, it is displaying that the number is not a SUPERSPY number.

Now, write this program and test it with various numbers and increase your knowledge.

Happy Coding.......


Sunday, 7 July 2024

Searching in Array

Searching in Array - PR Webmatrix


Linear Search

It is one of the simplest techniques to search a value within an array.
It traverses the array sequentially to locate a given value and that is the reason due to which, it is also known as sequential search.

Now, suppose if we search for 42 in this array, then it will search the array sequentially as shown in the below diagram.

Sequential Search

If we search for 32, it is not present in the array, resulting in an unsuccessful search and unsuccessful search is represented by -1.

Here is a Linear Search Related Question

Define a class to search for a value input by the user from the list of values given below. If it is found, display the message, Number exists. Otherwise display the message, Number doesn't exists using linear search technique.

11,25,36,47,58,69,79,92

Answer:

import java.util.Scanner;
class hello
{
    public static void main(String[]args)
    {
        Scanner kbd = new Scanner(System.in);
        int searchnumber;
        int foundindex = -1;
        int list[]={11,25,36,47,58,69,79,92};
        System.out.println("Enter a number to search");
        searchnumber= kbd.nextInt();
        for(int i = 0;i<list.length;i++)
        {
            if(list[i]==searchnumber)
            {
                foundindex = i;
                break;
            }
        }
        if(foundindex>=0)
        {
            System.out.println("Number exists");
        }
        else
        {
            System.out.println("Number doesn't exists");
        }
    }
}

Guide of how code is working

Line 8: Initialized the foundindex variable with a default value of -1 indicating value is not found

Line 11: Accepting the number to search for and stored it to search number
Line 12: Iterates through the array using the length property
Line 14: Checks if searchnumber matches any of elements in array.
Line 16: Assigns the index value to the foundindex variable.
Line 17: If searched value is defected, loop is terminated with break statement.
Line 20: Checks if foundindex variable was assigned any value in loop.
Line 22: Displays the success message.
Line 26: Else, Displays unsuccessful message.


Binary Search

Binary search is another technique which is used to find an element in array by the array needs to be sorted. It is faster than linear search.

Here is an example of an array namely list having 9 elements in it.

Sorted Array

Lets imagine that number to be searched = 78
Let us call this number to be searched as searchNumber.

Since we need to divide the sorted array into two halves, we will need three variables:
start - Stores start index of array
end - Stores end index of array
mid - Stores middle value of index

Pass 1:

start = 0
end = 8
mid = (start+end)/2 = (0+8)/2 = 4


searchNumber will be compared to the value at the mid position 4 i.e list[mid]. Now, there are three possibilities:

i. searchNumber is equal to value at list[mid]. In this case, loop will break.
ii.searchNumber is less than the value at list[mid]. In this case, number to be searched exists in first half. Hence, we adjust end variable to one less than mid.
    end = mid-1
iii. searchNumber is greater than the value at list[mid]. In this case, number to be searched exists in second half. Hence, we adjust start variable to one more than mid.
    start = mid+1

Here, searchNumber (i.e 78) is greater than list[mid] (i.e 62) as it can be seen in the above diagram, hence we will adjust the start variable as per point number iii.

The updated value will be:

start = mid+1 (i.e. 4+1 = 5)

Pass 2

start = 5
end = 8
mid = (start+end)/2 = 5+8/2 = 6

Binary Search - PR Webmatrix

searchNumber is again compared with the value at list[mid]. Here, searchNumber is less than value of list[mid]. Hence, we will adjust the end variable as per point number ii.

Now, updated value will be:

end = mid-1 (i.e. 6-1 = 5)

Pass 3

start = 5
end = 5
mid = (start+end)/2 = 5+5/2 = 5

Binary Search - PR Webmatrix

searchNumber is again compared with the value at list[mid]. Here, searchNumber is equal to the value at list[mid]. Hence, search successful.


Here is a Binary Search Related Question

Define a class to search for a value input by the user from the list of values given below. It is is found, display the message, Number exists. Otherwise display the message, Number doesn't exists using Binary search technique.

11,25,36,47,58,69,79,92

Answer:

import java.util.Scanner;
class hello
{
    public static void main(String[]args)
    {
        Scanner kbd = new Scanner(System.in);
        int searchnumber;
        int foundindex = -1;
        int start, end, mid;
        int list[]={11,24,36,47,58,69,79,92};
        System.out.println("Enter a number to search");
        searchnumber= kbd.nextInt();
        start = 0;
        end = list.length-1;
        while(start<=end)
        {
            mid = (start+end)/2;
            if(searchnumber==list[mid])
            {
                foundindex = mid;
                break;
            }
            else if(searchnumber<list[mid])
            {
                end = mid-1;
            }
            else
            {
                start = mid+1;
            }
        }
        if(foundindex>=0)
        {
            System.out.println("Number exists");
        }
        else
        {
            System.out.println("Number doesn't exists");
        }
    }
}

Guide of how code is working

Line 8: Initialized the foundindex variable with a default value of -1 indicating value is not found

Line 12: Accepting the number to search for and stored it to search number
Line 13: Initialized start variable with 1st index i.e 0
Line 14: Initialized end variable with last index i.e length of array-1
Line 15: Loops through until start is less than or equal to end.
Line 17: Calculates value of mid variable i.e. mid index.
Line 18: Checks if searchnumber matches with array element at mid index.
Line 20: Updates foundindex variable with index value at mid location.
Line 21: Stops searching further.
Line 23-25: If searchnumber is present in first half, it adjusts the end variable
Line 29: Else, adjust the start variable.