Subham-Maity / problem-solving

Many JAVA and Python Problem Series
3 stars 3 forks source link
algorithms c coding-interviews cpp hacktoberfest hacktoberfest2022 java leetcode matrix problem-solving python solutions

Coding Problem Series For Beginners


Contributors✨

Thanks to these Wonderful People 👨🏻‍💻
Contributions of any kind are welcome! 🚀

Welcome to this book on "Learning JAVA- Python Problem Series For Beginners"

I love Programming. One of the aims I had when I started CodeXam was to make learning programming easy

At CodeXam, we ask ourselves one question every day: "How do we create awesome learning experiences?"

Help us improve this guide - Fork, Pull Requests, Shares and Likes are recommended !

Chapters


Problem List

Operators


String -> Learn About Complete String From Here


1.Board Percentage Calculator :

Exercise

Write a program to calculate the percentage of a given student in a board exam. His marks from 5 subjects must be taken as input from the keyboard. (Marks are out of 100)

Approach:

So here we did like this
Marks Percentage =
(What is the total number you got in the exam / The sum of the all subjects highest number ) X 100

Solution

Java :

import java.util.Scanner;
public class CodeXam { //our class is CodeXam
    public static void main(String[] args) {
        System.out.println("Enter The Maximum Marks Of One Subject (example: Physics 100) ");
        Scanner sc = new Scanner(System.in);
        float max= sc.nextFloat();
        max= max*5 ;
        System.out.println("Enter the number of your Subject 1 (Physics) : ");
        float a = sc.nextFloat();
        System.out.println("Enter the number of your Subject 2 (Math): ");
        float b = sc.nextFloat();
        System.out.println("Enter the number of your Subject 3 (Biology) : ");
        float c = sc.nextFloat();
        System.out.println("Enter the number of your Subject 4 (Chemistry) : ");
        float d = sc.nextFloat();
        System.out.println("Enter the number of your Subject 5 (Optional) : ");
        float e = sc.nextFloat();
        float total = a+b+c+d+e;
        System.out.println("Total marks: " + total);
        System.out.println("Percentage of your 5 Subject is: ");
        float Percentage = (total/max)*100;
        System.out.println("Marks Percentage= "+ Percentage);
    }
}

Python :

maximum_numbers = int(input("Enter The Maximum Marks of One Subject (example: Physics 100) : "))

physics = int(input("Enter the number of your Subject 1 (Physics) : "))

math = int(input("Enter the number of your Subject 2 (Math) : "))

biology = int(input("Enter the number of your Subject 3 (Biology) : "))

chemistry = int(input("Enter the number of your Subject 4 (Chemistry) : "))

optional = int(input("Enter the number of your Subject 5 (Optional) : "))

total_marks = physics + math + biology + chemistry + optional
max_possible_marks = (maximum_numbers*5)

print("Total marks : ", total_marks)
print("Percentage of your 5 Subject is: ", (total_marks/max_possible_marks)*100)

2.Sum of three numbers :

Exercise

Write a program to sum three numbers

Approach:

So here we did like this
Take the input of the first three numbers, then sum them all

Solution

Java :


import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number ");
        int a = sc.nextInt();
        System.out.println("Enter the 2nd number ");
        int b = sc.nextInt();
        System.out.println("Enter the 3rd number ");
        int c = sc.nextInt();
        int sum = a + b + c;
        System.out.println("Sum of the three number is " + a + " + " + b + " + "+ c +  " = " + sum );

    }
}

Python :

first_num = int(input("Enter the 1st number : "))
second_num = int(input("Enter the 2nd number : "))
third_number = int(input("Enter the 3rd number : "))

sum_of_numbers = first_num+second_num+third_number

# Printing using Python String formatting ,also known as String  interpolation
print(f"Sum of three numbers is : {first_num} + {second_num} + {third_number} = {sum_of_numbers}")

3.Calculate CGPA :

Exercise

Write a program to calculate CGPA using marks of three subjects (out of 100)

Approach:

So here we did like this
(What is the total number you got in the exam) / (total number of subject x 10) 

Solution

Java :


import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of your Subject 1 (Physics) : ");
        float a = sc.nextFloat();
        System.out.println("Enter the number of your Subject 2 (Math): ");
        float b = sc.nextFloat();
        System.out.println("Enter the number of your Subject 3 (Biology) : ");
        float c = sc.nextFloat();

        float Total = a+b+c;
        System.out.println("Total marks: " + Total + " out of 300");
        System.out.println("CGPA of your 3 Subject is: ");
        float cGPA = (Total/30);
        System.out.println("Your CGPA is = "+ cGPA);
    }
}

Python :


 sub1 = int(input("Enter the number of your Subject 1 (Physics) : "))
sub2 = int(input("Enter the number of your Subject 2 (Math) : "))
sub3 = int(input("Enter the number of your Subject 3 (Biology) : "))

total = sub1+sub2+sub3
print("Total marks :", total, "out of 300")
print("Your CGPA is", total/30)

4.Asks the user to enter his/her name and greets them with “Hello <name>, have a good day” text.

Exercise

write a program that asks the user to enter his/her name and greets them with “Hello , has a good day” text.

Approach:

So here we did like this
Take the name as an input 
and print Hello first with user input 
and concatenate with have a good day!

Solution

Java :


import java.util.Scanner;
public class CodeXam {
   public static void main(String[] args) {
       System.out.println("What is your name");
       Scanner sc = new Scanner(System.in);

       String name = sc.next();
       System.out.println("Hello " + name + " have a good day!");
   }
}

Python :


 name = input("What's your name ? \n")

print(f"Hello {name}, have a great day !")

5.Convert Kilometers to miles

Exercise

Write a program to convert Kilometers to miles.

Approach:

So here we did like this
Take the km as an input and multiply with 0.621371
 miles = km*0.621371

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        System.out.println("Enter the value in kilometers");
        Scanner sc = new Scanner(System.in);
        double km = sc.nextDouble();
        System.out.println();
        double miles = km*0.621371;

        System.out.println("The value in miles is  "  +  miles  +  "  miles");
    }
}

Python :


 value_in_km = int(input("Enter the value in kilometers: \n"))

km_to_miles = (value_in_km * 0.621371)
print("The value in miles is : \n", km_to_miles)

6. Detects whether a number entered by the user is an integer or not.

Exercise

Write a program to detect whether a string by the user is an integer(number) return true or if not return false.

Approach:

So here we did like this
For java : The hasNext() is a method of Java Scanner class which returns true if this scanner has another token in its input.
So here sc.hasNextInt()method returns true if the next set of characters in the input stream can be read in as an int. 
If they can't be read as an int, or they are too big for an int or if the end of the file has been reached, then it returns false. 
hasNextInt() itself does not consume any characters.

For Python : Python String isnumeric() method is a built-in method used for string handling. 
The isnumeric() method returns “True” if all characters in the string are numeric characters, Otherwise, It returns “False”

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        System.out.println("Enter your number");
        Scanner sc = new Scanner(System.in);
        System.out.println(sc.hasNextInt());
    }
}

Python :

user_input = input("Enter your number ")

print(user_input.isnumeric())

7. Multiplication table, from any number to any number

Exercise

printing multiplication table for any number, from any number to any number (all given in input) (Forward and reverse order multiplication should be implemented in the program)

Approach:

So here we did like this

Forward : Run a incrementing for loop from Start to end and print the value of the given number what you want 
to get a multiplication table (note: Start < End ) 
Reverse : Run a decrementing for loop from Start to end and print the value of the given number what you want 
to get a multiplication table
(note: Start > End ) 

Solution

Java :

import java.util.Scanner;
public class CodeXam
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.print(" Enter the number you want to get a multiplication table of : ");
        int n=s.nextInt();
        System.out.print("From where : ");
        int start=s.nextInt();
        System.out.print("To where : ");
        int end=s.nextInt();

        if (start <= end )
        for(int i=start; i <= end; i++)
        {
            System.out.println(n+" * "+i+" = "+n*i);
        }
        else{
            for(int i=start; i >=  end; i--){
                System.out.println(n+" * "+i+" = "+n*i);
            }

        }
    }
}

Python :


 value = int(input("Enter the number you want to get a multiplication table of : "))
start = int(input("From where : "))
end = int(input("To where : "))

if start <= end:
    for i in range(start, end+1):
        print(f"{value} * {i} = {value * i}")
elif start > end:
    for o in range(start, end-1, -1):
        print(f"{value} * {o} = {value * o}")

8. (Type Casting) Encrypt a grade by adding a number to it. Decrypt it to show the correct grade.

Exercise

Write a program to the first user input his/her exam grade. Now the program asks for a code number to encrypt your grade by adding the number with your grade. Now the program asks you if you want to decrypt your grade press y or if no type n (note: Y/y or N/n case must be ignored and user can type the capital letter or small letter your program should understand)and if yes program will start decrypting your grade and show you your original grade otherwise program will print “ sorry sir/mam, we can't crack your grade “

Approach:

So here we did like this
Java: 1. First take a input as a char (letter like : A B C D ) 
      2. Take a input as an integer value 
      3. Type cast them because if we do any operation between char and int, it returns int (it’s called numaric Promotion Rules 
1.Byte + Short = Int  
2.Short + Int  = Int
3.Long + Float = Float
4.Character + Int = Int (here we use this)
5.Character + Short = Int
6.Long + Double = Double
7.Float + Double = Double)So we must have to cast them into char 
      4.Take a input as a string value (yes for y No for n) 
      6.we check the input letter(y/n) and also ignore case by equalsIgnoreCase 
      7.Type cast again and do this : Your given grade - Your given number 

==========================================================================

Python : To install “Click” package simply go to any terminal and type “pip install click”

1. We used 'Click' module by this command "import click"
2. Take a input as a string for your grade
3. Take a input as an string for your code
4. use 'click' for take yes or no on input

Python click module is used to create command-line (CLI) applications.
It is an easy-to-use alternative to the standard optparse and argparse modules.

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println(" Enter Your Exam Grade ");
        char grade = sc.next().charAt(0);
        System.out.println("Enter Your Code Number We Will Encrypt Your Grade ");
        int a = sc.nextInt();

        // Encrypting the grade
        grade = (char)(grade + a);
        System.out.println("So Now Your Grade is : " + grade);

        // Ask User
        System.out.println("Sir/Mam, Do you want to decrypt your grade? If yes type " + " y/Y " + " If no type " + " n/N ") ;
        String answer = sc.next();

        // Decrypting the grade
        if ( (answer.equalsIgnoreCase("Y") ) ) {
            grade = (char) (grade - a);
            System.out.println("Your actual Grade is " + grade);
        }
        else
        {
            System.out.println("sorry Sir/mam, we can't crack your grade");
        }

    }
}

Python :


 import click

result = input("Please Enter Your Exam Grade: ")
code = input("Please Enter Your Encryption Code: ")

print("\nNow Your Grade is 'F'")

if click.confirm("\nSir/Ma'am, Do You Want to Decrypt Your Grade ? If Yes type 'Y/y' or 'N/n' for No :\n>> ",
                 default=True):
    print("Your Actual Grade is ", result)
else:
    print("Grade Decryption Aborted")

9.Comparison operators to find out whether a given number is greater than the user entered number or not.

Exercise

Use comparison operators to find out whether a given number 28/56 is greater than the user entered number or not.

Approach:

So here we did like this

Take a number from the user and compare them using < / > and store it in the boolean data type because 
if you compare two operators it returns true or false

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {

        Scanner ab = new Scanner(System.in);
        int a1 = 28;
        System.out.println("Given number is " + a1);

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

        int a = ab.nextInt();
        System.out.println(a);
        boolean bool = (a1 >= a);
        if (bool){
            System.out.println("given number 28 is greater than your entered number ");
        }
        else {
            System.out.println("given number 28 is less than your entered number ");
        }
    }
}

Python :

given_number = 56
print("The given number is", given_number)

user_input = int(input("Enter your number : \n"))

if user_input < given_number:
    print("Given number is greater than the entered number")
elif user_input == given_number:
    print("Both are same number")
else:
    print("Given number", given_number, "is less than the entered number")

10. Write the following expression in a Java / Python / in your program

Exercise

Write the following expression in a Java / Python / in your program (v^2-u^2)/2as

Approach:

So here we did like this
Just do this
(v*v) - (u*u))/ (2*a*s)

Solution

Java :


import java.util.Scanner;

public class CodeXam {
    public static void main(String[] args) {
        double v,u,a,s;

        Scanner sc = new Scanner(System.in);
        System.out.println("Equation is (v^2 -u^2)/(2as)");
        System.out.println("Enter your value of v");
        v = sc.nextInt();
        System.out.println("Enter your value of u");
        u = sc.nextInt();
        System.out.println("Enter your value of a");
        a = sc.nextInt();
        System.out.println("Enter your value of s");
        s = sc.nextInt();

        double d = ((v*v) - (u*u))/ (2*a*s) ;
        System.out.println("your result is "+d);

    }}

Python :


 print("\nEquation is (v^2 -u^2)/(2as)")

v = int(input("\nEnter the value of v: "))
u = int(input("Enter the value of u: "))
a = int(input("Enter the value of a: "))
s = int(input("Enter the value of s: "))

result = ((v*v) - (u*u))/ (2*a*s)
print("Your result is :", result)

11.(Java)What will be the result of the following expression

Exercise

Why does this happen?

Approach:

So here we did like this for result we need to define the floating point
7/4 it always return an integer so 7/4 = 1 
                                Then 9/2 = 4
                                Then 1*4 = 4 (this is the reason why then 
 Our program return 4 instead of 7.875) 

12. Convert a string to lowercase.

Exercise

Write a program to convert a string to lowercase. This string is given by the user.

Approach:

So here we did like this
Java : in java The toLowerCase() method converts a string to lower case letters
Python : in Python, the “ .lower” method is used to convert a string in lower case !

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter any sentence or word: ");
        String string = sc.nextLine();
        string = string.toLowerCase();
        System.out.println("In lower case this word or sentence looks like this : " + "\n" + string);
    }
}

Python :

given_str = input("Enter any sentence or word : ")

print("In lower case this word or sentence looks like this :", given_str.lower())

13. Replace spaces with underscores.

Exercise

Write a program to replace spaces with underscores. This string is given by the user.

Approach:


So here we did like this
Java : The replace() method searches a string for a specified character, and
returns a new string where the specified character(s) are replaced.
Python : It's the same as Java, just use the .replace method.

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter any sentence with space: ");
        String string = sc.nextLine();
        string = string.replace(" ", "_");
        System.out.println("This sentence with underscores looks like this : " + "\n" + string);}}

Python :

txt = input("Enter your sentence with space : \n")

x = txt.replace(" ", "_")

print("This sentence with underscores looks like this:\n",x)

14. Fill in a letter template which looks like below:

Exercise

Write a program to fill in a letter template which looks like below:

Sentence =      “Dear <|name|>, Thanks a lot” 

Replace =      <|name|> with a string (some name)

Approach:

So here we did like this
Java : We use replace method but if we just do like this 
        String sentences = sc.nextLine();
        String sentence = "Dear <|name|>, Thanks a lot!";
        sentence.replace("<|name|>", sentences);
        System.out.println(sentence);
 It will execute this : Enter your name: Subham
                        Dear <|name|>, Thanks a lot!
If we want to change a string we need convert a string by storing it in 
another string variable

Python : We will use the .replace() method again and unlike java , we don’t need to store the string in another variable !

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String sentences = sc.nextLine();
        String sentence = "Dear <|name|>, Thanks a lot!";
        sentence =  sentence.replace("<|name|>", sentences);
        System.out.println(sentence);
    }
}

Python :

name = input("Enter your name: ")

output = "Dear <|Name|>, Thanks a Lot !"

print(output.replace('<|Name|>', name))

15. Detects double and triple spaces in a string.

Exercise

Write a program to detect the index of double and triple spaces in a string given by the user.

Approach:

So here we did like this
Java: The indexOf() method returns the position of the first occurrence 
of specified character(s) in a string

Python : The .index() method return the position of first occurrence 
of specified character(s) in a string

Solution

Java :

import java.util.*;
public class code_xam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your Sentence ");
        String str1 = sc.nextLine();
        System.out.println(str1.indexOf("  "));
        System.out.println(str1.indexOf("   "));
    }
}

Python :

txt = input("Enter Your sentence with 2 and 3 spaces:\n")
print(txt.index("  "))
print(txt.index("   "))

16. Check if a String contains only whitespaces

Exercise

Check if a String given by the user contains only whitespaces or not if the string has only whitespace print “ It is only whitespace” if not print “It’s a sentence ”

Approach:

So here we did like this
Java:

The Java String class trim() method eliminates leading and trailing spaces
he Java String class isEmpty() method checks if the input string is empty or not

Get the String to be checked in str1
We can use the trim() method of String class to remove the leading whitespaces in the string.
Syntax:
str1.trim()
Then we can use the isEmpty() method of String class to check if the resultant string is empty or not. If the string contained only whitespaces, then this method will return true
Syntax:
str.isEmpty()
Combine the use of both methods using Method Chaining.
str.trim().isEmpty()
Print true if the above condition is true. Else print false.

Python : We’re simply using if, else conditions here ! 

Solution

Java :

import java.util.*;
class CodeXam {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your Sentence");
        String str1 = sc.nextLine();
        {
            if (str1.trim().isEmpty())
                System.out.println("It is only whitespace");
            else
                System.out.println("It's a sentence");
        }}}

Python :

input_str = input("Please enter your sentence : \n")

if  input_str:
    print("It's a sentence")
else:
    print("It's only Whitespace")

17.(Escape sequence) format the following sentence using escape sequence characters only

Exercise

format the following sentence using escape sequence characters only

Approach:

So here we did like this
Java :
Escape Sequence :

\t  Inserts a tab in the text at this point.
\b  Inserts a backspace in the text at this point.
\n  Inserts a newline in the text at this point.
\r  Inserts a carriage return in the text at this point.
\f  Inserts a form feed in the text at this point.
\'  Inserts a single quote character in the text at this point.
\"  Inserts a double quote character in the text at this point.
\\  Inserts a backslash character in the text at this point.

Python :

\'  Single Quote
\”    Double Quote  
\\  Backslash   
\n  New Line    
\r  Carriage Return 
\t  Tab 
\b  Backspace   
\f  Form Feed   
\ooo    Octal value 
\xhh    Hex value

Solution

Java :


class CodeXam {
    public static void main(String[] args) {
        String myLetter = "Dear Xam,\n\tThis question answer sheet is very helpful for me .\n Thanks!";
        System.out.println(myLetter);
    }
     }

Python :

output = "Dear Suvo,\n\tThis question answer sheet is very helpful for me.\n Thanks!"

print(output)

18.Make a Calculator.

Exercise

Make a Calculator. Take 2 integer numbers (a & b) from the user and an operation as follows

Press 1 : + (Addition) a + b 
Press 2 : - (Subtraction) a - b 
Press 3 : * (Multiplication) a * b 
Press 4 : / (Division) a / b 
Press 5 : % (Modulo or remainder) a % b 
Calculate the result according to the operation given and display it to the user

Approach:

So here we did like this
Java : using case switch and take the integer input from the user and operation to them as 
the instructions are given in the question 

Python : We take all int value as input and simply use if elif method

Solution

Java :

import java.util.*;

public class CodeXam {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Your First Number");
        int a = sc.nextInt();
        System.out.println("Enter Your Second Number");
        int b = sc.nextInt();
        System.out.println("Press 1 : + (Addition):  " +  a + " + " + b + "\nPress 2 :  - (Subtraction):  " +  a + " - " + b + "\nPress 3 :  * (Multiplication):  " +  a + " * " + b +"\nPress 4 :   / (Division):  " +  a + " / " + b +"\nPress 5 :  % (Modulo or remainder):  " +  a + " % " + b );

        int operator = sc.nextInt();

          /**
         * 1 -> +
         * 2 -> -
         * 3 -> *
         * 4 -> /
         * 5 -> %
           */

        switch(operator) {
            case 1 : System.out.println(a+b);
                break;
            case 2 : System.out.println(a-b);
                break;
            case 3 : System.out.println(a*b);
                break;
            case 4 : if(b == 0) {
                System.out.println("Invalid Division");
            } else {
                System.out.println(a/b);
            }
                break;
            case 5 : if(b == 0) {
                System.out.println("Invalid Division");
            } else {
                System.out.println(a%b);
            }
                break;
            default : System.out.println("Invalid Operator");
        }
    }
}

Python :

a = int(input("Enter your 1st number: "))
b = int(input("Enter your 2nd number: "))

print(f"""
Press 1 : + (Addition): {a} + {b}
Press 2 :  - (Subtraction): {a} - {b}
Press 3 :  * (Multiplication): {a} * {b}
Press 4 :   / (Division): {a} / {b}
Press 5 :  % (Modulo or remainder): {a} % {b}""")

user_input = int(input())

if user_input == 1:
    print(a+b)
elif user_input == 2:
    print(a-b)
elif user_input == 3:
    print(a*b)
elif user_input == 4:
    print(a / b)
elif user_input == 5:
    print(a % b)
else:
    print("Invalid Input :(") 

19.Print the name of the month.

Exercise

Ask the user to enter the number of the month & print the name of the month. For eg - For ‘1’ print ‘January’, ‘2’ print ‘February’ & so on

Approach:

So here we did like this
Java : using case switch and take the integer input from the user and print according to the number
Python:Same as Java, we’re using Case switch method here, “match-case”.Python 3.10 (2021) introduced the
match-case statement which provides a first-class implementation of a "switch" for Python.

Solution

Java :

import java.util.*;

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

        System.out.println("Enter the number of the month \n(Press : 1 -12 only) " );

        int operator = sc.nextInt();
        String sentence = "The name of the month according to your number is: ";

        switch(operator) {
            case 1 : System.out.println(sentence + "January");
                break;
            case 2 : System.out.println(sentence + "February");
                break;
            case 3 : System.out.println(sentence + "March");
                break;
            case 4 : System.out.println(sentence + "April");
                break;
            case 5 : System.out.println(sentence + "May");
                break;
            case 6 : System.out.println(sentence + "June");
                break;
            case 7 : System.out.println(sentence + "July");
                break;
            case 8 : System.out.println(sentence + "August");
                break;
            case 9 : System.out.println(sentence + "September");
                break;
            case 10 : System.out.println(sentence + "October");
                break;
            case 11 : System.out.println(sentence + "November");
                break;
            case 12 : System.out.println(sentence + "December ");
                break;
            default : System.out.println("Invalid Number");
        }
    }
}

Python :

x = int(input("Please enter the no. of your month: \n"))

sentence = "The name of the month according to your number is:"
match x:
    case 1:
        print(f"{sentence} January")
    case 2:
        print(f"{sentence} February")
    case 3:
        print(f"{sentence} March")
    case 4:
        print(f"{sentence} April")
    case 5:
        print(f"{sentence} May")
    case 6:
        print(f"{sentence} June")
    case 7:
        print(f"{sentence} July")
    case 8:
        print(f"{sentence} August")
    case 9:
        print(f"{sentence} September")
    case 10:
        print(f"{sentence} October")
    case 11:
        print(f"{sentence} November")
    case 12:
        print(f"{sentence} December")  

20.Prime or not (input from the user)

Exercise

Print if a number is prime or not (Input n from the user). (without creating a method or recursion using if else and for loop or do while loop only)

Approach:

 Note : To find if a number is prime, why is checking till n/2 ?

Well, whenever you find a number which is Prime or not , you check it till n/2. That is true, and there is no problem checking it till n. But we don’t check it because there is no possibility of getting a number x which is divisible by n and which lies on the second half of the number (n/2).

Let’s check what I am talking about.

Consider the number 17. Check whether it is prime or not.

17%2≠0 (%=Modulus or Remainder)

17%3≠0

17%4≠0

17%5≠0

17%6≠0

17%7≠0

17%8≠0

17%9≠0 (Consider this which lies on the second half in the n/2).

You won’t find any more numbers which can produce the result.

The minimum number that can be divided by 17 is 2, and if you divide 17/9 which can’t give you the number which is less than 2. (We don’t consider 1 as minimum since 1 is divisible with every other number).

So, it is a waste of time to check further for any other number, or it is an inefficient algorithm in terms of computer programming.

Python : 
1st approach = Just same as Java approach mentioned above

2nd Approach = In python we can simply use pip(package manager)  to install a python package which is called “sympy” , just go to your terminal(for windows CMD or Powershell or Windows Terminal for Win 11, system terminal for MaxOS and any Linux Based OS) and type “pip install sympy”, it will automatically download and install sympy. After that, type “from sympy import *” on your IDE (see the 1st line of the python solution mentioned below). Then we can use the isprime() method which we imported from sympy !

P.S. To uninstall any kinda pip package just type “pip uninstall package_name”

Solution

Java :


import java.util.Scanner;
class CodeXam {
    public static void main(String[] args) {
        boolean isPrime = false;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number to check prime or not:");
        int n = sc.nextInt();

        if (n == 1 || n ==0) {
            System.out.println(n + " is not prime number");
        } else {
            for (int i = 2; i <= n / 2; ++i) {
                // condition for non-prime number
                if (n % i == 0) {
                    isPrime = true;
                    break;

                }
            }
            if (!isPrime)
                System.out.println(n + " is a prime number.");
            else
                System.out.println(n + " is not a prime number.");
        }
    }
}

Python :


num = int(input("Enter Your Number :\n"))
if num > 1:

    for i in range(2, int(num / 2) + 1):
        if (num % i) == 0:
            print(num, "is not a prime number")
            break
    else:
        print(num, "is a prime number")

else:
    print(num, "is not a prime number")

#2nd approach
from sympy import *

x = int(input("Enter a number to check whether it's a Prime number or not:\n"))

if isprime(x):
    print(x, "is a prime number indeed")
else:
    print(x, "is not a prime number ")

21.Pass or fail

Exercise

Write a program to find out whether a student is pass or fail; if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as input from the user

Approach:

So here we did like this

        avg = (subject1 + subject2 + subject3)/3.0
        If Conditions: avg>=40 && subject1>=33 && subject2>=33 && subject3>=33
           print"Congratulations, You have been promoted"
        Else print"Sorry, You have not been promoted! Please try again."

Solution

Java :

import java.util.Scanner;
class CodeXam
{
    public static void main(String [] args)
    {
        byte m1, m2, m3;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your marks in Physics");
        m1 = sc.nextByte();

        System.out.println("Enter your marks in Chemistry");
        m2= sc.nextByte();

        System.out.println("Enter your marks in Mathematics");
        m3 = sc.nextByte();
        float avg = (m1+m2+m3)/3.0f; //you can do this also Marks Percentage = (What is the total number you got in the exam / The sum of the all subjects highest number ) X 100

        System.out.println("Your Overall percentage is: " + avg);
        if(avg>=40 && m1>=33 && m2>=33 && m3>=33){
            System.out.println("Congratulations, You have been promoted");
        }
        else{
            System.out.println("Sorry, You have not been promoted! Please try again.");
        }
    }
}

Python :

physics = int(input("Enter your score in Physics:\n"))
chemistry = int(input("Enter your score in Chemistry:\n"))
mathematics = int(input("Enter your score in Mathematics:"))

result = (physics+chemistry+mathematics) / 3
print("\nYour overall percentage is", result)
if result >= 40 and physics >= 33 and chemistry >= 33 and mathematics >= 33:
    print("Congratulations ! You've been promoted ")
else:
    print("Ah , You've failed this year ! See you never :)")

22.Calculate income tax

Exercise

Calculate income tax paid by you to the government as per the slabs mentioned below:

Income Slab         Tax
2.5L – 5.0L             5% 
5.0L – 10.0L            20%
Above 10.0L             30%
Note that there is no tax below 2.5L. Take the input amount as input from the user.

Approach:

Python : Simple use of if, elif, else methods

Solution

Java :

import java.util.Scanner;
class CodeXam
{
    public static void main(String [] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Income Slab                 Tax\n" +
                "2.5L –  5.0L                5% \n" +
                "5.0L – 10.0L                20%\n" +
                "Above  10.0L                30%\n" +
                ": Note that there is no tax below 2.5L :\n");
        System.out.println("Enter your annual income ");
        double tax = 0f;
        double income = sc.nextDouble();
        if(income<=250000f){
            tax = tax + 0;
        }
        else if(income>250000f && income <= 500000f){
            tax = tax + 0.05f * (income - 250000f);
        }
        else if(income>500000f && income <= 1000000f){
            tax = tax + 0.05f * (500000f - 250000f);
            tax = tax + 0.2f * (income - 500000f);
        }
        else if(income>1000000f){
            tax = tax + 0.05f * (500000f - 250000f);
            tax = tax + 0.2f * (1000000f - 500000f);
            tax = tax + 0.3f * (income - 1000000f);
        }

        System.out.println("The total tax paid by you is: " + tax);

  }
}

Python :

print("""         Income Slab                Tax
         ============                ====
         2.5L –  5.0L                5%
         5.0L – 10.0L                20%
         Above  10.0L                30%
* Note that there is no tax for income below or equal to 2.5L *""")

income = int(input("\nEnter your annual income:\n"))

tax1 = (5/100)
tax2 = (20/100)
tax3 = (30/100)
sentence = "Your annual tax is"

if income <= 250000:
    print("You have no annual Tax charge !")
elif 250000 < income <= 500000:
    tax = ((income-250000)*tax1)
elif 500000 < income <= 1000000:
    tax = ((500000-250000) * tax1 + (income - 500000)*tax2)
else:
    tax = ((500000-250000) * tax1 + (1000000 - 500000)*tax2 + (income - 1000000)*tax3)

print(sentence, tax)

23.Leap year or not.

Exercise

Write a program to find whether a year entered by the user is a leap year or not.

Approach:

So here we did like this
Check if the year is divisible by 400 or 4 but not 100, DISPLAY "is a leap year",
Otherwise, DISPLAY ": is not a leap year.""

Solution

Java :

import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int year = sc.nextInt();
        if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
            System.out.println(year + " : is a leap year");
        }
        else {System.out.println(year + " : is not a leap year.");
        }
    }
}

Python :

year = int(input("Enter your Year:\n"))

leap_year = "It's a leap year !"
common_year = "It's not a leap year"
if year % 4 == 0:
    if year % 100 != 0:
        print(leap_year)
    elif year % 400 == 0:
        print(leap_year)
    else:
        print(common_year)
else:
    print(common_year)

24.Type of website

Exercise

Approach:

So here we did like this
Java : The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false.
Python : Same like Java, we’re using endswith() method in python as well

Solution

Java :


import java.util.Scanner;
public class CodeXam {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Your Website: ");
        String website = sc.next();
        if(website.endsWith(".org")){
            System.out.println("This is an Organizational website");
        }
        else if(website.endsWith(".com")){
            System.out.println("This is a Commercial website");
        }
        else if(website.endsWith(".in")){
            System.out.println("This is an Indian website");
        }
        }
    }

Python :

user_input = input("Please Enter Your URL:\n")

if user_input.endswith(".com"):
    print("It's an Commercial Website")
elif user_input.endswith(".org"):
    print("It's an Organization Website")
elif user_input.endswith(".in"):
    print("It's an Indian Website")
else:
    print("Not Found !")

25.Email by deleting the part

Exercise

Input an email from the user. You have to create a username from the email by deleting the part that comes after ‘@’. Display that username to the user. Example :

email = “codexam@gmail.com” ; username = “codexam”

email = “helloWorld123@gmail.com”; username = “helloWorld123”

Approach:

Python: In python we're simply using slicing, 
we're printing from index 0 to (index of '@') -1

Solution

Java :

import java.util.*;

public class CodeXam {
    public static void main(String args[]) {
        System.out.println("Enter Your Gmail");
        Scanner sc = new Scanner (System.in);
        String email = sc.next();
        String userName = "";

        /* //You can use this too

        for(int i=0; i<email.length(); i++) {
            if(email.charAt(i) == '@') {
                break;
            } else {
                userName += email.charAt(i);
            }
        }
        */

        for(int i=0; i<email.length(); i++) {
            if(email.charAt(i) == '@')
                break;
               userName = userName+email.charAt(i);
        }

        System.out.println("Your username is: " + userName);
    }
}

Python :

user = input("Please enter your email id:\n")

x = user.index("@")

user_name = user[0:x]
print("Your username is:", user_name)

26. Pattern

1.(Solid Rectangle)

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

So here we did like this
Row range:0-4 
Column range:0-5

Solution

Java :


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

Python :

for i in range(1, 5):
    for j in range(1, 6):
        print("*", end=" ")
    print()

2.(Hollow Rectangle)

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

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

        for(int i=1; i<=4; i++) {
            for(int j=1; j<=5; j++) {
                if(i == 1 || i == 4 || j == 1 || j == 5) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Python :

for i in range(1, 5):
    for j in range(1, 6):
        if (i == 1 or i == 4 or
                j == 1 or j == 5):
            print("*", end=" ")
        else:
            print(" ", end=" ")

    print()

3.(Half Pyramid)

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

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

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

            System.out.println();
        }
    }
}

Python :

for i in range(0, 5):
    for j in range(0, i + 1):
        print("*", end=" ")

    print(" ")

4.(Inverted half Pyramid )

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

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

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

            System.out.println();
        }
    }
}

Python :

for i in range(4, 0, -1):
    for j in range(i + 1, 1, -1):
        print("* ", end="")

    print(" ")

5.(Inverted & Rotated Half Pyramid )

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

//Approach -1
public class code_xam {
    public static void main(String[] args) {
        int n = 4;

        //For "Row"
        for (int i = 1; i <= n; i++) {

            //For "Space"
            for (int j = 1; j <= n - i; j++) {
                System.out.print(" ");}

            //For "Star"
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

//Approach -2
public class code_xam {
    public static void main(String[] args) {
        int n = 4;
        //For "Row"
        //similar to Approach -1... 1-4 or 4-1 is same because we have 4 row so if we go backwards, it works fine

        for (int i = n; i>=1; i--) {
            //For "Space"

            /*it's also similar to Approach -1...because when i = 4(n) ;
            the range of the j will be 1-4 that is total 3 space so for the first row second loop will print 3 space like Approach -1
             */
            for (int j = 1; j<i ; j++) {
                System.out.print(" ");}

            //For "Star"

            /*it's also similar to Approach -1...because when i = 3 ;
            and the range of the j will be 0 to (n-i) = (4-3) that is total 1 star(*) so for the first row third loop will print 1 star like Approach -1
            same as
            i = 2; range of the j 0 to (4-2) so **
            i = 1; range of the j 0 to (4-1) so ***
            i = 0; range of the j 0 to (4-0) so ****           */
            for (int j = 0; j <= n-i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Python :

for i in range(1, 5):
    for j in range(5, 0, -1):
        if j > i:
            print(" ", end=" ")
        else:
            print("*", end=" ")

    print("")

6.Half Pyramid with Numbers

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class code_xam {
    public static void main(String[] args) {
        int n = 5;

        //For "Row"
        for (int i = 1; i <= n; i++) {

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

            }
            System.out.println();
        }
    }

Python :

for i in range(0, 5):
    num = 1
    for j in range(0, i+1):
        print(num, end=" ")
        num += 1

    print(" ")

7.Inverted half Pyramid with Numbers

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class code_xam {
    public static void main(String[] args) {
        int n = 5;

        //For "Row"
        for (int i = n; i >= 1; i--) {

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

            }
            System.out.println();
        }
    }

Python :

for i in range(5, 0, -1):
    num = 1
    for j in range(i + 1, 1, -1):
        print(num, end=" ")
        num += 1

    print(" ")

8.Floyd’s triangle

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class code_xam {
    public static void main(String args[]) {
        int n = 5;
        int number = 1;

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

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

Python :

for i in range(1, 6):
    for j in range(1, i+1):
        print(num, end="  ")
        num += 1
    print("  ")

9.(0-1) Triangle

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class code_xam {
    public static void main(String args[]) {
        int n = 5;
        int sum;

        for(int i=1; i<=n; i++) {
            for(int j=1; j<=i; j++) {
                sum = i+j;
                if((sum) % 2 == 0) {
                    System.out.print(1+" ");
                } else {
                    System.out.print(0+" ");
                }
            }
            System.out.println();
        }
    }
}

Python :

for i in range(1, 6):
    for j in range(1, i+1):
        sums = i + j
        if sums % 2 == 0:
            print(1, end=" ")
        else:
            print(0, end=" ")
    print(" ")

10.ButterFly

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
    public static void main(String args[]) {
        int n = 4;

        //upper part
        for(int i=1; i<=n; i++) {
            for(int j=1; j<=i; j++) {
                System.out.print("*");
            }

            int spaces = 2 * (n-i);
            for(int j=1; j<=spaces; j++) {
                System.out.print(" ");
            }

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

        //lower part
        for(int i=n; i>=1; i--) {
            for(int j=1; j<=i; j++) {
                System.out.print("*");
            }

            int spaces = 2 * (n-i);
            for(int j=1; j<=spaces; j++) {
                System.out.print(" ");
            }

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

//Using Absolute Function : (Math.abs here math is a class and abs is a method of the math class)
public class CodeXam
{
    public static void main(String[] args)
    {
        for(int i=-3;i<=3;i++)
        {
            for(int j=1;j<=4-Math.abs(i);j++)
            {
                System.out.print("*");
            }
            for(int j=1;j<=2*Math.abs(i);j++)
            {
                System.out.print(" ");
            }
            for(int j=1;j<=4-Math.abs(i);j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Python :


# Q1 

n = 4
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print("*", end=" ")
    for space in range(1, (2 * (n - i)) + 1):
        print(end="  ")

    for j in range(i, 0, -1):
        print("*", end=" ")
    print()

for i in range(n, 0, -1):

    for j in range(1, i + 1):
        print("*", end=" ")
    for space in range(1, (2 * (n - i)) + 1):
        print(end="  ")

    for j in range(i, 0, -1):
        print("*", end=" ")
    print()

# Q2

n = 3
for i in range(-n, n+1):
    for j in range(1, (n+1)-abs(i)+1):
        print("*", end=" ")
    for j in range(1, 2*abs(i)+1):
        print(" ", end=" ")
    for u in range(1, (n+1)-abs(i)+1):
        print("*", end=" ")
    print(" ")

11.Solid Rhombus

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

//Approach - 1
public class CodeXam {
   public static void main(String args[]) {
       int n = 5;

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

           //stars
           for(int j=1; j<=n; j++) {
               System.out.print("*");
           }
           System.out.println();
       }
   }   
}

//Approach - 2
public class CodeXam {
    public static void main(String args[]) {
        int n = 5;

        for(int i=n; i>=1; i--) {
            //spaces
            for(int j=1; j<=i; j++) {
                System.out.print(" ");
            }

            //stars
            for(int j=1; j<=n; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Python :

# Approach 1

n = 5
for i in range(n+1, 1, -1):
    for j in range(1, i):
        print(" ", end=" ")
    for j in range(1, n+1):
        print("*", end=" ")
    print(" ")

#Approach 2
n = 5
for i in range(1, n + 1):
   for j in range(1, (n-i)+1):
       print(" ", end=" ")
   for j in range(1, n+1):
       print("*", end=" ")
   print(" ")

12.Number Pyramid

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

class code_xam {
    public static void main(String args[]) {
        int n = 5;

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

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

Python :

n = 5
for i in range(1, n + 1):
  for j in range(1, (n-i)+1):
      print(" ", end=" ")
  for j in range(1, i+1):
      print(i," " ,end=" ")
  print(" ")

13.Palindromic Pattern

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
    public static void main(String[] args) {
        int n = 5;
        for(int i=1; i<=n; i++) {
            //spaces
            for(int j=1; j<=n-i; j++) {
                System.out.print(" ");
            }

            //first part
            for(int j=i; j>=1; j--) {
                System.out.print(j);
            }

            //second part
            for(int j=2; j<=i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}

Python :

n = 5

for i in range(1, n+1):
    for j in range(n, 0, -1):
        if j > i:
            print(" ", end=" ")

    for j in range(i, 0, -1):
        print(j, end=" ")

    for j in range(2, i + 1):
        print(j, end=" ")

    print()

14.Diamond Pattern

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Approach:

Solution

Java :

// Approach 1
public class CodeXam {
    public static void main(String args[]) {
        int n = 4;

        //upper part
        for(int i=1; i<=n; i++) {
            //spaces
            for(int j=1; j<=n-i; j++) {
                System.out.print(" ");
            }
            for(int j=1; j<=2*i-1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        //lower part
        for(int i=n; i>=1; i--) {
            //spaces
            for(int j=1; j<=n-i; j++) {
                System.out.print(" ");
            }
            for(int j=1; j<=2*i-1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
// Approach 2
public class CodeXam {
   public static void main(String args[]) {
       int n = 4;

       //upper part
       for(int i=1; i<=n; i++) {
           //spaces
           for(int j=n; j>0; j--) {
               if (j >i)
               {
                   System.out.print(" ");}
           }
           for(int j=1; j<=2*i-1; j++) {
               System.out.print("*");
           }
           System.out.println();
       }

       //lower part
       for(int i=n; i>=1; i--) {
           //spaces
           for(int j=n; j>0; j--) {
               if (j >i)
               {
                   System.out.print(" ");}
           }
           for(int j=1; j<=2*i-1; j++) {
               System.out.print("*");
           }
           System.out.println();
       }
   }
}

// Approach 3

public class CodeXam {
    public static void main(String args[]) {
        int n = 4;

        //upper part
        for(int i=1; i<=n; i++) {
            //spaces
            for(int j=1; j<=2*n-i; j++) {
                System.out.print(" ");
            }
            for(int j=i; j>0; j--) {
                System.out.print("*");
            }
            for(int j=2; j<i+1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        //lower part
        for(int i=n; i>=1; i--) {
            //spaces
            for(int j=1; j<=2*n-i; j++) {
                System.out.print(" ");
            }
            for(int j=i; j>0; j--) {
                System.out.print("*");
            }
            for(int j=2; j<i+1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Python :

#Approach 1
n = 4

for i in range(1, n+1):
    for j in range(n, 0, -1):
        if j > i:
            print(" ", end=" ")

    for j in range(i, 0, -1):
        print("*", end=" ")

    for j in range(2, i + 1):
        print("*", end=" ")

    print()

for i in range(n, 0, -1):
    for j in range(n, 0, -1):
        if j > i:
            print(" ", end=" ")

    for j in range(i, 0, -1):
        print("*", end=" ")

    for j in range(2, i + 1):
        print("*", end=" ")

    print()

#Approach 2
n = 4

for i in range(1, n+1):
   for j in range(1, 2*n-i):

         print(" ", end=" ")

   for j in range(i, 0, -1):
       print("*", end=" ")

   for j in range(2, i + 1):
       print("*", end=" ")

   print()

for i in range(n, 0, -1):
   for j in range(1, 2 * n - i):
       print(" ", end=" ")

   for j in range(i, 0, -1):
       print("*", end=" ")

   for j in range(2, i + 1):
       print("*", end=" ")

   print()

# Approach 3
n = 4

for i in range(1, n + 1):
   for j in range(1, 2 * n - i):
       print(" ", end=" ")
   for j in range(1, 2 * i-1 + 1):
       print("*", end=" ")
   print()

for i in range(n, 0, -1):
   for j in range(1, 2 * n - i):
       print(" ", end=" ")
   for j in range(1, 2 * i-1 + 1):
       print("*", end=" ")
   print()

15.Hollow butterfly

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
   public static void main(String args[]) {
      int n =5;

       for (int i = 1; i <= n; i++) { // 1st outer loop

           for (int j = 1; j <= i; j++) { // Star Printing - 2nd inner loop
               if(j==1 || j==i )
                   System.out.print("*");
               else
                   System.out.print(" ");
           }

           int spaces = 2 * (n-i);
           for(int j=1; j<=spaces; j++) {
               System.out.print(" ");
           }

           for (int j = 1; j <= i; j++) { // Star Printing - 2nd inner loop
               if(j==1 || j==i )
                   System.out.print("*");
               else
                   System.out.print(" ");
           }
           System.out.println();
       }

       for (int i = n; i >= 1; i--) { // 2nd outer for loop

           for (int j = 1; j <= i; j++) { // Stars printing - 2nd inner for
               // loop
               if (j == 1 || j == i)
                   System.out.print("*");

               else
                System.out.print(" ");

           }
           int spaces = 2 * (n-i);
           for(int j=1; j<=spaces; j++) {
               System.out.print(" ");
           }

           for (int j = 1; j <= i; j++) { // Star Printing - 2nd inner loop
               if(j==1 || j==i)
                   System.out.print("*");
               else
                   System.out.print(" ");
           }

           System.out.println();
       }
   }

}

Python :

n = 5
for i in range(1, n + 1):
   space = 2 * n - 2 * i
   for j in range(1, i + 1):
       if j == 1 or j == i:
           print("*", end='')
       else:
           print(" ", end='')
   for j in range(space):
       print(" ", end='')
   for j in range(1, i + 1):
       if j == 1 or j == i:
           print("*", end='')
       else:
           print(" ", end='')
   print()

for i in range(n, 0, -1):
   space = 2 * n - 2 * i
   for j in range(1, i + 1):
       if j == 1 or j == i:
           print("*", end='')
       else:
           print(" ", end='')
   for j in range(space):
       print(" ", end='')
   for j in range(1, i + 1):
       if j == 1 or j == i:
           print("*", end='')
       else:
           print(" ", end='')
   print()

16.Hollow Rhombus

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
   public static void main(String args[]) {
       int n = 5;

       for (int i = 1 ; i <= n; i++ )
       {
           for (int j = 1 ; j <= n - i; j++ )
           {
               System.out.print(" ");
           }
           for (int j = 1 ; j <= n; j++ )
           {
               if (i == 1 || i == n || j == 1 || j == n) {
                   System.out.print("* ");
               }
               else {
                   System.out.print("  ");
               }
           }
           System.out.println();
       }
   }
}

Python :

rows = 5
for i in range(1, rows + 1):
    for j in range(1, rows - i + 1):
        print(end=" ")

    if i == 1 or i == rows:
        for j in range(1, rows + 1):
            print("*", end=" ")

    else:
        for j in range(1, rows + 1):
            if j == 1 or j == rows:
                print("*", end=" ")
            else:
                print(" ", end=" ")
    print()

#approach
n = 5
for i in range(1, n + 1):
   for j in range(1, n - i + 1):
       print(" ", end="")
   for j in range(1, n + 1):
       if i == 1 or i == n or j == 1 or j == n:
           print("*", end=" ")
       else:
           print(" ", end=" ")
   print()

17.Print Pascal’s Triangle.

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
   public static void main(String args[]) {
         int n =5;
       for (int i = 0; i < n; i++) {
           for (int j= n; j> i;j--)
               System.out.print(" ");

           int num=1;
           for (int j = 0; j <= i; j++) {
               System.out.print(num  + " ");
               num = num * (i - j) / (j + 1);
           }
           System.out.println(" ");
       }
   }
}

Python :

n = 4

for i in range(0, n + 1):
   for j in range(0, (n - i) + 1):
       num = 1
       print(" ", end=" ")
   for j in range(0, i + 1):
       print(int(num), " ", end=" ")
       num *= (i - j) / (j + 1)

   print()

18.Print half Pyramid.

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
   public static void main(String args[]) {
       int n = 5;
       for (int i = 0; i <= n; i++) {
           for (int j = 1; j <= i; j++)
               System.out.print(j);
           System.out.println();
       }}}

Python :

n = 5
for i in range(0, n + 1):
   for j in range(1, i + 1):
       print(j, end=" ")

   print(" ")

19.Print Inverted Half Pyramid.

1 to 9 all Pattern Quality Loss canvas Download here

9 to 19 all Pattern Quality Loss canvas Download here

Exercise

Print the pattern using for loop

Approach:

Solution

Java :

public class CodeXam {
   public static void main(String args[]) {
       int n = 4;
       for (int i = 1; i <= 4; i++) {
           for (int j = n; j >= i ; j--)

               System.out.print(i + " ");
           System.out.println();
       }
   }}

Python :

n = 5
for i in range(1, n + 1):
   for j in range(n, i, -1):
       print(i, end=" ")

   print(" ")

27. Rock, Paper Scissors game

Exercise

Create a simple Rock, Paper Scissors game

Approach:

So here we did like this
Rules and Main approach:
 Rock wins against scissors
 paper wins against rock
 scissors wins against paper
 Here 0 = ROCK 1 = Paper 2 = Scissors, 
If
Case 1 When user enter 0 Rock(0) wins against scissors(2) so user_input == 0 && comp_input == 2 So user win here
Case 2 When user enter 1 paper(1) wins against rock(0) so user_input == 1 && comp_input == 0 So user win 
Case 3 When user enter 2 scissors(2) wins against paper(1) so user_input == 2 && comp_input == 1 So user win
Else Any other case(except case1/case2/case3) computer win 

In java :
I use switch case and first make scanner class and random method 
Step 1: For user (scanner class takes input as 0 1 2)

Step 2: For pc (scanner class takes input as 0 1 2) scanner class takes input from the random method(where bound is 3)
Step 3:I use while loop for 3 times game play
Step 4: Total 3 case for user and total 3 case for Pc
Step 5:Now I compare the cases between user and pc
For user win
Case 1 When user enter 0 Rock(0) wins against scissors(2) so user_input == 0 && comp_input == 2 So user win here
Case 2 When user enter 1 paper(1) wins against rock(0) so user_input == 1 && comp_input == 0 So user win 
Case 3 When user enter 2 scissors(2) wins against paper(1) so user_input == 2 && comp_input == 1 So user win
For pc win
Any other case(except case1/case2/case3) computer win 
Step 6:Now just print the counter for how many times user win

Solution

Java :

import java.util.Random;
import java.util.Scanner;
public class CodeXam {
   public static void main(String[] args) {
       System.out.println("Welcome to Rock:Paper:Scissor Game");
       System.out.println("Rules:\n Rock wins against scissors\n paper wins against rock\n and scissors wins against paper\n ");
       System.out.println("enter\n 0:ROCK\n 1:Paper\n 2:Scissors ");
       Scanner sc = new Scanner(System.in);
       Random rd = new Random();

       int n = 1; // initialize n = 1
       int count = 0; // counter or terminator

       while (n <= 3) { //Condition 1<=3 means 3 times our loop runs means user play against computer total three times (1-2-3)
           System.out.println("Your turn enter number");
           int user_input = sc.nextInt(); //taking input from the user
           switch (user_input) {
               case 0: { // if user enter zero
                   System.out.println("You select Rock");
               }
               break;

               case 1: { // if user enter one
                   System.out.println("You select Paper");
               }
               break;
               case 2: { // if user enter two
                   System.out.println("You select Scissor");
               }
               break;
           }
           System.out.println("Computer's turn ");

           //nextInt(int n) is used to get a random number between 0(inclusive) and the number passed in this argument(n) here the bound is 3
           int comp_input = rd.nextInt(3); //taking input from the computer(0-3)
           switch (comp_input) {
               case 0: { // if our random program generate zero
                   System.out.println("Computer select Rock");
               }
               break;

               case 1: { // if our random program generate one
                   System.out.println("Computer select Paper");
               }
               break;
               case 2: { // if our random program generate two
                   System.out.println("Computer select Scissor");
               }
               break;
           }
           if (user_input == comp_input) { // if our random program's generate number = user's given number
               System.out.println("Draw match");
                  /* Rules:
                   Here 0 = ROCK 1 = Paper 2 = Scissors,

                   Rock(0) wins against scissors(2) so user_input == 0 && comp_input == 2 So user win
                   paper(1) wins against rock(0) so user_input == 1 && comp_input == 0 So user win
                   scissors(2) wins against paper(1) so user_input == 2 && comp_input == 1 So user win
                   */
           } else if ((user_input == 0 && comp_input == 2) || (user_input == 1 && comp_input == 0) || (user_input == 2 && comp_input == 1)) {
               System.out.println("Congratulations! You win the match :( ");
               count++; //Counter is the iterator for update 0-3

           } else { // If above three combinations(0-2 , 1-0 , 2 -1 ) are false , Computer win
               System.out.println("You lose! Haha,Better luck next time");
           }
           n++; //n++ is the iterator for update the match again (total 3 times play 1 - 2 - 3)

       }
       System.out.println("you won match " + count + " times"); //It can track users match record

   }

}

Python :

import random

print("Welcome to Rock:Paper:Scissor Game")
print("Rules:\n Rock wins against scissors\n paper wins against rock\n and scissors wins against paper\n ")
print("enter\n Rock\n Paper\n Scissors ")

n = 0
user_point = 0
computer_point = 0

while n < 3:
   user_action = input("Enter a choice (rock, paper, scissor): ")

   possible_actions = ["rock", "paper", "scissor"]
   computer_action = random.choice(possible_actions)
   print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")

   if user_action == computer_action:
       print(f"Both players selected {user_action}. It's a tie!")
   elif user_action == "rock":
       if computer_action == "scissor":
           print("Rock smashes scissors! You win!")
           user_point += 1
       else:
           print("Paper covers rock! You lose.")
           computer_point += 1
   elif user_action == "paper":
       if computer_action == "rock":
           print("Paper covers rock! You win!")
           user_point += 1
       else:
           print("Scissors cuts paper! You lose.")
           computer_point += 1
   elif user_action == "scissor":
       if computer_action == "paper":
           print("Scissors cuts paper! You win!")
           user_point += 1
       else:
           print("Rock smashes scissors! You lose.")
           computer_point += 1
   n += 1

if user_point == computer_point:
   print("It's a Tie")
elif user_point > computer_point:
   print(f"You've won {user_point}")
else:
   print(f"Computer won {computer_point}")

28. Do-while loop , while loop.

Exercise

Write a program to print first n natural numbers using a do-while loop and while loop

Approach:

Solution

Java :

//While loop
import java.util.Scanner;
public class CodeXam{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);

       // Take number from user
       System.out.print("Enter any number : ");
       int num = sc.nextInt();
       System.out.println("\nNatural numbers from 1 to " + num);
       int i = 1; //initialization
       while (i <= num) { //condition check
           System.out.print(i + " ");// if true execute the statement this with update
           i++; // update
       }
   }
}
//Do-While loop
public class CodeXam{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Take number from user
        System.out.print("Enter any number : ");
        int num = sc.nextInt();
        System.out.println("\nNatural numbers from 1 to " + num);
        int i = 1; //initialization
        do {
            System.out.print(i + " ");// the statement

            i++; // update
        }
        while (i <= num) ;//condition check if condition is true execute the statement
    }
}

Python :


# While Loop

"""A while loop will run a piece of code while a condition is True. It will keep executing the desired
set of code statements until that condition is no longer True. A while loop will always first check the condition
before running"""

num = int(input("Please Enter Your Number: "))
n = 1
print(f"Natural Numbers from {n} to {num} is :")
while n <= num:
   print(n, end=" ")
   n += 1

 # Do While Loop

"""What is unique in Do While loops is the fact that the code in the loop block will be executed at least one time.The code in the statement runs one time and then the condition is checked only after the code is executed 
As Do While Loop doesn't really exist in python , so we're going to modify a simple while loop into a Do While Loop"""

num = int(input("\nPlease Enter Your Number: "))
n = 1
print(f"Natural Numbers from {n} to {num} is :")
while True:
   print(n, end=" ")
   n += 1
   if n > num:
       break

29. Break in For and Do While Loop 1

Exercise

Print " user entered name " 10 times but if user would like to break the loop then print his/her name at that number of times and print "You want to stop at " user’s enter number " so I stop "
*Do it in for loop and do while loop
Enter Your Name
Xam
In order to stop printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name 
yes
Enter the number
6
Xam
Xam
Xam
Xam
Xam
Xam
You want to stop at 6 so I stop here

Approach:

So here we did like this
In a Nutshell …break statement completely exits the loop
The break statement is used to exit the loop irrespective of whether the condition is true or false.
Whenever a ‘break’ is encountered inside the loop, the control is sent outside the loop.
Syntax : 

Java :

// For Loop

import java.util.Scanner;
public class CodeXam{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter Your Name");
       String name = sc.nextLine();
       System.out.println("In order to stop printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name ");
       String answer_1 = sc.next();
       if ( (answer_1.equalsIgnoreCase("Yes"))) {
           System.out.println("Enter the number");
           int n = sc.nextInt();
           for (int i = 1; i <= 10; i++) {
               System.out.println(name);
               if (i == n) {
                   break;   //break the loop
               }
           }
           System.out.println("You want to stop at " + n + " so I stop here");
       }
       else  {
           System.out.println();
           for (int i = 1; i <= 10; i++) {
               System.out.println(name);
           }
       }
   }
   }

    // Do While Loop
import java.util.Scanner;
public class CodeXam{
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter Your Name");
      String name = sc.nextLine();
      System.out.println("In order to stop printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name ");
      String answer_1 = sc.next();
      if ((answer_1.equalsIgnoreCase("Yes"))) {
        System.out.println("Enter the number");
        int n = sc.nextInt();
        int i = 0;
        do {
          i++;

          if (i == n) {

            System.out.println("You want to stop at " + n + " so I stop here");
            break;   //break the loop
          }
          System.out.println(name);
        }
        while (i < 10);
      } else {

        int i = 1;
        do {
          i++;
          System.out.println(name);
        }

        while (i <= 10);
      }

    }}

Python :

# For Loop : 
name = input("Enter Your Name : ")
yes_no = input("""In order to stop printing your name at any number of
times below 10,enter 'Y/y' for yes and then enter the
number otherwise type 'N/n' for no to print your name 10 times : """)
if yes_no.lower() == "y":
   num = int(input("How many times you want to print your name: "))
   for i in range(1, 11):
       print(i, name)
       if i == num:
           break
elif yes_no.lower() == "n":
   for i in range(1, 11):
       print(i, name)
else:
   print("error ! Please Enter your ans 'yes' or 'no' as y/n")

# Do While Loop :

name = input("Enter Your Name : ")
yes_no = input("""In order to stop printing your name at any number of
times below 10,enter 'Y/y' for yes and then enter the
number otherwise type 'N/n' for no to print your name 10 times : """)
i = 1
if yes_no.lower() == "y":
   num = int(input("How many times you want to print your name: "))
   while i <= 11:
       print(i, name)
       i += 1
       if i == num+1:
           break

elif yes_no.lower() == "n":
   while i <= 10:
       print(i, name)
       i += 1

else:
   print("error ! Please Enter your answer 'yes' or 'no' as y/n")

30. Continue in For and Do While Loop 1

Exercise

print "user entered name" 10 times but if the user wants to skip his name at any number of times and print " You skip your “user entered name” at "user entered number" “ and then continue looping and print the remaining user entered name *Do it in for loop and do while loop

Enter Your Name
Xam
In order to skip printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name 
yes
Enter the number
5
Xam
Xam
Xam
Xam
You skip Xam at 5
Xam
Xam
Xam
Xam
Xam

Approach:

So here we did like this
In a Nutshell …continue statement skips the particular iteration of the loop.
The continue statement is used to immediately move to the next iteration of the loop.
The control is taken to the next iteration thus skipping everything below ‘continue’ inside the loop for that iteration.

Solution

Java :


//For Loop 
import java.util.Scanner;
public class CodeXam{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter Your Name");
       String name = sc.nextLine();
       System.out.println("In order to skip printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name ");
       String answer_1 = sc.next();
       if ( (answer_1.equalsIgnoreCase("Yes"))) {
           System.out.println("Enter the number");
           int n = sc.nextInt();
           for (int i = 1; i <= 10; i++) {

               if (i == n) {
                   System.out.println("You skip " + name + " at " + n);
                   continue;   
               }
               System.out.println(name);
           }
       }
       else  {
           for (int i = 1; i <= 10; i++)
           System.out.println(name);
           }
       }
   }

// Do While Loop 
import java.util.Scanner;
public class CodeXam{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter Your Name");
       String name = sc.nextLine();
       System.out.println("In order to skip printing at any number of times before 10 times printing your name, you can enter yes then enter number otherwise type no for 10 times printing your name ");
       String answer_1 = sc.next();
       if ( (answer_1.equalsIgnoreCase("Yes"))) {
           System.out.println("Enter the number");
           int n = sc.nextInt();
           int i =0;
           do {
               i++;

               if (i == n) {
                   System.out.println("You skip " + name + " at " + n);
                   continue;

               }
               System.out.println(name);
           }
           while (i<10);

       }
       else {

           int i = 1;
           do {
               i++;
               System.out.println(name);
           }

               while (i <= 10) ;
           }

       }
   }

Python :

# For Loop 

name = input("Enter Your Name : ")
yes_no = input("""In order to skip printing your name at any number below 10,
enter 'Y/y' for yes and then enter the number otherwise
type 'N/n' for no to print your name 10 times : """)
if yes_no.lower() == "y":
   num = int(input("How many times you want to print your name: "))
   for i in range(1, 11):
       if i == num:
           print(i, "You skip", name, "at", num)
           continue
       print(i, name)

elif yes_no.lower() == "n":
   for i in range(1, 11):
       print(i, name)
else:
   print("error ! Please Enter your answer 'yes' or 'no' as y/n")

# Do While Loop 
name = input("Enter Your Name : ")
yes_no = input("""In order to skip printing your name at any number below 10,
enter 'Y/y' for yes and then enter the number otherwise
type 'N/n' for no to print your name 10 times : """)
i = 0
if yes_no.lower() == "y":
   num = int(input("How many times you want to print your name: "))
   while i <= 9:
       i += 1
       if i == num:
           print(i, "You skip", name, "at", num)
           continue
       print(i, name)

elif yes_no.lower() == "n":
   while i <= 10:
      i += 1
       print(i, name)

else:
   print("error ! Please Enter your answer 'yes' or 'no' as y/n")

31. Sum first n even numbers using a while loop

Exercise

Write a program to sum first n(1 to n) even numbers using a while loop.

n= 4 means 2+4+6+8

Approach:

So here we did like this
Using While loop here

Work Process:
            sum = sum + evenNumber where sum = 0
             0 =  0 +  2  <-(1)  
             2 =  2 +  4  <-(2) 
             6 =  6 +  6  <-(3) 
            12 = 12 +  8  <-(4) 

           Sum of even numbers is = 20 (12 + 8 (4))

            evenNumber = even number + 2
           (1)->  2 = 2 + 2 
           (2)->  4 = 4 + 2
           (3)->  6 = 6 + 2
           (4)->  8 = 8 + 2

Solution

Java :

import java.util.*;
public class CodeXam_SumOfEvenNumber {
   public static void main(String[] args) {
       int sum = 0, evenNumber = 2;
       int count = 1;
       System.out.println("Enter Number");
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       while (count <= n) {

             sum += evenNumber;

             evenNumber += 2;

             count++;
             }
             System.out.println("First ( 1 - " + n + " ) Sum of even numbers is " + sum);
   }
}

Python :

n = int(input("Enter Your Number: "))
sum_of_evenNumbers = 0
even_numbers = 2
count = 1
while count <= n:
   sum_of_evenNumbers += even_numbers
   even_numbers += 2
   count += 1
print(f"First ( 1 -  {n} ) Sum of even numbers is {sum_of_evenNumbers}")

32. Corresponding Series

Exercise

Approach:

In java

Using math function 

 a +=(int)Math.pow(2,j)*b 
 System.out.print(a + " ")

Or 
 a = a+b;
 System.out.print(a + " ");
 b = b*2;

Solution

Java :

//Approach 1

import java.util.Scanner;

public class CodeXam {
   public static void main(String []argh){
       Scanner in = new Scanner(System.in);

       int t=in.nextInt();
       for(int i=0;i<t;i++){

           int a = in.nextInt();
           int b = in.nextInt();
           int n = in.nextInt();

           for (int j = 0; j < n ; j++){

               a +=(int)Math.pow(2,j)*b ;
               System.out.print(a + " ");
           }
           System.out.println();
       }
       in.close();
   }
}

//Approach 2

import java.util.Scanner;

public class CodeXam {
   public static void main(String []argh){
       Scanner in = new Scanner(System.in);

       int t=in.nextInt();
       for(int i=0;i<t;i++){

           int a = in.nextInt();
           int b = in.nextInt();
           int n = in.nextInt();

           for (int j = 0; j < n ; j++){

               a = a+b;

               System.out.print(a + " ");
               b = b*2;
           }
           System.out.println();
       }
       in.close();
   }
}

Python :

t = int(input("How many times you want to get the output ?\n"))
for i in range(1, t+1):
   a = int(input("Enter the value of a: "))
   b = int(input("Enter the value of b: "))
   n = int(input("Enter the value of n: "))

   for j in range(0, n):
       a += b

       print(a, end=" ")
       b *= 2
   print()

33. Calculate the sum of the numbers occurring in the multiplication table

Exercise

Write a program to calculate the sum of the numbers occurring in the multiplication table of given number

If Number = 2 , ( 2 1 = 2) + ( 2 2 = 4) + ( 2 3 = 6) + ( 2 4 = 8) + ( 2 5 = 10) + ( 2 6 = 12) + ( 2 7 = 14) + ( 2 8 = 16) + ( 2 9 = 18) + ( 2 10 = 20)

2+4+6+8+10+12+14+16+18+20 = 110

Approach:

So here we did like this
Sum += n*i
0 = 2*1
2 = 2*2
4 = 2*3
6 = 2*4
8 = 2*5
10 = 2*6
12 = 2*7
14 = 2*8
16 = 2*9
18 = 2*10
20 = sum

Solution

Java :

import java.util.Scanner;
public class CodeXam{
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter the number: ");
       int n = sc.nextInt();
       int sum = 0;
       for(int i=1;i<=10;i++){
           sum += n*i;

       }
       System.out.println("The sum of the numbers in the multiplication"+ "[ (" + n + " x 1)" + "to.." + "(" + n + " x 10) ]"  + "table of "+ n + " is "+ sum);

   }
}

Python :

n = int(input("Which multiplication table it is ?\n-> "))
total_sum = 0
for i in range(1, 11):
   total_sum += (n * i)
print(f"The sum of the numbers in the multiplication [({n} * 1) to ({n} * 10)] table {n} is {total_sum}"

34. Create an array of 5 floats and calculate their sum.

Exercise

Create an array of 5 floats and calculate their sum.

Approach:

So here we did like this
Java : Float number 45.7, 67.8, 63.4, 99.2, 100.0
sum = sum + element
Then using for each loop for print the array 

Solution

Java :

public class CodeXam {
  public static void main(String args[]) {
    float[]numbers = {45.7f, 67.8f, 63.4f, 99.2f, 100.0f};
    float sum = 0;
    for(float element:numbers){ //for each loop
      sum = sum + element;
    }
    System.out.println("The value of sum is " + sum);
  }
}

Python :

arr = [45.7, 67.8, 63.4, 99.2, 100.0]
total_sum = 0
for i in arr:
   total_sum += i
print("The value of sum is", total_sum)

35. Integer is present in an array or not

Exercise

Write a program to find out whether the user given floating value is present in an array of 45.7, 67.8, 63.4, 99.2, 100.0 or not

Approach:

So here we did like this
Java: 
1.Making Array of 45.7f, 67.8f, 63.4f, 99.2f, 100.0f
2.Taking number from the user 
3.Default Boolean value as false store in isInArray 
4.For each loop is used to traverse the array 
5.While traversing if any element match with entered number 
returning true will store in isInArray.
6.if not then simple print The value is not present in the array

Solution

Java :

import java.util.Scanner;
public class CodeXam {
  public static void main(String args[]) {
    float [] marks = {45.7f, 67.8f, 63.4f, 99.2f, 100.0f};
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number");
    float num = sc.nextFloat();
    boolean isInArray = false;
    for(float element:marks){
      if(num==element){
        isInArray = true;
        break;
      }
    }
    if(isInArray){
      System.out.println("The value is present in the array");
    }
    else{
      System.out.println("The value is not present in the array");
    }
  }
}

Python :

# approach 1
n = float(input("Please enter your value : "))
arr = [45.7, 67.8, 63.4, 99.2, 100.0]

if n in arr:
   print(f"The Value is present in the array at the index {arr.index(n)}")
else:
   print("The value isn't present in the array")

# approach 2
n = float(input("Please enter your value : "))
arr = [45.7, 67.8, 63.4, 99.2, 100.0]
in_arr = False
for i in arr:
   if i == n:
       in_arr = True
       break

if in_arr:
   print(f"The Value is present in the array at the index {arr.index(n)}")
else:
   print("The value isn't present in the array")

36. Averages from an array

Exercise

Calculate the average marks from an array containing marks(45.7, 67.8, 63.4, 99.2, 100.0 ) of all students in physics using a for-each loop in java and normal for loop in python.

Approach:

So here we did like this
Sum = 0 default 
Sum = sum + element (45.7f, 67.8f, 63.4f, 99.2f, 100.0f)
Sum / marks.length (n size means here 5) 

Solution

Java :

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

    {
      float[] marks = {45.7f, 67.8f, 63.4f, 99.2f, 100.0f};
      float sum = 0;
      for (float element : marks) {//for each loop
        sum = sum + element;
      }
      System.out.println("The value of average marks is " + sum / marks.length);
    }
  }
}

Python :

arr = [45.7, 67.8, 63.4, 99.2, 100.0]
total_sum = 0
for i in arr:
   total_sum += i
print(f"The average value of sum in the array {arr} is {total_sum/len(arr)}")

37. Two matrices of size 2x3 (2D)

Exercise

Create a program to add two matrices of size 2x3.

Approach:

So here we did like this

java:
1.Three multidimensional Arrays create mat1 ,mat2 , mat3  

 Mat1 = 5 10 20 (row1)   
        8 6 5 (row2) 
 Mat2 = 3 8 5(row1) 
        2 9 3 (row2) 
 Mat3 = Result Default zero so , 0 0 0(row1) 
                                 0 0 0(row2) 

2.first loop run for setting the value of i and j [matrix format] for result
Like this

 First loop for row (0-mat1.length)(2 arrays so 0 to 1)

 Second Loop for column (0-mat1[i].length)(here mat1[i] is first 5 10 20 means 3 element so run this loops for 0-2)  

3.Now just adding result[i][j] = mat1[i][j] + mat2[i][j]

4.Third loop run for printing the output  

Solution

Java :

public class CodeXam {
  public static void main(String[] args) {
    {
      int[][] mat1 = {{5, 10, 20}, //Multidimensional Arrays
              {8, 6, 5}};
      int[][] mat2 = {{3, 8, 5},
              {2, 9, 3}};

      int[][] result = {{0, 0, 0},
              {0, 0, 0}};

      for (int i = 0; i < mat1.length; i++) { // row number of times
        for (int j = 0; j < mat1[i].length; j++) { // column number of time
          System.out.format(" Setting value for i=%d and j=%d\n", i, j);
          result[i][j] = mat1[i][j] + mat2[i][j];
        }
      }
      for (int i = 0; i < mat1.length; i++) { // row number of times
        for (int j = 0; j < mat1[i].length; j++) { // column number of time
          System.out.print(result[i][j]+" ");
          result[i][j] = mat1[i][j] + mat2[i][j];}
        System.out.println();
      }
    }
  }}

Python :

# Program to add two matrices using nested loop

X = [[12, 32, 34],
     [65, 35, 23],
     [43, 45, 21]]

Y = [[10, 21, 23],
     [17, 54, 75],
     [24, 54, 75]]

result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]
# printing the matrices
print('Matrix 1 :')
for i in X:
    print(i)

print('\nMatrix 2 :')
for i in Y:
    print(i)

# iterate through rows
for i in range(len(X)):
    # iterate through columns
    for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j]

print('\nThe result is: ')
for r in result:
    print(r)

38. Reverse an array Iterative way.

Exercise

Write a program to reverse an array using swapping technique only (Iterative way)

Approach:

So here we did like this

Find only mid point and swap the elements 

Java : use this function for finding the mid Math.floorDiv(lengths, 2)
Return Value: This method returns the largest (closest to positive infinity) integer value that is less than or equal to the algebraic quotient.

Solution

Java :

public class CodeXam {
  public static void main(String[] args) {
    {
      int [] arr = {1, 21, 3, 4, 5, 34, 67};
      int lengths = arr.length;
      //we can use this also int n = lengths/2;
      int n = Math.floorDiv(lengths, 2); //mid find

      int temp;

      for(int i=0; i<n; i++){
        // Swap a[i] and a[l-1-i]
        // a   b   temp
        // |4| |3| ||
        temp = arr[i];
        arr[i] = arr[lengths-i-1];
        arr[lengths-i-1] = temp;
      }

      for(int element: arr){
        System.out.print(element + " ");
      }
    }
  }
}

Python :

arr = [98, 90, 87, 76, 65, 54, 43, 32, 21, 12]
start = 0
end = len(arr) - 1
print(f"Your default arr is :{arr}")

while start < end:
   arr[start], arr[end] = arr[end], arr[start]
   start += 1
   end -= 1

print(f"Your reversed list is :{arr}")

39.find the maximum element in an array.

Exercise

Write a program to find the maximum element in an array using function and without function

Approach:

So here we did like this
Set Max as a zero.
Traverse to arr length.
Now if any element is greater than Max then stop and make it Max 

Solution

Java :

// Without Function 

public class CodeXam  {
  public static void main(String[] args) {
    int [] arr = {1, 2100, 3, 455, 5, 34, 67,565569};
    int max = arr[0];
    for(int e: arr){ //for each loop

           /* We also write like this
              for (int i = 0; i < arr.length; i++) {
              if(arr[i] > max)
              max = arr[i];
              */

      if(e>max){
        max = e;

      }}
    System.out.println("The value of the maximum element in this array is: "+ max);

  }
}

// Using function

import java.util.Arrays;
public class CodeXam  {
  public static void main(String[] args) {
    int [] arr = {1, 2100, 3, 455, 5, 34, 67,565569};
    System.out.println("The value of the maximum element in this array is: " + Arrays.stream(arr).max().getAsInt());
  }
}

Python :

arr = [1, 2100, 3, 455, 5, 34, 67, 565569, 9756545, 5, 12]
max_value = 0
for i in arr:
   if i > max_value:
       max_value = i
print(f"The Element with the maximum value in the array is: {max_value}")

40.Find the minimum element in an array.

Exercise

Write a program to find the minimum element in an array using function and without function

Approach:

So here we did like this
Set min as a zero.
Traverse to arr length.
Now if any element is less than min then stop and make it min 

Solution

Java :

//Without Function 
public class CodeXam  {
  public static void main(String[] args) {
    int [] arr = { 2100, 3, 455, 5, 34, 67,565569};
    int min = arr[0];
    for(int e: arr){ //for each loop

          /* We also write like this
             for (int i = 0; i < arr.length; i++) {
             if(arr[i] < min)
             min = arr[i];
             */

      if(e<min){
        min = e;

      }}
    System.out.println("The value of the minimum element in this array is: "+ min);

  }
}

//Using function
import java.util.Arrays;
public class CodeXam  {
  public static void main(String[] args) {
    int [] arr = {2100, 3, 455, 5, 34, 67,565569};
    System.out.println("The value of the maximum element in this array is: " + Arrays.stream(arr).min().getAsInt());
  }
}

Python :

arr = [2100, 37, 455, 57, 34, 67, 7, 565569, 9756545, 53, 12]
min_value = arr[0]
for i in arr:
   if i < min_value:
       min_value = i
print(f"The Element with the minimum value in the array is: {min_value}")

41.Find whether an array is sorted or not.

Exercise

Write a program to find whether an array is sorted or not without function.

Approach:

So here we did like this

It is always shorter than i+1. If it's false and comes out to the loop then it's not started.

Solution

Java :

public class CodeXam  {
  public static void main(String[] args) {
    boolean isSorted = true;
    int [] arr = {1, 2, 3, 4, 5, 34, 67};
//we can’t compare for 67 with something, so we have to decrease the length one
    for(int i=0;i<arr.length-1;i++){

      if(arr[i] > arr[i+1]){
        isSorted = false;
        break;
      }
    }
    if(isSorted){
      System.out.println("The Array is sorted");
    }
    else{
      System.out.println("The Array is not sorted");
    }
  }
}

Python :

arr = [1, 2, 3, 4, 5, 34, 67, 73]  # use any array as your choice
isSorted = True
i = 1
while i < len(arr) - 1:
   if arr[i - 1] > arr[i]:
       isSorted = False
   i += 1

if isSorted:
   print(f"The array{arr} is sorted.")
else:
   print(f"The array{arr} isn't sorted.")

42.Matrix size as an input and printing its elements.

Exercise

Taking a matrix size as an input and printing its elements(taking from the user) .

Approach:

So here we did like this
Taking row size then column size then initialize the range according to the row column then place elements according to the row size and column size

Solution

Java :

import java.util.*;

public class CodeXam {
  public static void main(String[]args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your row size");
    int rows = sc.nextInt(); //taking row size
    System.out.println("Enter your column size");
    int cols = sc.nextInt(); //taking column size
    System.out.println("Enter elements according to your entered size (row x column)");
    int[][] numbers = new int[rows][cols];//initialize the size according to the user input

    //creating or visualize matrix format inside the code
    for(int i=0; i<rows; i++) { //traverse to our row size
      //columns
      for(int j=0; j<cols; j++) { //traverse to our column size

        numbers[i][j] = sc.nextInt();
      }
    }

    //printing the matrix
    for(int i=0; i<rows; i++) {
      for(int j=0; j<cols; j++) {
        System.out.print(numbers[i][j]+" ");
      }
      System.out.println();
    }
  }
}

Python :

row = int(input("Enter number of rows you want: "))
col = int(input("Enter number of columns you want: "))
mat = []
for m in range(row):
    a = []
    for n in range(col):
        a.append(0)
    mat.append(a)

for i in range(len(mat)):
    for j in range(len(mat[0])):
        mat[i][j] = int(input("Input element: "))
print("Your Matrix is :")
for i in mat:
    print(i)

43.Searching for an element x in a matrix.

Exercise

Searching for an element x in a matrix.

Approach:

1. The simple idea is to traverse the array and to search elements one by one.
2. Run a nested loop, outer loop for row and inner loop for the column
3. Check every element with x and if the element is found then print “element found”

Solution

Java :

import java.util.*;

public class CodeXam {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the row size");
    int rows = sc.nextInt();//taking row size
    System.out.println("Enter the Column size");
    int cols = sc.nextInt();//taking column size

    System.out.println("Insert elements(numbers) for your matrix [ Matrix size will be " + rows + "x" +cols +" ]");

    int[][] numbers = new int[rows][cols];//make this array size according to the user input

    // initialize the matrix
    //rows
    for(int i=0; i<rows; i++) {

      //columns
      for(int j=0; j<cols; j++) {

        numbers[i][j] = sc.nextInt();//taking element from user here
      }
    }
    System.out.println("If you want to search for a specific element in the matrix, enter the element here.");
    int x = sc.nextInt(); //taking the target

    //iterate
    for(int i=0; i<rows; i++) {
      for(int j=0; j<cols; j++) {

        //compare with x
        if(numbers[i][j] == x) { //if found x while iterating just print the location
          System.out.println( x + " found at location (" + i + ", " + j + ")");
        }
      }
    }

  }
}

Python :

row = int(input("Enter number of rows you want: "))
col = int(input("Enter number of columns you want: "))
mat = []
for m in range(row):
    a = []
    for n in range(col):
        a.append(0)
    mat.append(a)

for i in range(len(mat)):
    for j in range(len(mat[0])):
        mat[i][j] = int(input("Input element: "))
print("Your Matrix is :")
for i in mat:
    print(i)

d = int(input('Enter the element which you want to search for in the matrix : '))

for m, e in enumerate(mat):
    for n, ee in enumerate(e):
        if d == ee:
            print(f'{d} fount at location ({m},{n})')

44.Spiral order matrix as output for a given matrix of numbers.

Exercise

Print the spiral order matrix as output for a given matrix of numbers.

Approach:

Ref GFG Video Here (Recommend : 1.5x video Speed)

APPROACH : 
Algorithm: (We are given a 2D matrix of rows X cols ).

1. We will need 4 variables:
-------------------------------
a. row_start - initialized with 0.
b. row_end - initialized with n-1.
c. column_start - initialized with 0.
d. column_end - initialized with m-1.

2. First of all, we will traverse in the row row_start from column_start
to column_end and we will increase the row_start with 1 as we have
traversed the starting row.

3. Then we will traverse in the column column_end from row_start to
row_end and decrease the column_end by 1.

4. Then we will traverse in the row row_end from column_end to
column_start and decrease the row_end by 1.

5. Then we will traverse in the column column_start from row_end to
row_start and increase the column_start by 1.

6. We will do the above steps from 2 to 5 until row_start <= row_end
and column_start <= column_end.

Solution

Java :


//Time complexity O(m X n)

import java.util.*;

public class CodeXam {

    // first part same as problem 43.Searching for an element x in a matrix.
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the row size");
        int rows = sc.nextInt();//taking row size
        System.out.println("Enter the Column size");
        int cols = sc.nextInt();//taking column size
        System.out.println("Insert elements(numbers) for your matrix [ Matrix size will be " + rows + "x" +cols +" ]");
        int matrix[][] = new int[rows][cols];//make this array size according to the user input
        // initialize the matrix
        //rows
        for(int i=0; i<rows; i++) {
            //columns
            for(int j=0; j<cols; j++) {
                matrix[i][j] = sc.nextInt();///taking element from user here
            }
        }

    //2nd part

        System.out.println("The Spiral Order Matrix is : ");

        //main code

        int rowStart = 0;//row_start - initialized with 0 (check approach box)
        int rowEnd = rows-1;//row_end - initialized with n-1 (check approach box)
        int colStart = 0;//column_start - initialized with 0 (check approach box)
        int colEnd = cols-1;//column_end - initialized with m-1.(check approach box)

        //To print spiral order matrix
        while(rowStart <= rowEnd && colStart <= colEnd) { //checking Condition or base case

            /* left to right*/

            for(int col=colStart; col<=colEnd; col++) {//First, we will traverse column_star to column_end
                System.out.print(matrix[rowStart][col] + " "); //row start col end(it wil print first row 5 6 3 6 8 according to the picture and row start always same but column wil change)
            }
            rowStart++; //now increase the row means 0 -> 1 -> 2 ->3 -> 4

            /* Down- right column */

            for(int row=rowStart; row<=rowEnd; row++) { //row start is now for remaining row
                System.out.print(matrix[row][colEnd] +" "); //row start col end(4 8 8 according to the picture)
            }
            colEnd--; //now decrease the column means reduce the array

            /* Right - Print the last row from the remaining rows*/

            for(int col=colEnd; col>=colStart; col--) {
                System.out.print(matrix[rowEnd][col] + " ");
            }
            rowEnd--;

            // Toward the up-> Print the first column from the remaining column
            for(int row=rowEnd; row>=rowStart; row--) {
                System.out.print(matrix[row][colStart] + " ");
            }
            colStart++;

            System.out.println();
        }
    }
}

Python :

def spiralPrint(m, n, a):
    k = 0
    l = 0

    ''' k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator '''

    while k < m and l < n:

        # Print the first row from
        # the remaining rows
        for i in range(l, n):
            print(a[k][i], end=" ")

        k += 1

        # Print the last column from
        # the remaining columns
        for i in range(k, m):
            print(a[i][n - 1], end=" ")

        n -= 1

        # Print the last row from
        # the remaining rows
        if k < m:

            for i in range(n - 1, (l - 1), -1):
                print(a[m - 1][i], end=" ")

            m -= 1

        # Print the first column from
        # the remaining columns
        if l < n:
            for i in range(m - 1, k - 1, -1):
                print(a[i][l], end=" ")

            l += 1

# Driver Code
a = [[1, 2, 3, 4, 5, 6],
     [7, 8, 9, 10, 11, 12],
     [13, 14, 15, 16, 17, 18]]

R = 3
C = 6

# Function Call
print('Your Matrix in Spiral Order:')
spiralPrint(R, C, a)

45. Transpose of a Matrix

Exercise

For a given matrix of N x M, print its transpose

Approach:

First we run the loop for row and then for column, 
but here we will do the opposite for column first, then row 

Solution

Java :

/*
 time complexity of O(n + m),
 where n is the number of columns and m is the number of non-zero elements in the matrix.
 The computational time for transpose of a matrix using identity matrix as reference matrix is O(m*n).
  Suppose, if the given matrix is a square matrix, the running time will be O(n2).
*/
import java.util.*;

public class CodeXam {

    // first part same as problem 43.Searching for an element x in a matrix.
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the row size");
        int rows = sc.nextInt();//taking row size
        System.out.println("Enter the Column size");
        int cols = sc.nextInt();//taking column size
        System.out.println("Insert elements(numbers) for your matrix [ Matrix size will be " + rows + "x" +cols +" ]");
        int matrix[][] = new int[rows][cols];//make this array size according to the user input
        // initialize the matrix
        //rows
        for(int i=0; i<rows; i++) {
            //columns
            for(int j=0; j<cols; j++) {
                matrix[i][j] = sc.nextInt();///taking element from user here
            }
        }

            System.out.println("The transpose is : ");
            //To print transpose just interchange the sequence
            for(int j=0; j<cols ;j++) { //just run first loop for column
                for(int i=0; i<rows; i++) {//just run 2nd loop for row
                    System.out.print(matrix[i][j]+" ");
                }
                System.out.println();
            }
        }
    }

Python :

46. Given an array A of size N, print the reverse of it.

Exercise

Solve here

Approach:

1.No of Test case "Suppose We are gonna teste once so input is 1"

2.Traverse 0 to no of Testcase 

3.now taking the size of the array 

4.array size declare according to the input 

5.Traverse to Size of the array to take the element and map them according to the index position

6.taking elements while traversing (suppose for 0 index take a element 1)

7.Reverse the array - traverse length to index 0 

Solution

Java :

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt(); //No of Test case "Suppose We are gonna teste once so input is 1"
        for(int i=0; i<T; i++){ //Traverse 0 to no of Testcase 
            int N = sc.nextInt();//now taking the size of the array 
            int arr[] = new int[N];//array size declare according to the input 
            for(int j=0; j<N; j++){//Traverse to Size of the array to take the element and map them according to the index position
                arr[j]=sc.nextInt();//taking elements while traversing (suppose for 0 index take a element 1)
            }

           //Reverse the array 

            for(int j=N-1; j>=0; j--){
                System.out.print(arr[j]+" ");
            }
            System.out.println();
        }
    }
}

Python :

47. Maximum and Minimum element in an array - O(N)

Exercise

Solve here

Approach:

Same As Problem no 39 and 40 just combine them

Solution

Java :

class Compute 
{
    static pair getMinMax(long a[], long n)  
    {
    long min=0, max=0;//min maxinitialize with  zer

       if(n > 0){//array size in n here  
           min = a[0]; 
           max = a[0];
           for(long x : a){ //for each loop
               if(min > x){
                   min = x;
               }
               if(max < x){
                   max = x;
               }
           }
       }

       //pair p = new pair(min, max); //same 

       return new pair(min, max);

   }
}

Python :

48.Kth smallest element

Exercise

Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.

Do it Here

Approach:

Watch this video


Use PriorityQueue

Solution

Java :

class Solution{
  public static int kthSmallest(int[] arr, int l, int r, int k) 

    /*

    //Approach -1 (basic)
    {
        //sort this array then just return the index element 
      Arrays.sort(arr);
        return(arr[k-1]);
    } 
    */

  /**

   //Approach -2 (Follow this one)
   {
   PriorityQueue<Integer> pq=new PriorityQueue<>(); //Integer type priority queue 

   // a min heap by default is created in java

   //traverse 0-arr.length
   for(int i=0;i<arr.length;i++)
   {
   pq.add(arr[i]); //add elements in Priority Queue 
   }

   //again iterate 

   for(int i=0;i<k-1;i++)
   {

   // The peek() method only retrieved the element 
   // at the head but the poll() also removes the element 
   //along with the retrieval

   // Also you can use remove

   pq.remove();
   }
   return pq.peek();
   }

   */

  //almost same

  {
    //Your code here
    int n = r-l+1;
    Queue<Integer> pq = new PriorityQueue<>();
    for(int i = 0; i < n; i++) {
      pq.add(arr[i]);
    }
    int K = 0;
    while(!pq.isEmpty() && K < k - 1) {
      pq.poll();
      K++;
    }
    int ans = -1;
    if (!pq.isEmpty()) {
      ans = pq.poll();
    }
    return ans;
  }
}

Python :

49. Set Matrix Zeroes

Exercise

leetcode Solve Here

Given a matrix if an element in the matrix is 0 then you will have to set its entire column and row to 0 and then return the matrix.

Examples 1:

Input: matrix=[[1,1,1],[1,0,1],[1,1,1]]

Output: [[1,0,1],[0,0,0],[1,0,1]]

Explanation: Since matrix[2][2]=0.Therfore the 2nd column and 2nd row wil be set to 0.

Input: matrix=[[0,1,2,0],[3,4,5,2],[1,3,1,5]]

Output:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Explanation:Since matrix[0][0]=0 and matrix[0][3]=0. Therefore 1st row, 1st column and 4th column will be set to 0

Solution Video Here

Solution Video(Hindi) Here

Approach 1:(Using brute force)


Assuming all the elements in the matrix are non-negative. 
Traverse through the matrix and if you find an element with value 0, 
then change all the elements in its row and column to -1, except when an element is 0.
The reason for not changing other elements to 0, but -1, 
is because that might affect other columns and rows. 
Now traverse through the matrix again and if an element
is -1 change it to 0, which will be the answer.

Solution

Java :

import java.util.*;
class CodeXam {
    static void setZeroes(int[][] matrix) {
        int rows = matrix.length, cols = matrix[0].length;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {

                    int ind = i - 1;
                    while (ind >= 0) {
                        if (matrix[ind][j] != 0) {
                            matrix[ind][j] = -1;
                        }
                        ind--;
                    }
                    ind = i + 1;
                    while (ind < rows) {
                        if (matrix[ind][j] != 0) {
                            matrix[ind][j] = -1;
                        }
                        ind++;
                    }
                    ind = j - 1;
                    while (ind >= 0) {
                        if (matrix[i][ind] != 0) {
                            matrix[i][ind] = -1;

                        }
                        ind--;
                    }
                    ind = j + 1;
                    while (ind < cols) {
                        if (matrix[i][ind] != 0) {
                            matrix[i][ind] = -1;

                        }
                        ind++;
                    }
                }
            }
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] <= 0) {
                    matrix[i][j] = 0;
                }
            }
        }

    }

    public static void main(String args[]) {
        int arr[][] = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
        setZeroes(arr);
        System.out.println("The Final Matrix is ");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Approach 2:(Better approach)

Intuition: Instead of traversing through each row and column, we can use dummy arrays to check if the particular row or column has an element 0 or not, which will improve the time complexity.

Intuition: Instead of traversing through each row and column,
 we can use dummy arrays to check if the particular row or column has 
 an element 0 or not, which will improve the time complexity.

Approach:Take two dummy array one of size of row and other of 
size of column.Now traverse through the array.
If matrix[i][j]==0 then set dummy1[i]=0(for row) and dummy2[j]=0(for column).
Now traverse through the array again and 
if dummy1[i]==0  || dummy2[j]==0 then arr[i][j]=0,else continue.

Solution

Java :

import java.util.*;
class CodeXam{
  static void setZeroes(int [][] matrix) {
    int rows = matrix.length, cols = matrix[0].length;
    int dummy1[]=new int[rows];
    int dummy2[]=new int[cols];
    Arrays.fill(dummy1,-1);
    Arrays.fill(dummy2,-1);
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        if (matrix[i][j] == 0) {
          dummy1[i] = 0;
          dummy2[j] = 0;
        }
      }

    }
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        if (dummy1[i] == 0 || dummy2[j]==0) {
          matrix[i][j] = 0;
        }
      }
    }
  }

  public static void main(String args[]) {
    int arr[][] = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
    setZeroes(arr);
    System.out.println("The Final Matrix is ");
    for (int i = 0; i < arr.length; i++) {
      for (int j = 0; j < arr[0].length; j++) {
        System.out.print(arr[i][j] + " ");
      }
      System.out.println();
    }
  }
}

Approach 3:(Optimizing the better approach.)

Intuition: Instead of taking two dummy arrays we can use the first row and column of the matrix for the same work. This will help to reduce the space complexity of the problem. While traversing for the second time the first row and column will be computed first, which will affect the values of further elements that’s why we traversing in the reverse direction.

Instead of taking two separate dummy array,take first row and column
of the matrix as the array for checking whether the particular column 
or row has the value 0 or not.Since matrix[0][0] are overlapping.
Therefore take separate variable col0(say) to check if the 0th column 
has 0 or not and use matrix[0][0] to check if the 0th row has 0 or not.
Now traverse from last element to the first element and 
check if matrix[i][0]==0 || matrix[0][j]==0 and if true set matrix[i][j]=0,else continue.

Solution

Java :

import java.util.*;
class CodeXam{
  static void setZeroes(int[][] matrix) {
    int col0 = 1, rows = matrix.length, cols = matrix[0].length;

    for (int i = 0; i < rows; i++) {
      if (matrix[i][0] == 0) col0 = 0;
      for (int j = 1; j < cols; j++)
        if (matrix[i][j] == 0)
          matrix[i][0] = matrix[0][j] = 0;
    }

    for (int i = rows - 1; i >= 0; i--) {
      for (int j = cols - 1; j >= 1; j--)
        if (matrix[i][0] == 0 || matrix[0][j] == 0)
          matrix[i][j] = 0;
      if (col0 == 0) matrix[i][0] = 0;
    }
  }
  public static void main(String args[]) {
    int arr[][] = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
    setZeroes(arr);
    System.out.println("The Final Matrix is ");
    for (int i = 0; i < arr.length; i++) {
      for (int j = 0; j < arr[0].length; j++) {
        System.out.print(arr[i][j] + " ");
      }
      System.out.println();
    }
  }
}

LeetCode Approach 3 Solution

Java :

class Solution {
    public void setZeroes(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;

        boolean row=false, col=false;

        //we are checking the first column 

        for(int i=0;i<n;i++)if(matrix[i][0]==0)col=true;

        //we are checking the first row 

        for(int j=0;j<m;j++)if(matrix[0][j]==0) row=true;

//** now we are working for remain matrix 

        for(int i=1;i<n;i++){
        for(int j=1;j<m;j++){

            if(matrix[i][j]==0){
                matrix[0][j]=0; 
                matrix[i][0]=0;

            }
        }           

    }

        //if column element is zero then fill the entire row with zero

        for(int i=1;i<n;i++){
        if (matrix[i][0] == 0) {

           for(int j=0;j<m;j++){
              matrix[i][j] = 0; 

            }
         }

        }
         //if traverse for column 

        for(int j=1;j<m;j++){
           if(matrix[0][j] == 0){

           for(int i=0;i<n;i++){
            matrix[i][j] = 0; 

           }
           }
        }

       // now we are checking is the row and column false or true 

        if(row){ //if row zero make all zero 
             for(int j=0;j<m;j++){
              matrix[0][j] = 0; 

             }
        }

         if(col){ //if row zero make all zero 
             for(int i=0;i<n;i++){
              matrix[i][0] = 0; 

             }
        }

    }
}

50.Pascal's Triangle

Exercise

(Leetcode)Solve Here

Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:

Input: numRows = 1
Output: [[1]]

visualize :

Input Format: N = 5

Result:
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Explanation: There are 5 rows in the output matrix. Each row corresponds to each one of the rows in the image shown above.

Input Format: N = 1

Result: 
    1

Intuition:

When you see the image above, you get a pretty good idea of what you are supposed to do here.
Think about the image as a matrix now where each line is basically a row in the matrix. 
So, first things first, if you are at the edge of the matrix, the value is 1, 
that’s for sure. Now, what about the inner elements? Well, any inner element is 
obtained by doing the sum of the 2 values present in the row just above it, i.e., 
if the element is at index (i, j), then matrix[i][j] 
can be obtained by doing matrix[i – 1][j – 1] + matrix[i – 1][j].

Approach: To solve the problem, we need to first create an array of size N or numRows (input value). This array is used to store each of the rows expected in the output, so, for example, array[1] = [1,1]. In this array, the number of columns (say, numCols) is equal to the number of the i-th row + 1 (Since, 0-indexed), i.e., for 0-th row, numCols = 1. So, the number of columns is different for each row.

Next, we need to run a loop from i = 0 to numRows – 1 (inclusive) in order to store each row in our array. For each of iteration of this loop, we follow the below steps:

After iterating numRows times, you return the array.

Dry Run: Let’s do a dry run to understand it in a much better way.

Input: numRows = 5

   = array[1][0] + array[1][1] = 1 + 1 = 2

So, array = [[1],[1,1],[1,2,1],[],[]]

Time Complexity: We are creating a 2D array of size (numRows * numCols) (where 1 <= numCols <= numRows), and we are traversing through each of the cells to update it with its correct value, so Time Complexity = O(numRows2).

Space Complexity: Since we are creating a 2D array, space complexity = O(numRows2).

Solution

Java :

class Solution {
  public List<List<Integer>> generate(int numRows) {
       /* 
       List(Index)    row
        0              1
        1              2
        2              3
        3              4
        4              5

       if we wanna make a row(n)=5 we have to set the list as (n-2) means (5-2)=3 
       so index 3 means row 5

       */

    if(numRows==0) return new ArrayList();
    List<List<Integer>> result = new ArrayList(); //array list result of result 

    //all rows 

    for(int i=1;i<=numRows; i++){//we need to feel out entire 5 rows assume that numrow = 5
      List<Integer> row = new ArrayList();//4th-for single row  
      for(int j=0;j<i;j++){//2nd we need to make 5 rows means less than 5 index
        if(j==0 || j==i-1){//6th -first and last position always 1(base case)
          row.add(1);//7th- simple add if index position is 0 nd i-1
        }else{

                     /*
                     lookat the image for last row 1 4 6 4 1 
                     //1 element  ----- previous rows' 0 + 1(index)
                     //2 element  ----- previous rows' 1 + 2(index)
                     //3 element  ----- previous rows' 2 + 3(index)

                    ****we need 4th row for develop the 5th row so already i told you we need (n-2)=3 position for that 5th row
                     */

          //8th -  i-2 = for develop 5th row 
          //if we want to build an eement (suppose 3 = 2+3),we need that element(j)with previous element(j-1)

          row.add(result.get(i-2).get(j)+result.get(i-2).get(j-1));//main element(from previous row)+previous element(from previous row)
        }
      }
      result.add(row); //1 2 3 4 5 //5th add this row for result 
    }
    return result; //3rd-return result 
  }
}

51.Factorial of a Number:

Exercise

Find the factorial of a number

Approach:

Here at first two variables are being initialized one is fact which is initialized to 1 and it would contain the result that we would be printing, the second one is the num variable which contains the value we want to find the factorial of which can be hardcoded(as I have done in this example) or can be taken as a input from the user. After that a for loop is executed from 2 to the number i.e. n and finally the result is returned since 5!=5*4*3*2*1

Solution

Java :

public class code_xam
{
    public static void main(String[] args) {
        int fact=1,num=10;
        for (int i=2;i<=num;i++){
            fact=fact*i;
        }
        System.out.println("Factorial of "+num+" is "+fact);
    }
}

Python :

fact,num=1,5
for i in range(1,num+1):
    fact=fact*i
print(f"Factorial of {num} is {fact}")