# Trending December 2023 # Golang Program To Calculate The Sum Of Columns Of Matrix Elements # Suggested January 2024 # Top 14 Popular

You are reading the article Golang Program To Calculate The Sum Of Columns Of Matrix Elements updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Golang Program To Calculate The Sum Of Columns Of Matrix Elements

A matrix is a collection of numbers arranged in rows and columns, a two-dimensional array, each of the values of this matrix is known as an element. Here we will use three methods to find the sum of column elements and compare each method for the same using go programming.

Here is an example of a matrix and the sum value of it’s columns −

The given matrix is −

0 1 2 4 5 6 8 9 7

Sum of elements in column 1 is 12

Sum of elements in column 2 is 15

Sum of elements in column 3 is 15

Algorithm

Step 1 − Import the fmt package.

Step 2 − Now we need to start the main() function.

Step 3 − Then we are creating a matrix naming matrix and assign elements to it.

Step 4 − Print the matrix on the screen using fmt.Println() function.

Step 5 − Initialize a new variable called sum of type int to hold the resultant sum.

Step 6 − To find sum of the column elements use the for loop to iterate over the matrix.

Step 7 − Using the first for loop is used to get the column of the matrix while the second for loop gives us the column of the matrix.

Step 8 − Once the loop gets over the matrix elements update the sum variable by adding values to it.

Step 9 − Print the sum of the matrix on the screen.

Example 1

In the following example, we will use a for loop to iterate over the matrix and find the sum of its elements and print it on the screen.

package main import "fmt" func main() { matrix := [][]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix); i++ { sum := 0 for j := 0; j < len(matrix); j++ { sum += matrix[j][i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 0 1 2 4 5 6 8 9 7 Sum of elements in column 1 is 12 Sum of elements in column 2 is 15 Sum of elements in column 3 is 15 Example 2

In this example we will find the sum of the columns of matrix elements using range function.

package main import "fmt" func main() { matrix := [][]int{ {10, 1, 2}, {4, 50, 6}, {8, 9, 7}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix); i++ { sum := 0 for _, row := range matrix { sum += row[i] } fmt.Printf("Sum of elements in column %d is %dn", i+1, sum) } } Output The given matrix is: 10 1 2 4 50 6 8 9 7 Sum of elements in column 1 is 22 Sum of elements in column 2 is 60 Sum of elements in column 3 is 15 Example 3

In this example we will use the recursion approach to find the sum of columns of matrix elements.

package main import "fmt" func colSum(matrix [][]int, col int) int { if col == len(matrix) { return 0 } sum := 0 for i := range matrix { sum += matrix[i][col] } return sum } func main() { matrix := [][]int{ {20, 1, 22}, {43, 5, 16}, {86, 91, 10}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrix[i][j], "t") } fmt.Println() } fmt.Println() for i := 0; i < len(matrix); i++ { fmt.Printf("Sum of elements in column %d is %dn", i+1, colSum(matrix, i)) } } Output The given matrix is: 20 1 22 43 5 16 86 91 10 Sum of elements in column 1 is 149 Sum of elements in column 2 is 97 Sum of elements in column 3 is 48 Conclusion

We have successfully compiled and executed a go language program to calculate the sum of columns of matrix elements along with examples. In the first and second example we have used for loop and range functions respectively in the main() section of the program while in the last example we have used a separate function to implement the logic.

You're reading Golang Program To Calculate The Sum Of Columns Of Matrix Elements

## Swift Program To Calculate The Sum Of Rows Of Matrix Elements

A matrix is an arrangement of numbers in rows and columns. Matrix can be of various type like square matrix, horizontal matrix, vertical matrix etc.

In this article, we will learn how to write a swift program to calculate the sum of rows of matrix elements. Here we are using the following methods to find the sum of the rows elements −

Using nested for-in loop

Using in-built function

Method 1: Using nested for-in loop

Here we use nested for-in loop to find the sum of rows of matrix elements.

Algorithm

Step 1 − Create a function.

Step 2 − Create a variable named sum to store the sum. The initial value of sum = 0.

Step 3 − Find the number of rows and columns.

Step 4 − Run nested for-in loop to iterate through each row and column.

Step 5 − In this nested loop, add elements row-wise and store the result into sum variable.

Step 6 − After each row reset the value of sum = 0 for the sum of next row elements.

Step 7 − Create a matrix and pass it in the function.

Step 8 − Print the output.

Example

Following Swift program to calculate the sum of rows of matrix elements.

import Foundation import Glibc func rowElementsSum(matrix: [[Int]]) { var sum = 0 let noRow = matrix.count let noColumn = matrix.count for R in 0..<noRow { for C in 0..<noColumn { sum += matrix[R][C] } print("Sum of row (R) = (sum)") sum = 0 } } let M = [[1, 2, 2], [1, 1, 6], [7, 8, 3], [2, 4, 2]] print("Matrix is:") for x in 0..<M.count { for y in 0..<M.count { print(M[x][y], terminator:" ") } print("n") } rowElementsSum(matrix: M) Output Matrix is: 1 2 2 1 1 6 7 8 3 2 4 2 Sum of row 0 = 5 Sum of row 1 = 8 Sum of row 2 = 18 Sum of row 3 = 8

Here in the above code, we have a 4×3 matrix and then pass it in the function named rowElementsSum() to find the sum of the row’s elements of the matrix. In this function, we use nested for loop to iterate through each element of the input matrix and then add it to the corresponding row sum. After finishing the nested for loop this function return the row sums that is row 0 = 5, row 1 = 8, row 2 = 18 and row 3 = 8(according to the input matrix).

Method 2: Using in-built function

To find the sum of the rows of the given matrix elements we uses reduce(_:_:) function. This function returns a result by combining the elements of the array or any sequence using the given closure.

Syntax func reduce(_initial: Value, _next: Value)

Here, initial represent the value to use as an initial accumulating value. It passes to the next for the first time the closure is executed. And next represent a closure that combines an accumulating value and an element of the array into a new accumulating value which if further used for next call of the next closure or return to the caller.

Algorithm

Step 1 − Create a matrix.

Step 2 − Print the matrix.

Step 3 − Create an 1-D array to store the sum of the rows.

Step 4 − Run a for loop to iterate through each row.

Step 5 − Find the sum of the rows elements using reduce() function.

let sum = row.reduce(0, +)

Step 6 − Now store the sum of each row in the array using append() function.

RowsSum.append(sum)

Step 7 − Print the resultant array.

Example

Following Swift program to calculate the sum of rows of matrix elements.

import Foundation import Glibc let matrix = [[1, 2, 3, 4, 6], [4, 5, 6, 1, 1], [7, 8, 9, 5, 5]] print("Matrix is:") for x in 0..<matrix.count { for y in 0..<matrix.count { print(matrix[x][y], terminator:" ") } print("n") } var RowsSum = [Int]() for row in matrix { let sum = row.reduce(0, +) RowsSum.append(sum) } print("So the sums of the individual rows are:", RowsSum) Output Matrix is: 1 2 3 4 6 4 5 6 1 1 7 8 9 5 5 So the sums of the individual rows are: [16, 17, 34]

Here in the above code, we have a 5×3 matrix. Then create an empty 1-D array to store the sum of each row. The using for loop we iterate through each row of the given matrix and adds the elements of the row using reduce() function. This sum is then store in the RowsSum array. So according to the given matrix the final result is [16, 17, 34]. Here 16 is the sum of row 0 elements(1+2+3+4+6), 17 is the sum of row 1 elements(4+5+6+1+1) and so on.

Conclusion

So this is how we can calculate the sum of rows of matrix elements. Here using the above methods we can calculate the sum of any type of matrix like 6×6, 9×9, 4×3, 6×7, etc.

## Swift Program To Calculate The Sum Of All Odd Numbers Up To N

This tutorial will discuss how to write a Swift program to find the sum of all odd numbers upto N.

A number that is not divisible by 2 or we can say that when an odd number is divided by 2 then it leaves some remainder such type of number is known as an odd number. For example, when 2 divides by 2 leave remainder 0 whereas 3 divides by 2 leaves remainder 1. So it means 2 is an even number and 3 is an odd number.

List of odd numbers is −

1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, ……

We can calculate the sum of all the odd numbers upto N by adding all the odd numbers present in the given list.

Below is a demonstration of the same −

Input

Suppose our given input is −

Number - 10

Output

The desired output would be

1+3+5+7+9 = 25 Sum of odd numbers are 25 Algorithm

Following is the algorithm −

Step 1 − Create a function.

Step 2 − Declare a variable to store the sum of the odd numbers upto N – sum = 0.

Step 3 − Run a for loop from 0 to N.

Step 4 − Check if the given number is odd number or not.

if j % 2 != 0

Here using % operator, we find the remainder. If the remainder is not equal to 0 then the number is an odd number.

Step 5 − Calculate the sum of odd numbers.

sum += j

Step 6 − Return the sum.

Step 7 − Create a variable named “num” to store the value of N. Here the value of num can be user-defined or pre-defined.

Step 8 − Call the function and pass “num” as a argument in it.

Step 9 − Print the output

Example 1

The following program shows how to find the sum of all odd numbers upto N.

import

Glibc

var

sum

=

0

print

(

“Odd numbers from 0 to (a):”

)

for

j

in

1.

.

.

a

{

if

j

%

2

!=

0

{

sum

+=

j

print

(

j

,

terminator

:

” ,”

)

}

}

return

sum

}

var

num

=

16

print

(

“nSum of all the odd numbers from 0 to (num): “

,

sumOddNum

(

a

:

num

)

)

Output Odd numbers from 0 to 16: 1 ,3 ,5 ,7 ,9 ,11 ,13 ,15 , Sum of all the odd numbers from 0 to 16: 64

In the above code, we create a function named sumOddNum() function to find the sum of all the odd numbers upto N. This function takes one argument. So the working of the sumOddNum() function is −

sumOddNum

(

16

)

sum

=

0

1st

Iteration

:

for

j

in

0.

..

16

if

0

%

2

!=

0

// false

sum

=

sum

+

j

print

(

j

,

terminator

:

" ,”) sum = 0 2nd Iteration: for j in 0...16 if 1 % 2 != 0 sum = 0 + 1 = 1 print(j, terminator: "

,”)

// print 1

sum

=

1

3rd

Iteration

:

for

j

in

0.

..

16

if

2

%

2

!=

0

// false

sum

=

sum

+

j

print

(

j

,

terminator

:

" ,”) sum = 1 4th Iteration: for j in 0...16 if 3 % 2 != 0 sum = 1 + 3 = 4 print(j, terminator: "

,”)

// print 3

sum

=

4

...

so on till

16.

Now we display the sum of all the odd numbers present between 0 to 16 is 64(1+3+5+7+9+11+13+15 = 64).

Example 2

The following program shows how to find the sum of all odd numbers upto N.

import

Foundation

import

Glibc

var

sum

=

0

print

(

"Odd numbers from 0 to (a):"

)

for

j

in

1.

.

.

a

{

if

j

%

2

!=

0

{

sum

+=

j

print

(

j

,

terminator

:

" ,"

)

}

}

return

sum

}

print

(

)

var

num

=

Int

(

(

)

!

)

!

print

(

"nSum of all the odd numbers from 0 to (num): "

,

sumOddNum

(

a

:

num

)

)

STDIN Input Please enter the number(N): 10 Output Odd numbers from 0 to 10: 1 ,3 ,5 ,7 ,9 , Sum of all the odd numbers from 0 to 10: 25

Here the working of the above code is same as the Example 1 the only difference is here we take the value of “num” from the user using readLine() function and convert the input value into integer type using Int() function. So here user enter number 10 so the sum of all the odd numbers present in between 0 to 10 is 25 (1+3+5+7+9= 25)

## Java Program To Calculate Length Of Chord Of The Circle

A circle is a round shape two-dimensional diagram which has no corners. Every circle has an origin point and every point on the circle maintains equal distance from the origin. The distance between the origin and a point in a circle is known as Radius of the circle. And similarly, if we draw a line from one edge to another edge of the circle and the origin is held in the middle of it, that line is known as diameter of the circle. Basically, the diameter is double of the length of the radius.

Chord of the circle refers to a line touching from one endpoint of circle to another end point of circle. Or simply we can say a chord refers to the line whose endpoints lie on the circle. A chord divides the circle into two parts.

As per the problem statement we have to find the length of the chord when the radius of circle and angle subtended at centre by the chord is given.

Formula to find length of chord −

Length = 2 * r * sin(a/2)

Where, ‘r’ refers to the radius of the circle and ‘a’ refers to the angle subtended at centre by the chord.

So, let’s explore.

To show you some instances − Instance-1 Let say radius (r) of circle is 3. And angle (a) subtended at centre by the chord is 60 Then by using the formula, length of the chord is 5.19. Instance-2 Let say radius (r) of circle is 4. And angle (a) subtended at centre by the chord is 50 Then by using the formula, length of the chord is 6.12. Instance-3 Let say radius (r) of circle is 4. And angle (a) subtended at centre by the chord is 40. Then by using the formula, length of the chord is 5.1. Algorithm

Step-1 − Get the radius of circle and angle at the centre subtended by the chord either by static input or by user input.

Step-2 − Find the length of the chord by using the formula.

Step-3 − Print the result.

Multiple Approaches

We have provided the solution in different approaches.

By Using Static Input Values.

By Using User Input Values.

Let’s see the program along with its output one by one.

Approach-1: By Using Static Input Value

In this approach, we initialize the radius and angle value in the program. Then by using the algorithm we can find the length of the chord.

Example public class Main { public static void main(String[] args) { double r = 4; double a = 40; double length = 2 * r * Math.sin(a * (3.14 / 180)); System.out.println("Length of Chord: "+length); } } Output Length of Chord: 5.140131589369607 Approach-2: By Using User Defined Method with Static Input Value.

In this approach, we take user input of radius and angle value in the program. Then call a user defined method by passing these values as parameters and inside the method by using the algorithm we can find the length of the chord.

Example public class Main { public static void main(String[] args) { double r = 4; double a = 40; length_of_chord(r, a); } static void length_of_chord(double r, double a) { double length = 2 * r * Math.sin(a * (3.14 / 180)); System.out.println("Length of Chord: "+length); } } Output Length of Chord: 5.140131589369607

In this article, we explored how to find the length of the chord when the radius ofcircle and angle subtended by chord to centre is given by using different approaches in Java.

## Golang Program To Compare Elements In Two Slices

In this tutorial, we will learn how to compare elements in two slices. In slices a simple equality comparison is not possible so the slices are compared with their lengths and the elements present in the loop. The output will be printed in the form of Boolean value on the console with the help of fmt.Println() function. Let’s see how to execute this with the help of an example.

Method 1: Using a user-defined function

In this method, we will compare elements in two slices using an external function and, in that function, we will set some conditions, if the slices satisfy those conditions, they will be considered equal else they won’t be considered equal. Let’s have a look to get a better understanding.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a main function, in it create two slices of type string and call a function named slice_equality with two slices as arguments.

Step 3 − Create a function slice_equality and in that function check if the length of the first slice is not equal to the second slice return false.

Step 4 − In the next case run a for loop till the range of str1 and check if the elements of str2 are equal to str1, if they are not equal return false.

Step 5 − After checking all the conditions set in the algorithm, if not even once false is returned, return true to the function.

Step 6 − Print the Boolean value using fmt.Println() function where ln refers to the next line here.

Example

Golang program to compare elements in two slices using custom function

package main import "fmt" func slice_equality(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i, str := range str1 { if str != str2[i] { return false } } return true } func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The slices are equal or not before adding any element:") fmt.Println(slice_equality(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The slices are equal or not after adding another element:") fmt.Println(slice_equality(str1, str2)) } Output The slices are equal or not before adding any element: true The slices are equal or not after adding another element: false Method 2: Using built-in function

In this method, we will use reflect.DeepEqual() function to compare two slices recursively. Built-in functions ease our work and shorten the code. The output here will be printed using fmt.Println() function. Let’s have a look and inculcate how to solve this problem.

Syntax reflect.DeepEqual()

This function compares two values recursively. It traverses and check the equality of the corresponding data values at each level. However, the solution is less safe as compared to comparison in loops. Reflect should be used with care and should be used in those cases where it’s of utmost importance.

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt and reflect package in the program.

Step 2 − Create a function main and in that function create two slices of type string which are to be compared with each other.

Step 3 − In the first case before adding any new element in the slice, compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 4 − In the second case add new string in the slice and compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 5 − The output will be printed using fmt.Prinln() function on the console as a Boolean value.

Example

Golang program to compare elements in two slices using built-in function

package main import ( "fmt" "reflect" ) func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The strings are equal or not before adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The strings are equal or not after adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) } Output The strings are equal or not before adding any element: true The strings are equal or not after adding any element: false Conclusion

In this tutorial, of comparing slices, we used two methods to execute the program. In the first method we used custom function with some conditions and in the second method we used a built-in function named reflect.DeepEqual() function.

## Golang Program To Remove Repeated Elements From An Array

In this tutorial, we will write a go language program to remove duplicate elements from an array. By removing the duplicate entries, we mean that we wish to remove a value repeating multiple times. In this tutorial, we are using examples of an array of integers as well as an array of strings.

Method 1: Remove Duplicate Values from an Array using an External Function

The following code illustrates how we can remove duplicate values from an array of integers using a user-defined function.

Algorithm

Step 1 − First, we need to import the fmt package.

Step 2 − Now, make a function named removeDuplicate() that accepts an array as an argument and returns an array after removing all the duplicate entries.

Step 3 − This function uses a for loop to iterate over the array.

Step 4 − Here we have created a map that has keys as integers and values as Boolean by default the values stored by the map_var are false.

Step 5 − During each iteration from the array, we are checking the value of map_var if it is false then we have to take that value and append it into the new array created above.

Step 6 − Repeat this process until all the array values are checked and then return the new array just formed.

Step 7 − Now, we need to start the main function.

Step 8 − Initialize an array arr of integers, store values to it, and print the array on the screen.

Step 9 − Now call the removeDuplicate function by passing the array created above as an argument to it.

Step 10 − Store the result obtained in an array called result and print the array on the screen.

Example

Golang program to remove duplicate values from an array using an external function.

package main import "fmt" func removeDuplicate(arr int) []int { map_var := map[int]bool{} result := []int{} for e := range arr { if map_var[arr[e]] != true { map_var[arr[e]] = true result = append(result, arr[e]) } } return result } func main() { arr := int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) result := removeDuplicate(arr) fmt.Println("The array obtained after removing the duplicate values is:", result) } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The array obtained after removing the duplicate values is: [1 2 4 5 7] Method 2: Remove Duplicate Elements from an Array without using the Maps

Let us now look at another example of how we can remove duplicate entries from an array without using the maps.

Algorithm

Step 1 − Import the fmt package that allows us to print anything on the screen.

Step 2 − Call the main() function.

Step 3 − Initialize and store the elements in an array of integers and print it on the screen.

Step 4 − Iterate over the array using for loops to check if the current element is equal to the next element or not.

Step 5 − If both the elements are equal then remove the duplicate element using the for loop and decrement the size of the array by 1 by doing size–

Step 6 − Once iterated over the whole array print the elements of the new array obtained on the screen using fmt.Println() function.

Example

GoLang Program to Remove Duplicate Elements from an Array.

package main import "fmt" func main() { arr := []int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) size := len(arr) for i := 0; i < size; i++ { for j := i + 1; j < size; j++ { if arr[i] == arr[j] { for k := j; k < size-1; k++ { arr[k] = arr[k+1] } size-- j-- } } } fmt.Println("The elements of array obtained after removing the duplicate values is:") for i := 0; i < size; i++ { fmt.Println(arr[i]) } } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The elements of array obtained after removing the duplicate values is: 1 2 4 5 7 Conclusion

We have successfully compiled and executed a golang program to remove duplicate elements from an array along with examples.

Update the detailed information about Golang Program To Calculate The Sum Of Columns Of Matrix Elements on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!