C# Exercise 4

Mannan Ul Haq
0

Objective:

  • 1D Array
  • 2D Array

Activity 1:

Write a program that declare an int array of size N inside the main function. Write the following functions for this array:

  1. InitializeArray(int[] arr) This function takes an int array parameter. The function will be used to populate the array by taking input from user.
  2. void PrintArray(int[] arr) Print the array data in an efficient manner that each element is separated with appropriate space. Note: Use this function to print all results of below functions.
  3. int Find2Largest(int[] arr) The function returns the second largest element of an array.
  4. void FindMinMax(int[] arr, ref int min, ref int max) This function should store the min and max value in the relevant variables which are passed by reference to the function.
  5. void SearchData(int[] arr, int key, ref int found). This function should search the key using linear search technique and return the index. If key isn't available in the array, then return -1.
  6. void SortData(int[] arr, char choice)  This function also takes choice variable as parameters and sort the data according to users choice, i.e., ascending or descending. You can use any sorting technique to sort the data in ascending order.
  7. void SortEvenOdd(int[] arr) function to separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers.
  8. void CheckFrequency(int[] arr)  - the function will take an array as input and print the frequency of each element of an array

Solution:

using System;

class Program
{
    const int SIZE = 6;

    static void InitializeArray(int[] arr)
    {
        Console.WriteLine("Enter values of Set: ");
        for (int i = 0; i < SIZE; i++)
        {
            arr[i] = Convert.ToInt32(Console.ReadLine());
        }
    }

    static void PrintArray(int[] arr)
    {
        Console.Write("The Elements in Set are: ");
        for (int n = 0; n < SIZE; n++)
        {
            Console.Write(arr[n]);
            if (n < (SIZE - 1))
                Console.Write(" ");
        }
        Console.WriteLine();
    }

    static int Find2Largest(int[] arr)
    {
        int[] arr2 = new int[SIZE];
        int max1 = 0, max2 = 0;
        for (int i = 0; i < SIZE; i++)
        {
            arr2[i] = arr[i];
            if (arr2[i] > max1)
                max1 = arr2[i];
        }
        for (int i = 0; i < SIZE; i++)
        {
            if (arr2[i] == max1)
                arr2[i] = 0;
            if (arr2[i] > max2)
                max2 = arr2[i];
        }
        return max2;
    }

    static void FindMinMax(int[] arr, out int min, out int max)
    {
        min = arr[0];
        max = arr[0];
        for (int i = 1; i < SIZE; i++)
        {
            if (arr[i] < min)
                min = arr[i];
            if (arr[i] > max)
                max = arr[i];
        }
    }

    static void SearchData(int[] arr, int key, out int found)
    {
        found = -1;
        for (int i = 0; i < SIZE; i++)
        {
            if (arr[i] == key)
                found = key;
        }
    }

    static void SortData(int[] arr, char choice)
    {
        Array.Sort(arr);
        if (choice == 'd')
            Array.Reverse(arr);

        Console.Write(choice == 'a' ? "Elements sorted in the Ascending Order are: " : "Elements sorted in the Descending Order are: ");
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);
            if (i < (arr.Length - 1))
                Console.Write(" ");
        }
        Console.WriteLine();
    }

    static void SortEvenOdd(int[] arr)
    {
        Console.Write("Even Elements of Array: ");
        foreach (int i in arr)
        {
            if (i % 2 == 0)
                Console.Write(i + " ");
        }
        Console.WriteLine();

        Console.Write("Odd Elements of Array: ");
        foreach (int i in arr)
        {
            if (i % 2 != 0)
                Console.Write(i + " ");
        }
        Console.WriteLine();
    }

    static void CheckFrequency(int[] arr)
    {
        Console.WriteLine("Frequency of all Elements in the Array: ");
        for (int i = 0; i < SIZE; i++)
        {
            int count = 0;
            for (int j = 0; j < SIZE; j++)
            {
                if (arr[i] == arr[j])
                    count++;
            }
            Console.WriteLine(arr[i] + " occurs " + count + " time(s)");
        }
    }

    static void Main()
    {
        int[] arr = new int[SIZE];
        int key, found, max, min;
        char choice;

        InitializeArray(arr);
        Console.WriteLine();
        PrintArray(arr);
        Console.WriteLine();
        Console.WriteLine("The Second Largest in the Array is: " + Find2Largest(arr));
        Console.WriteLine();
        FindMinMax(arr, out min, out max);
        Console.WriteLine("The Max. value in the Array is: " + max);
        Console.WriteLine("The Min. value in the Array is: " + min);
        Console.WriteLine();
        Console.WriteLine("Enter value to find: ");
        key = Convert.ToInt32(Console.ReadLine());
        SearchData(arr, key, out found);
        Console.WriteLine(found == -1 ? "Value not found in the Array." : "Value found in the Array.");
        Console.WriteLine();
        do
        {
            Console.WriteLine("Type 'a' for Ascending Order or 'd' for Descending Order.");
            choice = Convert.ToChar(Console.ReadLine());
        } while (choice != 'a' && choice != 'd');
        SortData(arr, choice);
        Console.WriteLine();
        SortEvenOdd(arr);
        Console.WriteLine();
        CheckFrequency(arr);
        Console.WriteLine();
    }
}


Activity 2:

Write a C# program to read a sentence from console into a character array. Now separate each word and find the word with minimum length and display it on screen. You also have to make integer array to store length of each word in sentence. Your code should be generic. 
*Note: Your sentence always ends with full stop.

Solution: 

using System;

class Program
{
    const int SIZE = 100;

    static void Min(char[] arr)
    {
        int[] lengths = new int[SIZE];
        int lengthIndex = 0;
        int minLength = SIZE;
        int currentLength = 0;

        for (int i = 0; i < arr.Length && arr[i] != '\0'; i++)
        {
            if (arr[i] != ' ' && arr[i] != '.')
            {
                currentLength++;
            }
            else if (currentLength > 0)
            {
                Console.Write(currentLength + " ");
                lengths[lengthIndex] = currentLength;
                lengthIndex++;

                if ( currentLength < minLength )
                {
                    minLength = currentLength;
                }

                currentLength = 0;
            }
        }

        Console.WriteLine("\nMin: " + minLength);
    }

    static void Main()
    {
        char[] arr = new char[SIZE];
        Console.WriteLine("Enter a Sentence: ");
        string input = Console.ReadLine();
        input.CopyTo(0, arr, 0, input.Length);
        Min(arr);
    }
}


Activity 3:

Write a function in C# called void Trace(int[,] data) that calculates and returns the trace of a square matrix of size 3x3. The trace of a square matrix is the sum of values present in its diagonal.


Solution:

using System;

class Program
{
    const int rows = 3, column = 3;

    static void Trace(int[,] data)
    {
        int trace = 0;
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < column; j++)
            {
                if (i == j)
                    trace += data[i, j];
            }
        }

        Console.WriteLine("Trace = " + trace);
    }

    static void Main()
    {
        int[,] data = new int[rows, column];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < column; j++)
            {
                Console.Write($"Enter ({i}) and ({j}) value: ");
                data[i, j] = Convert.ToInt32(Console.ReadLine());
            }
        }
        Console.WriteLine("Given Matrix is: ");
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < column; j++)
            {
                Console.Write(data[i, j] + " ");
            }
            Console.WriteLine();
        }
        Trace(data);
    }
}



Activity 4:

Write a C# function to compare two do the following tasks:

  1. Compare two char arrays
  2. Copy contents of 1 array into other and then compare both 

Solution:

using System;

class Program
{
    const int SIZE = 30;

    static void Compare(char[] arr1, char[] arr2)
    {
        Console.WriteLine("First String: " + new string(arr1));
        Console.WriteLine("Second String: " + new string(arr2));
        if (new string(arr1) == new string(arr2))
        {
            Console.WriteLine("Both Strings are Same.\n");
        }
        else
        {
            Console.WriteLine("Both Strings are not Same.\n");
        }
    }

    static void Main()
    {
        char[] arr1 = new char[SIZE];
        Console.WriteLine("Enter 1st Sentence: ");
        string input1 = Console.ReadLine();
        input1.CopyTo(0, arr1, 0, input1.Length);

        char[] arr2 = new char[SIZE];
        Console.WriteLine("Enter 2nd Sentence: ");
        string input2 = Console.ReadLine();
        input2.CopyTo(0, arr2, 0, input2.Length);

        Compare(arr1, arr2);

        input1.CopyTo(0, arr2, 0, input1.Length);
        Console.WriteLine("After Copying contents of 1st array into other.");
        Compare(arr1, arr2);
    }
}



Activity 5:

Ask user for an input, store that input in a char array. Count small letters, capital letters, its and special charters in that input.


Solution:

using System;

class Program
{
    const int SIZE = 30;

    static void Count(char[] arr)
    {
        int upper = 0, lower = 0, number = 0, special = 0;
        for (int i = 0; i < arr.Length && arr[i] != '\0'; i++)
        {
            if (arr[i] >= 'A' && arr[i] <= 'Z')
                upper++;
            else if (arr[i] >= 'a' && arr[i] <= 'z')
                lower++;
            else if (arr[i] >= '0' && arr[i] <= '9')
                number++;
            else
                special++;
        }
        Console.WriteLine("Capital Letters: " + upper);
        Console.WriteLine("Small Letters : " + lower);
        Console.WriteLine("Numbers : " + number);
        Console.WriteLine("Special Characters : " + special);
    }

    static void Main()
    {
        char[] arr = new char[SIZE];
        Console.WriteLine("Enter the String: ");
        string input = Console.ReadLine();
        input.CopyTo(0, arr, 0, input.Length);
        Count(arr);
    }
}

 


Activity 6:

  1. Write a function static int[] InputArray() that asks user to enter size of required array allocates the memory, takes input in array.
  2. Write a program static void OutputArray(int[] array) that takes an integer array and prints its data.
  3. Implement a function static int[] Intersection(int[] array1, int[] array2) that finds intersection (common elements) of two sets (stored using arrays).

Solution:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("For Array 1: ");
        int[] array1 = InputArray();
        Console.WriteLine("For Array 2: ");
        int[] array2 = InputArray();

        Console.WriteLine("Array 1: ");
        OutputArray(array1);
        Console.WriteLine("Array 2: ");
        OutputArray(array2);

        int[] intersection = Intersection(array1, array2);

        Console.WriteLine("Intersection: ");
        OutputArray(intersection);
    }

    static int[] InputArray()
    {
        Console.WriteLine("Enter the Size of the Array:");
        int size = Convert.ToInt32(Console.ReadLine());

        int[] array = new int[size];
        Console.WriteLine("Enter Values for the Array: ");
        for (int i = 0; i < size; i++)
        {
            array[i] = Convert.ToInt32(Console.ReadLine());
        }

        return array;
    }

    static void OutputArray(int[] array)
    {
        Console.Write(" { ");
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write(array[i]);
            if (i < array.Length - 1)
            {
                Console.Write(", ");
            }
        }
        Console.WriteLine(" }");
    }

    static int[] Intersection(int[] array1, int[] array2)
    {
        int size3 = Math.Min(array1.Length, array2.Length);
        int[] array = new int[size3];
        int k = 0;

        for (int i = 0; i < array1.Length; i++)
        {
            for (int j = 0; j < array2.Length; j++)
            {
                if (array1[i] == array2[j])
                {
                    array[k] = array1[i];
                    k++;
                    if (k >= size3)
                        return array;
                }
            }
        }

        Array.Resize(ref array, k);
        return array;
    }
}



Activity 7: 

a) Write a function static int[,] AllocateMemory(ref int rows, ref int columns) that takes size of matrix (rows and columns) from user, allocates memory for the matrix.
b) Write a function static void InputMatrix(int[,] matrix, int rows, int columns) which takes input the values in matrix from user(console).
c) Write a function static void DisplayMatrix(int[,] matrix, int rows, int columns) that displays the matrix in proper format.
d) Write a function called MaxRow that takes a 2D array and its dimensions. It should return the largest element in each row of the array. Since there is more than one row in 2D array, you have to return a dynamic array that contains largest of each row. 
For example, if the Sample Matrix is
1 4 8
9 1 6
5 7 2
Your function will return array containing maximum elements of all the columns i.e.
8, 9, 7
e) (Concatinate tables ) It takes two 2D arrays and returns a new 2D array that is concation on y or x axis.
static void Concat(int[,] A, int[,] B, int row1, int column1, int row2, int column2) //axis 0 mean x axis 1 means Y axis.

Array 1
1,2,3
4,4,5
3,4,6

Array 2
5,8,9
4,9,4
4,6,0

If axis = 0 (x-axis)
Output 
1,2,3,5,8,9
4,4,5,4,9,4
3,4,6,4,6,0

If axis = 1 (y-axis)
Output
1,2,3
4,4,5
3,4,6
5,8,9
4,9,4
4,6,0

Solution:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("For Array A:");
        int row1 = 0, column1 = 0;
        int[,] A = AllocateMemory(ref row1, ref column1);
        InputMatrix(A, row1, column1);
        DisplayMatrix(A, row1, column1);

        Console.WriteLine("The Maximum Values in each Row are: ");
        int[] maxRowArray = MaxRow(A, row1, column1);
        foreach (var num in maxRowArray)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();

        Console.WriteLine("For Array B:");
        int row2 = 0, column2 = 0;
        int[,] B = AllocateMemory(ref row2, ref column2);
        InputMatrix(B, row2, column2);
        DisplayMatrix(B, row2, column2);

        Console.WriteLine("Concatenate Table: ");
        Concat(A, B, row1, column1, row2, column2);
    }

    static int[,] AllocateMemory(ref int rows, ref int columns)
    {
        Console.WriteLine("Enter the Number of Rows: ");
        rows = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the Number of Columns: ");
        columns = Convert.ToInt32(Console.ReadLine());

        return new int[rows, columns];
    }

    static void InputMatrix(int[,] matrix, int rows, int columns)
    {
        Console.WriteLine("Enter Values for Matrix: ");
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Console.Write($"[{i}][{j}] = ");
                matrix[i, j] = Convert.ToInt32(Console.ReadLine());
            }
        }
    }

    static void DisplayMatrix(int[,] matrix, int rows, int columns)
    {
        Console.WriteLine("Given Matrix: ");
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Console.Write(matrix[i, j] + "  ");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }

    static int[] MaxRow(int[,] matrix, int rows, int columns)
    {
        int[] maxValues = new int[rows];
        for (int i = 0; i < rows; i++)
        {
            int maxVal = matrix[i, 0];
            for (int j = 1; j < columns; j++)
            {
                if (matrix[i, j] > maxVal)
                {
                    maxVal = matrix[i, j];
                }
            }
            maxValues[i] = maxVal;
        }
        return maxValues;
    }

    static void Concat(int[,] A, int[,] B, int row1, int column1, int row2, int column2)
    {
        Console.WriteLine("Press 0: For x-axis");
        Console.WriteLine("Press 1: For y-axis");
        int choice = Convert.ToInt32(Console.ReadLine());

        if (choice == 0 && row1 == row2)
        {
            for (int i = 0; i < row1; i++)
            {
                for (int j = 0; j < column1; j++)
                {
                    Console.Write(A[i, j] + "  ");
                }
                for (int j = 0; j < column2; j++)
                {
                    Console.Write(B[i, j] + "  ");
                }
                Console.WriteLine();
            }
        }
        else if (choice == 1 && column1 == column2)
        {
            for (int i = 0; i < row1; i++)
            {
                for (int j = 0; j < column1; j++)
                {
                    Console.Write(A[i, j] + "  ");
                }
                Console.WriteLine();
            }
            for (int i = 0; i < row2; i++)
            {
                for (int j = 0; j < column2; j++)
                {
                    Console.Write(B[i, j] + "  ");
                }
                Console.WriteLine();
            }
        }
        else
        {
            Console.WriteLine("Invalid choice or matrices dimensions are not compatible for concatenation.");
        }
    }
}

 

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !