Ask Question

Write a function int sum (int array[][4], int r) that returns the sum of all the values in the two dimensionalinteger array called array[][4]of rows r.

+3
Answers (1)
  1. 11 June, 22:26
    0
    Arrays in C#.

    Explanation:

    In C#, arrays are of two types.

    single dimensional multi dimensional

    Multi dimensional arrays are 2d arrays where it contains set of rows and columns.

    The syntax for creating 2d arrays is:

    int[,] numbers = new int[3,2]{

    {4, 20},

    {13, 6},

    {8, 11}

    };

    where, 3 is number of rows and 2 is number of columns.

    If we want to access values, we can do it using indexes. First index is for row and second index is for column.

    Both indexes starts from zero.

    numbers[1,1] / / output is 6

    Program to calculate the sum of all values in 2d array:

    using System;

    namespace Arrays

    {

    public class Program

    {

    public static void Main (string[] args)

    {

    int[,] numbers = new int[3,2]{

    {4, 20},

    {13, 6},

    {8, 11}

    };

    int total = 0;

    foreach (var k in numbers)

    total + = k;

    Console. WriteLine ("Total = {0}", total);

    }

    }

    }

    Explanation of above code:

    Firstly, I have created a 2d array. We can use foreach loop, to loop through all the elements of an array until it reaches to an end. We don't have to mention the length of an array when foreach is used. It automatically comes out of the loop once it founds no other elements left.

    I created a variable named total to store the sum of all elements of an array. Foreach loop pulls out each element one by one and adds it to total variable. I used, + = operator to perform sum operation.

    Finally, I printed the total variable which holds the sum of all elements of an array.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function int sum (int array[][4], int r) that returns the sum of all the values in the two dimensionalinteger array called ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers