Friday, June 21, 2019

Magic Matrix in Java

Magic Matrix in Java

Magic matrix is such an odd sized matrix whose sum of each row, column and diagonal are equal.  The following video is an implementation of an odd sized magic matrix.

Source code for magic matrix

import java.util.*;
class MagicSquare{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int n,i,j,r,c;
        System.out.println("Enter the size of the matrix:");
        n=sc.nextInt();
        if(n%2==0)
            System.out.println("Only odd size matrix:");
        else
        {
            r=0;c=n/2;
            int a[][]=new int[n][n];
            for(i=1;i<=n*n;i++)
            {
                a[r][c]=i;
                if (i%n==0)
                    r++;
                else
                {
                    r--;
                    c--;
                    if(r<0 n="" p="" r="">
                    if(c<0 c="" n="" p="">
                }
            }
            System.out.println("The magic square:");
            for(i=0;i
            {
                for(j=0;j
                {
                    System.out.printf("%3d",a[i][j]);//printf() for formatted output
                }
                System.out.println();
            }
        }
    }
}

        

Tuesday, June 18, 2019

Finding the frequency of each element in a Tuple in Python

Code to find the frequency of each element in a Tuple in Python:
T=(1,2,3,1,1,5,5,6,1,5,5,6)
print("Tuple=",T)
for i in range(0,len(T)):
    if T[i] not in T[:i]:
        c=T[i:].count(T[i])
        print(T[i],"frequency=",c)

An introduction to recursive functions

Code to find the sum of first n natural numbers:
def sum(n,s=0):
    if n==0:
        return s;
    else:
        s=s+n;
        return sum(n-1,s)

#main
n=int(input("Enter a number:"))
s=sum(n)
print(s)



Code to find the largest digit in an integer:
def largest(n,l=0):
    if n==0:
        return l;
    else:
        if n%10>l:
            l=n%10
        return largest(n//10,l)

#main
n=int(input("Enter an integer:"))
p=largest(n)
print("Largest Digit",p)
 


Code to find the HCF between 2 numbers:
def HCF(n,d):
    if n%d==0:
        return d
    else:
        r=n%d
        n=d
        d=r
        return HCF(n,d)

#main
n=int(input("Enter a number:"))
m=int(input("Enter another number:"))
h=HCF(n,m)
print("HCF=",h)
 

  Source Code for :   Displaying all possible fangs of a Vampire Number in Java import java.util.*; class Number {     public static void ma...