Machine Problem 5.9
Write a program using two-‐dimensional arrays that computes the sum of data in rows and sum of data in columns of the 3x3 (three by three) array variable n[3[3].
Sample input/output dialogue:
5 9 8 = 22
3 8 2 = 13
4 3 9 = 16
-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐
12 20 19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace C_SHARP
{
class Program
{
static int[,] getNumbers() {
int[,] numbers = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Enter value [{0},{1}]: ", i, j);
numbers[i, j] = int.Parse(Console.ReadLine());
}
}
return numbers;
}
static int[,] calculateSums(int[,] numbers)
{
int[,] sums = new int[3, 2];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
sums[i, 0] += numbers[i, j];
sums[i, 1] += numbers[j, i];
}
}
return sums;
}
static void printResult(int[,] numbers, int[,] sums)
{
Console.WriteLine();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("{0} ", numbers[i, j]);
}
Console.WriteLine(" = {0}", sums[i, 0]);
}
Console.WriteLine("---------------");
for (int i = 0; i < 3; i++)
{
Console.Write("{0} ", sums[i, 1]);
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[,] numbers = getNumbers();
int[,] sums = calculateSums(numbers);
printResult(numbers,sums);
Console.ReadLine();
}
}
}
Comments
Leave a comment