1. Create a 2D array with the values shown in the following figure 4 38 2. Write
ID: 3745599 • Letter: 1
Question
1. Create a 2D array with the values shown in the following figure 4 38 2. Write the method searchNumber to search a number contained only in the diagonals of the 2D array using a for, do-while, and while loop. The method should accept two parameters of type int. The first one is the number to be searched, and the second one indicates the kind of loop to be used. If the second parameter is 1 then the search should be done using a for loop, 2 using a do-while loop, and 3 using a while loop. The method should print if the number was found.Explanation / Answer
Hello , I did this using c# language.
Hope you dont have any objection on this , :)
Following is working code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerchDigonalElement
{
class Program
{
public int[,] matrix = new int[3, 3] { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } };
static void Main(string[] args)
{
Program p = new Program();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(p.matrix[i,j]+" ");
}
Console.WriteLine();
}
Console.WriteLine ();
Console.WriteLine("Please enter number to serch");
int serch = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Please select loop type");
Console.WriteLine("For Loop : 1");
Console.WriteLine("While Loop : 2");
Console.WriteLine("Do-While Loop : 3 ");
int choice = Convert.ToInt32(Console.ReadLine());
p.SerchNumber(serch, choice);
Console.ReadLine();
}
public void SerchNumber(int number, int loop)
{
if (loop == 1)
{
for (int i = 0; i < 3; i++) // iterate through rows
{
for (int j = 0; j < 3; j++) // iterate through columns
{
if (i == j) // checked for diagonal position ie row and column position should match
{
if (matrix[i, j] == number) {
Console.WriteLine(number + " is present at [" + (i+1) + "," + (j+1) + "] position");
}
}
}
}
}
if (loop == 2)
{
int row = 0;
int column = 0;
while (row < 3) // iterate through rows
{
while (column < 3) // iterate through columns
{
if (row == column) {
if (matrix[row, column] == number)
{
Console.WriteLine(number + " is present at [" + (row + 1) + "," + (column + 1) + "] position");
}
}
column++;
}
column = 0;
row++;
}
}
if (loop == 3)
{
int row = 0;
int column = 0;
do{
do {
if (row == column) // check diagonal position.
{
if (matrix[row, column] == number)
{
Console.WriteLine(number + " is present at [" + (row + 1) + "," + (column + 1) + "] position");
}
}
column++;
} while (column < 3);
column = 0;
row++;
}while(row <3);
}
}
}
}
Please like my answer if its correct.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.