Author: admin

  • Java Program to find the sum of the Largest Forward Diagonal

    in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix).

    Java Program to find the sum of the Largest Forward Diagonal

    import java.util.ArrayList;
    
    public class Main {
        public static int diagonalSum(ArrayList<ArrayList<Integer>> matrix, int startRow, int startCol) {
            int sum = 0;
            int rows = matrix.size();
            int cols = matrix.get(0).size();
            
            while (startRow < rows && startCol < cols) {
                sum += matrix.get(startRow).get(startCol);
                startRow++;
                startCol++;
            }
            return sum;
        }
    
        public static int sumOfLargestForwardDiagonal(ArrayList<ArrayList<Integer>> matrix) {
            int rows = matrix.size();
            int cols = matrix.get(0).size();
            int maxSum = Integer.MIN_VALUE;
    
            // Iterate through each row to start a forward diagonal
            for (int row = 0; row < rows; row++) {
                maxSum = Math.max(maxSum, diagonalSum(matrix, row, 0));
            }
    
            // Iterate through each column to start a forward diagonal
            for (int col = 1; col < cols; col++) {
                maxSum = Math.max(maxSum, diagonalSum(matrix, 0, col));
            }
    
            return maxSum;
        }
    
        public static void main(String[] args) {
            ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
            matrix.add(new ArrayList<Integer>() {{
                add(1);
                add(2);
                add(3);
            }});
            matrix.add(new ArrayList<Integer>() {{
                add(9);
                add(5);
                add(6);
            }});
            matrix.add(new ArrayList<Integer>() {{
                add(7);
                add(9);
                add(9);
            }});
    
            int sumOfLargestDiagonal = sumOfLargestForwardDiagonal(matrix);
            System.out.println("Sum of largest forward diagonal: " + sumOfLargestDiagonal);
        }
    }
    

    Output:

    Sum of largest forward diagonal: 18
    

    Explanation:
    It calculates the sum of each forward diagonal and returns the sum of the largest forward diagonal. The diagonalSum method calculates the sum of a forward diagonal, and the sumOfLargestForwardDiagonal method finds the largest sum among all forward diagonals. Finally, the main method calls sumOfLargestForwardDiagonal to find and print the sum of the largest forward diagonal in the given matrix.

    The forward diagonals are:

    1. Starting from (0,0): 1
    2. Starting from (1,0): 9 + 2 = 11
    3. Starting from (2,0): 7 + 5 + 3 = 15
    4. Starting from (0,1): 2 + 5 + 9 = 16
    5. Starting from (0,2): 3 + 6 + 9 = 18
    6. Starting from (0,3) (out of bounds)
    7. Starting from (1,1) (out of bounds)
    8. Starting from (2,1) (out of bounds)

    Among these sums, the largest sum is 18.


  • C Program to search an element in an array using Pointers

    A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array will be passed. The function will return 1 if any element matches with the searched element otherwise it will return 0.

    #include <stdio.h>
    
    int search_function(int *a, int n, int s_element)
    {
      int i;
    
      for (i = 0; i < n; i++)
      {
        if (a[i] == s_element)
        {
          return 1;
        }
      }
    
      return 0;
    
    }
    
    int main()
    {
      int arr[30], i, size, s_element;
    
      printf("Enter the size of an array: ");
      scanf("%d", &size);
    
      printf("Enter %d elements of an array:\n", size);
      for (i = 0; i < size; i++)
      {
        scanf("%d", &arr[i]);
      }
    
      printf("\nEnter the element to be searched: ");
      scanf("%d", &s_element);
    
      if (search_function(arr, size, s_element))
        printf("Searched element %d is present.", s_element);
      else
        printf("Searched element %d is NOT present.", s_element);
    
    }

    This C program defines a function called search_function that searches for a given element in an array. Here’s a concise explanation of the program:

    1. Function Definition: search_function(int *a, int n, int s_element)
      • This function takes three parameters:
        • a: a pointer to an integer array.
        • n: the size of the array.
        • s_element: the element to be searched in the array.
      • It iterates through the array using a for loop and checks if the current element is equal to the s_element.
      • If it finds a match, it returns 1 (true), indicating that the element is present in the array.
      • If no match is found after checking all elements, it returns 0 (false).
    2. Main Function: main()
      • The main function begins the execution of the program.
      • It declares an array arr of size 30, variables i (for loop iteration), size (to store the size of the array), and s_element (the element to be searched).
      • The user is prompted to enter the size of the array, followed by the array elements.
      • The user is then prompted to enter the element to be searched (s_element).
      • The search_function is called with the array, size, and search element, and the result is used to print whether the element is present or not.
    3. Output:
      • The program outputs whether the searched element is present or not in the array.

  • C Program to find the sum of the digits of a number using recursion function

    This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation:

    1. Function Definition: sumDigits(int n)
      • This function calculates the sum of digits of a number n.
      • The base case checks if n is 0. If true, it returns 0 (no digits to sum).
      • Otherwise, it uses recursion by summing the last digit of n (obtained by n % 10) with the sum of the remaining digits (obtained by sumDigits(n / 10)).
    2. Main Function: main()
      • The main function begins the execution of the program.
      • It declares two variables: num for user input and result to store the sum of digits.
      • The user is prompted to enter a number, which is then stored in the variable num.
      • The sumDigits function is called with num as an argument, and the result is stored in the result variable.
      • The program prints the sum of digits.
    3. Output:
      • The program outputs the calculated sum of digits for the given input.
    #include <stdio.h>
    
    int sumDigits(int);
    int main()
    {
      int num, result;
    
      printf("Enter a number: ");
      scanf("%d", &num);
    
      result = sumDigits(num);
    
      printf("Sum of digits of a number: %d", result);
    
      return 0;
    }
    
    int sumDigits(int n)
    {
      if (n == 0)
        return 0;
    
      return (n % 10 + sumDigits(n / 10));	//recursion call
    }

    Output:

    Enter a number: 123
    Sum of digits of a number: 6

    Learn more on recursion.


  • C program to find factorial of a number using Ternary operator with Recursion

    Recursion refers to the function calling itself directly or in a cycle.

    Before we begin, you should have the knowledge of following in C Programming:

    #include <stdio.h>
    
    int factorial(int n)
    {
      // using ternary operator with recursion
      return (n == 1 || n == 0) ? 1 : n* factorial(n - 1);
    }
    
    int main()
    {
      int num, result;
    
      //taking Inputs
      printf("Enter the number to find factorial: ");
      scanf("%d", &num);
    
      //function call and display the result
      result = factorial(num);
      printf("Factorial of %d is: %d\n", num, result);
      getch();
      return 0;
    }

    This C program calculates the factorial of a given number using recursion and the ternary operator. Here’s a brief explanation:

    1. Function Definition: factorial(int n)
      • This function calculates the factorial of a number n.
      • It uses a ternary operator (? :) to check if n is 1 or 0. If true, it returns 1; otherwise, it recursively calls itself with the argument n - 1 multiplied by n.
    2. Main Function: main()
      • The main function begins the execution of the program.
      • It declares two variables: num for user input and result to store the factorial.
      • The user is prompted to enter a number, which is then stored in the variable num.
      • The factorial function is called with num as an argument, and the result is stored in the result variable.
      • The program prints the factorial result.
    3. Usage of getch():
      • The getch() function is used to hold the console window open until a key is pressed. Note that this function is not standard and may not be available on all systems.
    4. Output:
      • The program outputs the calculated factorial for the given input.
    5. Termination:
      • The program returns 0, indicating successful execution.

  • C Program to Add Two Numbers Using Call by Reference

    The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through the topic below.

    #include <stdio.h>
    
    //user-defined function
    float addFunc(float *a, float *b)
    {
      float sum;
    
      sum = *a + *b;
    
      return sum;
    }
    
    int main()
    {
      float num1, num2, result;
    
      printf("Enter the first number: ");
      scanf("%f", &num1);
    
      printf("Enter the Second number: ");
      scanf("%f", &num2);
    
      result = addFunc(&num1, &num2);
    
      printf("Sum of the result: %f", result);
    
      return 0;
    }

    Output:

    Enter the first number: 15.5
    Enter the Second number: 20.5
    Sum of the result: 36.000000


    This is a simple C program that demonstrates the use of a user-defined function to add two floating-point numbers. Let’s break down the code:

    Function Declaration:

    float addFunc(float *a, float *b)
    • This line declares a function named addFunc that takes two float pointers (a and b) as parameters and returns a float value.

    Function Definition:

    { float sum; sum = *a + *b; return sum; }
    • Inside the addFunc function, it calculates the sum of the values pointed to by a and b and returns the result.

    Main Function:

    int main()
    {
        // Variable declaration
        float num1, num2, result;
    
        // Input from user
        printf("Enter the first number: ");
        scanf("%f", &num1);
    
        printf("Enter the Second number: ");
        scanf("%f", &num2);
    
        // Function call
        result = addFunc(&num1, &num2);
    
        // Output
        printf("Sum of the result: %f", result);
    
        return 0;
    }
    • The main function is the entry point of the program.
    • It declares three float variables num1, num2, and result.
    • It takes user input for num1 and num2 using scanf.
    • Calls the addFunc function, passing the addresses of num1 and num2.
    • Prints the result.

    Execution:

    • The program prompts the user to enter two floating-point numbers.
    • It then calculates the sum of these numbers using the addFunc function.
    • Finally, it prints the result to the console.

    So, if the user enters, for example, 5.3 and 2.7, the program would output:

    Enter the first number: 5.3
    Enter the Second number: 2.7
    Sum of the result: 8.000000

  • Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

    In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will get output as ab,cd,ef,g


    Javascript and Python program to concatenate the string element in an array with its preceding string element.

    Javascript:

    const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
    let result = [];
    
    for(let i=0; i <= arr.length-1; i = i+2){
            let temp = arr[i] + (arr[i+1] ? arr[i+1] : "");
            result.push(temp)
    }
    print(result);

    Output:

    ab, cd, ef, g


    Python:

    arr = ['a', 'b', 'c', 'd', 'e'];
    result = [];
    i=0
    length = len(arr)
    
    while i <= length-1:
        t=""
        try:
            t=arr[i+1]
        except IndexError:
            t=""
        temp = arr[i] + t
        result.append(temp)
        i += 2
        
    print(result)

    Output:

    ['ab', 'cd', 'ef', 'g']


  • String Pattern Programs in C

    In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C.

    C Pyramid String Pattern: 1

    Enter the string: SIMPLE2CODE
    Enter the no. of rows: 8
    S
    I M
    P L E
    2 C O D
    E S I M P
    L E 2 C O D
    E S I M P L E
    2 C O D E S I M

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       char str[20];
       int rows, a = 0;
    
       printf("Enter the string: ");
       scanf("%[^\n]", str);
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
       for (int i = 0; i <= rows - 1; i++)
       {
          for (int j = 0; j <= rows - i; j++)
             printf(" ");
    
          for (int k = 0; k <= i; k++)
          {
             printf("%2c", str[a++]);
    
             if (str[a] == '\0')
                a = 0;
          }
    
          printf("\n");	// for new line
       }
    }

    Mirrored half diamond string pattern in C: 2

    Enter the string: SIMPLE2CODE
    S
    SI
    SIM
    SIMP
    SIMPL
    SIMPLE
    SIMPLE2
    SIMPLE2C
    SIMPLE2CO
    SIMPLE2COD
    SIMPLE2CODE
    IMPLE2CODE
    MPLE2CODE
    PLE2CODE
    LE2CODE
    E2CODE
    2CODE
    CODE
    ODE
    DE
    E

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       char str[20];
       int strLength;
    
       printf("Enter the string: ");
       scanf("%[^\n]", str);
    
      	// count the no. of characters
       for (strLength = 0; str[strLength] != '\0'; strLength++);
    
      	// for first half
       for (int i = 0; i < strLength; i++)
       {
          for (int j = 0; j < strLength - i - 1; j++)
             printf(" ");	// space
    
          for (int j = 0; j <= i; j++)
             printf("%c", str[j]);
    
          printf("\n");	// for a new line
       }
    
      	// for second half
       for (int i = 1; i < strLength; i++)
       {
          for (int j = 0; j < i; j++)
             printf(" ");	// space
    
          for (int j = i; j < strLength; j++)
             printf("%c", str[j]);
    
          printf("\n");	// for a new line
       }
    }

    Half diamond string pattern in C: 3

    Enter the string: SIMPLE
    S
    SI
    SIM
    SIMP
    SIMPL
    SIMPLE
    IMPLE
    MPLE
    PLE
    LE
    E

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       char str[20];
       int strLength;
    
       printf("Enter the string: ");
       scanf("%[^\n]", str);
    
      	// count the no. of characters
       for (strLength = 0; str[strLength] != '\0'; strLength++);
    
      	// for first half
       for (int i = 0; i < strLength; i++)
       {
          for (int j = 0; j <= i; j++)
             printf("%c", str[j]);
    
          printf("\n");	// for a new line
       }
    
      	// for second half
       for (int i = 1; i < strLength; i++)
       {
          for (int j = i; j < strLength; j++)
             printf("%c", str[j]);
    
          printf("\n");	// for a new line
       }
    }

    Half diamond string pattern in C: 4

    Enter a string: PROGRAM
    P
    PR
    PRO
    PROG
    PROGR
    PROGRA
    PROGRAM
    PROGRA
    PROGR
    PROG
    PRO
    PR
    P

    Source Code:

    #include <stdio.h>
    #include <stdlib.h>
    
    void main()
    {
       char str[20];
       int len, place;
    
       printf("Enter a string: ");
       scanf("%[^\n]", str);
    
      	// find the length of the string
       for (len = 0; str[len] != '\0'; len++);
       len--;
    
       for (int i = 0; i < (2 *len + 1); i++)
       {
          if (i < len) place = i;
          else place = abs(2 *len - i);
    
          for (int j = 0; j <= place; j++)
             printf("%c", str[j]);
    
          printf("\n");
       }
    }

    Half Pyramid String Pattern in C: 5

    Enter a string: PROGRAM
    P
    PR
    PRO
    PROG
    PROGR
    PROGRA
    PROGRAM

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       char str[20];
    
       printf("Enter a string: ");
       scanf("%[^\n]", str);
    
       for (int i = 0; str[i] != '\0'; i++)
       {
          for (int j = 0; j <= i; j++)
             printf("%c", str[j]);
    
          printf("\n");	// new line
       }
    }

  • Java Program to Find pair of Integers in Array whose sum is given Number

    In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java. Before that, you may go through the following topic in java.


    Algorithm to check the pair of similar numbers present in an array whose sum is a given number

    Step 1: Start
    Step 2: Initiate new Array arr[]
    Step 3: Declare n, value
    Step 4: Take user input for:
    n: number of elements in an array
    arr: elements of an array
    value: for the number to be checked
    Step 5: Loop the entered array:
    for 0 to n-1
    for 0 to n
    if(arr[i] + arr[j] == value)
    print “arr[i] and arr[j]”
    Step 6: Stop


    How to Find all Pairs of Elements in an Array whose sum is equal to a given Number

    import java.util.Scanner;
    
    public class Main
    {
       public static void main(String[] args)
       {
          int[] arr = new int[10];
          int n, value;
          Scanner sc = new Scanner(System.in);
    
          System.out.print("How many elements: ");
          n = sc.nextInt();
    
          System.out.println("Enter the elements: ");
          for (int i = 0; i < n; i++)
             arr[i] = sc.nextInt();
    
           //user input for the value to be checked
          System.out.print("Enter the value to be checked: ");
          value = sc.nextInt();
    
           //Display the sum of pairs
          System.out.println("The pairs are:");
          for (int i = 0; i < (n - 1); i++)
             for (int j = (i + 1); j < n; j++)
                if (arr[i] + arr[j] == value)
                   System.out.println("Arr(" + arr[i] + ", " + arr[j] + ")");
    
       }
    }

    Output:

    How many elements: 5
    Enter the elements:
    1
    2
    5
    3
    4
    Enter the value to be checked: 6
    The pairs are:
    Arr(1, 5)
    Arr(2, 4)


  • Program to Print Diamond Alphabet Patterns in C

    In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a character pattern in C using for loop. So you may go through the following topic in C.

    Pattern 1: Diamond pattern in c using alphabets

    Enter the no. of rows: 8
    A
    ABC
    ABCDE
    ABCDEFG
    ABCDEFGHI
    ABCDEFGHIJK
    ABCDEFGHIJKLM
    ABCDEFGHIJKLMNO
    ABCDEFGHIJKLM
    ABCDEFGHIJK
    ABCDEFGHI
    ABCDEFG
    ABCDE
    ABC
    A

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       int rows, i, j, k;
    
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
      	// ASCII value
       int alphabet = 64;
    
       for (i = 1; i <= rows; i++)
       {
          for (j = 1; j <= rows - i; j++)
             printf(" ");
    
          for (k = 1; k <= i *2 - 1; k++)
             printf("%c", alphabet + k);
    
          printf("\n");
       }
    
       for (i = rows - 1; i > 0; i--)
       {
          for (j = 1; j <= rows - i; j++)
             printf(" ");
    
          for (k = 1; k <= i *2 - 1; k++)
             printf("%c", alphabet + k);
    
          printf("\n");
       }
    }

    Pattern 2: Diamond pattern in c using alphabets

    Enter the no. of rows: 8
    A
    A B
    A B C
    A B C D
    A B C D E
    A B C D E F
    A B C D E F G
    A B C D E F G H
    A B C D E F G
    A B C D E F
    A B C D E
    A B C D
    A B C
    A B
    A

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       int rows, i, j, k;
    
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
      	// ASCII value
       int alphabet = 65;
    
       for (i = 0; i <= rows - 1; i++)
       {
          for (j = rows - 1; j >= i; j--)
             printf(" ");
    
          for (k = 0; k <= i; k++)
             printf("%c ", alphabet + k);
    
          printf("\n");;
       }
    
       for (i = 0; i <= rows - 1; i++)
       {
          for (j = -1; j <= i; j++)
             printf(" ");
    
          for (k = 0; k <= rows - i - 2; k++)
             printf("%c ", alphabet + k);
    
          printf("\n");;
       }
    }

    Pattern 3: Diamond pattern in c using alphabets

    Enter the no. of rows: 8
    A
    BAB
    CBABC
    DCBABCD
    EDCBABCDE
    FEDCBABCDEF
    GFEDCBABCDEFG
    HGFEDCBABCDEFGH
    GFEDCBABCDEFG
    FEDCBABCDEF
    EDCBABCDE
    DCBABCD
    CBABC
    BAB
    A

    Source Code:

    #include <stdio.h>
    
    void main()
    {
       int rows, i, j, k, l;
    
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
       // ASCII value
       int alphabet = 64;
    
       for (i = 1; i <= rows; i++)
       {
          for (j = 1; j <= rows - i; j++)
             printf(" ");
    
          for (k = i; k >= 1; k--)
             printf("%c", alphabet + k);
    
          for (l = 2; l <= i; l++)
             printf("%c", alphabet + l);
    
          printf("\n");
       }
    
       for (i = rows - 1; i > 0; i--)
       {
          for (j = 1; j <= rows - i; j++)
             printf(" ");
    
          for (k = i; k >= 1; k--)
             printf("%c", alphabet + k);
    
          for (l = 2; l <= i; l++)
             printf("%c", alphabet + l);
    
          printf("\n");
       }
    }

  • Half Diamond Pattern in C using Alphabets

    In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a character pattern in C using for loop. So you may go through the following topic in C.

    Pattern 1: Half Diamond pattern in c using alphabets

    Enter the no. of rows: 5
    A
    A B
    A B C
    A B C D
    A B C D E
    A B C D
    A B C
    A B
    A

    Source Code:

    #include <stdio.h>
    
    void main()
    {
      int rows, i, j;
    
      printf("Enter the no. of rows: ");
      scanf("%d", &rows);
    
      // ASCII value of alphabet 'A'
      int alphabet = 65;
    
      for (i = 0; i <= rows - 1; i++)
      {
        for (j = 0; j <= i; j++)
          printf("%c ", (char)(alphabet + j));
    
        printf("\n");
      }
      for (i = rows - 1; i >= 0; i--)
      {
        for (j = 0; j <= i - 1; j++)
          printf("%c ", (char)(alphabet + j));
    
        printf("\n");
      }
    
      getch();
    }

    Pattern 2: Half Diamond pattern in c using alphabets

    Enter the no. of rows: 5
    E
    E D
    E D C
    E D C B
    E D C B A
    E D C B
    E D C
    E D
    E

    Source Code:

    #include <stdio.h>
    #include <math.h>
    
    void main()
    {
       int rows, i, j;
    
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
       for (i = rows; i >= -rows; i--)
       {
          for (j = rows-1; j >= abs(i); j--)
             printf("%c ", j + 65);
    
          printf("\n");
       }
    }

    Pattern 3: Half Diamond pattern in c using alphabets

    Enter the no. of rows: 5
    E
    E D
    E D C
    E D C B
    E D C B A
    E D C B
    E D C
    E D
    E

    Source Code:

    #include <stdio.h>
    #include <math.h>
    
    void main()
    {
       int rows, i, j;
    
       printf("Enter the no. of rows: ");
       scanf("%d", &rows);
    
       for (i = rows; i >= -rows; i--)
       {
          for (j = rows-1; j >= abs(i); j--)
             printf("%c ", j + 65);
    
          printf("\n");
       }
    }