Trending March 2024 # Golang Program To Calculate The Sum Of Rows Of Matrix Elements # Suggested April 2024 # Top 12 Popular

You are reading the article Golang Program To Calculate The Sum Of Rows Of Matrix Elements updated in March 2024 on the website Cattuongwedding.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 April 2024 Golang Program To Calculate The Sum Of Rows Of Matrix Elements

A matrix is a collection of numbers arranged in rows and columns, a two-dimensional array. Here we will use three methods to find the sum of elements and compare each method for the same using Go Programming language.

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.

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 row elements use the for loop to iterate over the matrix.

Step 7 − Using the first for loop is used to get the row 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 this Golang program, 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 := [3][3]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 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++ { sum := 0 for j := 0; j < len(matrix[i]); j++ { sum += matrix[i][j] } fmt.Printf("Sum of elements in row %d is %dn", i+1, sum) } } Output The given matrix is: 0 1 2 4 5 6 8 9 10 Sum of elements in row 1 is 3 Sum of elements in row 2 is 15 Sum of elements in row 3 is 27 Example 2

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

package main import "fmt" func main() { matrix := [3][3]int{ {20, 1, 2}, {4, 5, 6}, {8, 9, 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, row := range matrix { sum := 0 for _, val := range row { sum += val } fmt.Printf("Sum of elements in row %d is %dn", i+1, sum) } } Output The given matrix is: 20 1 2 4 5 6 8 9 10 Sum of elements in row 1 is 23 Sum of elements in row 2 is 15 Sum of elements in row 3 is 27 Example 3

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

package main import "fmt" func rowSum(matrix [][]int, row int) int { if row == len(matrix) { return 0 } sum := 0 for _, val := range matrix[row] { sum += val } return sum } func main() { matrix := [][]int{ {20, 1, 2}, {4, 50, 6}, {8, 9, 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 row %d is %dn", i+1, rowSum(matrix, i)) } } Output The given matrix is: 20 1 2 4 50 6 8 9 10 Sum of elements in row 1 is 23 Sum of elements in row 2 is 60 Sum of elements in row 3 is 27 Conclusion

We have successfully compiled and executed a go language program to add to matrices 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 Rows Of Matrix Elements

Python Program To Calculate The Sum Of Right Diagonal The Matrix

A well-liked general-purpose programming language is Python. It is applied in a variety of industries, including desktop applications, web development, and machine learning. Fortunately, Python features a straightforward, user-friendly syntax for beginners. Here, in our article we will be using python for calculating the sum of right diagonal of the matrix.

What is a Matrix?

In mathematics, we use a rectangular arrangement or a matrix, which is used to describe a mathematical object or an attribute of one, it is a rectangular array or table containing numbers, symbols, or expressions that are arranged in rows and columns.

For Instance −

2 3 4 5 1 2 3 6 7 5 7 4

Hence, this is a matrix with 3 rows and 4 columns, which is represented as 3*4 matrix.

Now, there are two diagonals in the matrix i.e the Primary or Principal diagonal and the Secondary diagonal. Primary or principal diagonal is the diagonal starting from the upper left corner to the lower right corner and the secondary diagonal starting from lower left corner to the upper right corner.

From the above example we see that both a00, a11 are the principal diagonal (left diagonal) and a10, a01 is the secondary matrix (right diagonal), as shown below

2 3 a00 a01 1 2 a10 a11 Sum of Right Diagonal of the Matrix

As we have revised the basics concepts and we have a complete understanding of the matrix and the diagonals let’s dive deep into the topic now and complete the coding part of the concept.

For calculating the sum let’s take a 2D matrix. Consider a 4*4 matrix with elements

Here, a00, a11, a22 and a33 are the elements of the primary or principal diagonal of the matrix. The secondary or right diagonal consists of elements a30, a21, a12 and a03.

There is an important condition to consider before completing this task: for taking out the sum of elements present in the primary diagonal, it must fulfill what is known as the row-column condition which states that for every element in each row there must be an equivalent column number.

Similarly, for calculating the sum of elements on the secondary diagonal (a03, a12, a21 and a30), its row-column condition will be equal to number of rows minus column -1.

2 4 6 8 a00 a01 a02 a03 3 5 7 9 a10 a11 a12 a13 1 4 6 7 a20 a21 a22 a23 3 5 1 4 a30 a31 a32 a33 Using For Loop

In this method, we will use two loops for the purpose, that is for the rows and columns and an inner loop for checking the condition we have provided.

Algorithm

Give a value that is MAX.

Define a function for the matrix.

Use for loop for iterating through the numbers

Provide the condition for the right diagonal of the matrix.

Print the value.

Example

This example defines a constant MAX with the value 50, and then creates a function named SUM_RIGHT_MATRIX which takes in a matrix and an integer.

The function adds together all of the numbers on the right diagonal of the given matrix (i.e. from top right to bottom left) and prints out the sum.

MAX = 50 def SUM_RIGHT_MATRIX (matrix, m): rightD = 0; for i in range (0, m): for j in range (0, m): if ((i + j) == (m - 1)): rightD += matrix[i][j] print ("Sum of right diagonal is:", rightD) T = [[ 13, 21, 33, 45 ], [ 52, 16, 27, 28 ], [ 17, 28, 31, 43 ], [ 54, 26, 87, 28 ]] SUM_RIGHT_MATRIX (T, 4) Output

On the execution of the above program, we get the “Sum of right diagonal is: 155”. This means that the total sum of all numbers in the right diagonal is 155.

Sum of right diagonal is: 154 Using a Single Loop

The sum of the major and secondary diagonals is calculated using a single loop in this approach.

Algorithm

Give a value that is MAX.

Define a function for the matrix.

Use for loop for iterating through the numbers.

Provide the condition for the right diagonal of the matrix.

Print the value.

Example

The following example is defining a function called sumofrightdiagonal, which takes in two parameters: a matrix and m.

It iterates through the matrix and adds together each of the numbers on the right diagonal of the matrix, storing them in a variable called right_diagonal.

Finally, it prints out “Sum of Right Diagonal is:” followed by the value stored in right_diagonal. The example also includes an example input of T (a 4×4 matrix) with m being equal to 4, so that when Sumofrightdiagonal is called with these values as its parameters, it will calculate and print out the sum of all elements on T’s right diagonal.

MAX = 50 def sumofrightdiagonal (matrix, m): right_diagonal = 0 for i in range (0, m): right_diagonal += matrix [i] [m - i - 1] print ("Sum of Right Diagonal is:", right_diagonal) T = [[ 11, 12, 33, 24 ], [ 54, 69, 72, 84 ], [ 14, 22, 63, 34 ], [ 53, 64, 79, 83 ]] sumofrightdiagonal (T, 4) Output Sum of Right Diagonal: 171 Conclusion

In this article, we have briefly discussed about the two simple methods using python program to calculate the sum of right diagonal of the matrix. The first method uses two loops for completing the task provided to us while the second method provides us an efficient approach of completing the same task but with a shorter path.

Python Program To Interchange Elements Of First And Last In A Matrix Across Rows

A matrix is a set of numbers arranged in rows and columns format. In python, a matrix can not be created directly. Instead, we can use a nested list or NumPy array as a matrix.

The interchanging of first and last row elements of a matrix is demonstrated below.

Input Output Scenarios

Assume we have a 3X3 matrix represented using a nested list. and output matrix will be the resultant matrix whose first and last row elements are interchanged.

Input matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9] Output matrix: [7, 8, 9] [4, 5, 6] [1, 2, 3]

Let’s consider another matrix whose rows and columns are unequal.

Input matrix: ['a', 'b'] ['c', 'd', 'e'] ['f', 'g', 'h', 'i'] Output matrix: ['f', 'g', 'h', 'i'] ['c', 'd', 'e'] ['a', 'b']

Let’s discuss the one by one approach −

Swapping the Rows

We can simply interchange the elements of first and last in a matrix across rows, by swapping the first and last rows.

Example

In this example, we will swap the first and last rows with the help of first [0] and last [-1] row indexes.

matrix = [[1,2,3], [4,5,6], [7,8,9]] #function for displaying matrix def display(matrix): for row in matrix: print(row) print() # displaying original matrix print("Original matrix: ") display(matrix) # interchanging the element between first and last rows def swapLines(matrix): matrix[0], matrix[-1] = matrix[-1], matrix[0] return matrix # displaying changed matrix print("Changed matrix: ") display(swapLines(matrix)) Output Original matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9] Changed matrix: [7, 8, 9] [4, 5, 6] [1, 2, 3]

By using the python positive and negative indexing (matrix[0], matrix[-1]) we have interchanged the elements of first and last in a matrix across rows successfully.

Example

In this example, we will interchange the first and last rows of a matrix whose rows and columns dimensions are unequal.

matrix = [['a', 'b'], ['c', 'd', 'e'], [1, 2, 3]] #function for displaying matrix def display(matrix): for row in matrix: print(row) print() # displaying original matrix print("Original matrix: ") display(matrix) # interchanging the element between first and last rows matrix[0], matrix[-1] = matrix[-1], matrix[0] # displaying changed matrix print("Changed matrix: ") display(matrix) Output Original matrix: ['a', 'b'] ['c', 'd', 'e'] [1, 2, 3] Changed matrix: [1, 2, 3] ['c', 'd', 'e'] ['a', 'b']

In this example the original matrix is not a square matrix and we have successfully interchanged the elements of first and last in a matrix across rows.

Using Pop(), Insert(), and Append() Methods

In python pop(), insert() and append() methods are list manipulating methods.

pop() − The pop method removes the element at the specified position. By default, it removes the last element.

insert() − This method can be used to insert an element at any desired position. This method takes two arguments, one is the element and the index at which the element has to be inserted.

append() − method is used to add an element at the end of the list.

Example

With the help of above mentioned methods we will interchange the elements of first and last row of a matrix.

matrix = [['a', 'b'], ['c', 'd', 'e'], ['f', 'g', 'h', 'i']] #function for displaying matrix def display(matrix): for row in matrix: print(row) print() # displaying original matrix print("Original matrix: ") display(matrix) # interchanging the element between first and last rows temp1 = matrix[-1] temp2 = matrix[0] matrix.pop() matrix.pop(0) matrix.insert(0, temp1) matrix.append(temp2) # displaying changed matrix print("Changed matrix: ") display(matrix) Output Original matrix: ['a', 'b'] ['c', 'd', 'e'] ['f', 'g', 'h', 'i'] Changed matrix: ['f', 'g', 'h', 'i'] ['c', 'd', 'e'] ['a', 'b']

By using python list manipulation methods called pop(), insert(), and append() we have successfully interchanged the elements of first and last in a matrix across rows.

Note − matrices are created by using a python list of lists.

Golang Program To Add Elements At First And Last Position Of Linked List

In golang, a linked list is a unique data structure in which there is a value in the node and the next pointer which points to the next node. The list’s initial node is referred to as the head, while the list’s last node which points to nil depicts the end of list. We will add elements at the first and last position of the linked list using two examples. In the first example node struct will be used and in the second example ListNode struct will be used.

Method 1: Using Node Struct

In this method, we will use node struct to add elements at given position in linked list. Here, we will create two methods addfirst and addlast method where the program will be written to add the elements.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Make a Node structure with two fields − data, which will hold the node’s value, and next, which will hold a pointer to the node after it in the list.

Step 3 − Make an addFirst function. A node should be added to the linked list’s front first. The list’s head and the data to be added are the two inputs for this function. With the supplied data, the function generates a new node and sets its next field to the top of the list as it is at the moment.

Step 4 − The function returns a pointer to the new node, which takes over as the list’s new head.

Step 5 − To add a node to the end of the linked list, create the function addLast.

Step 6 − The list’s head and the data to be added are the two inputs for this function. The function iterates through the list beginning at the top and continues until it reaches the bottom.

Step 7 − Then, the next field of the current node is then set to point to the new node after creating a new node with the supplied data. The function returns the list’s head, which is left alone.

Step 8 − To print the linked list’s elements, create the function printList. This method iterates through the list while printing the value of each node’s data field. It takes the list’s head as a parameter.

Step 9 − Then create the list’s head node in the main function, and call the addFirst and addLast functions to add elements to the list’s first and last nodes, respectively.

Step 10 − Finally, use the printList method to show the connected list’s elements.

Example

In this example, we used node struct to add elements at first and last position of linked list.

package main import "fmt" type Node struct { data_val int next *Node } func addFirst(head *Node, data_val int) *Node { newNode := &Node{data_val: data_val} chúng tôi = head return newNode } func addLast(head *Node, data_val int) *Node { newNode := &Node{data_val: data_val} current := head for chúng tôi != nil { current = current.next } chúng tôi = newNode return head } func printList(head *Node) { current := head for current != nil { current = current.next } fmt.Println("nil") } func main() { head := &Node{data_val: 20} fmt.Println("The first and last elements are added as follows:") head = addFirst(head, 10) head = addLast(head, 30) printList(head) } Output The first and last elements are added as follows: Method 2: Using ListNode Struct

In this method, we will use ListNode struct to add elements at given position in linked list. Here, we will create two methods addfirst and addlast method where the program will be written to add the elements.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Build a structure and the ListNode contains two fields − next to store a pointer to the next node in the list and data_val to hold the node’s value.

Step 3 − Create an addFirst function. A node should be added to the linked list’s front first. The list’s head and the value to be added are the two inputs for this function.

Step 4 − In the next step the function takes a value and produces a new node, setting the next field to the head of the list as it is at that moment. The function returns a pointer to the new node, which takes over as the list’s new head.

Step 5 − To add a node to the end of the linked list, create the function addLast. The list’s head and the value to be added are the two inputs for this function.

Step 6 − The function iterates through the list beginning at the top and continues until it reaches the bottom.

Step 7 − The next field of the current node is then set to point to the new node after creating a new node with the specified value. The function returns the list’s head, which is left alone.

Step 8 − To print the linked list’s elements, create the function printList. This function prints the value of each node’s val field after iterating through the list using the list’s head as an argument.

Step 9 − Create the list’s head node in the main function, then call the addFirst and addLast functions to add elements to the list’s first and last nodes, respectively.

Step 10 − Finally, use the printList method to show the connected list’s elements.

Example

In this example, we will use ListNode struct to add elements at first and last position of linked list.

package main import "fmt" type ListNode struct { data_val int next *ListNode } func addFirst(head *ListNode, data_val int) *ListNode { newNode := &ListNode{data_val: data_val} chúng tôi = head return newNode } func addLast(head *ListNode, data_val int) *ListNode { newNode := &ListNode{data_val: data_val} current := head for chúng tôi != nil { current = current.next } chúng tôi = newNode return head } func printList(head *ListNode) { current := head for current != nil { current = current.next } fmt.Println("nil") } func main() { head := &ListNode{data_val: 1} head = addFirst(head, 0) head = addLast(head, 2) fmt.Println("The first and last elements are added as follows:") printList(head) } Output The first and last elements are added as follows: Conclusion

We execute the program of adding the elements at the first and last position of the linked list using two examples. In the first example, we used node struct and in the second example, we used Listnode struct.

Python Program Addition Of Two Matrix

Given two user input matrix. Our task is to display the addition of two matrix. In these problem we use nested List comprehensive.

Algorithm Step1: input two matrix. Step 2: nested for loops only to iterate through each row and columns. Step 3: At each iterationshall add the corresponding elements from two matrices and shall store the result. Example code # Program to add two matrices using nested loop A=[] n=int(input("Enter N for N x N matrix : ")) #3 here #use list for storing 2D array #get the user input and store it in list (here IN : 1 to 9) for i in range(n): row=[] #temporary list to store the row for j in range(n): row.append(int(input())) #add the input to row list A.append(row) #add the row to the list print(A) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] #Display the 2D array print("Display Array In Matrix Form") for i in range(n): for j in range(n): print(A[i][j], end=" ") #new line print() B=[] n=int(input("Enter N for N x N matrix : ")) #3 here #use list for storing 2D array #get the user input and store it in list (here IN : 1 to 9) for i in range(n): row=[] #temporary list to store the row for j in range(n): row.append(int(input())) #add the input to row list B.append(row) #add the row to the list print(B) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] #Display the 2D array print("Display Array In Matrix Form") for i in range(n): for j in range(n): print(B[i][j], end=" ") print() #new line result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(n): # iterate through columns for j in range(len(A[0])): result[i][j] = A[i][j] + B[i][j] for r in result: Output Enter N for N x N matrix : 3 10 10 10 20 20 20 30 30 30 [[10, 10, 10], [20, 20, 20], [30, 30, 30]] Display Array In Matrix Form 10 10 10 20 20 20 30 30 30 Enter N for N x N matrix : 3 100 100 100 200 200 200 300 300 300 [[100, 100, 100], [200, 200, 200], [300, 300, 300]] Display Array In Matrix Form 100 100 100 200 200 200 300 300 300 [220, 220, 220] [330, 330, 330]

Golang Program To Get The Size Of The Hash Collection

In Golang we can use various internal functions or packages like len() function or reflect package, to get the size of the hash collection. A Hash collection contains a hashmap which is generally used to create key:value pairs and on the basis of that it shortens the execution time. In this program, we have used two examples to get the size of hash collection.

Syntax func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

func range(variable)

The range function is used to iterate over any data type. To use this we first have to write the range keyword followed by the data type to which we want to iterate and as a result the loop will iterate till the last element of the variable.

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Using Len Function

In this method, we will create a hashmap using the make function in Golang and then find the length of the map using len function, The length will be printed on the console using fmt package.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and Output.

Step 2 − Create a main function and in this function create a hashmap using make function which is an inbuilt function in Golang.

Step 3 − Assign the values to the keys(key1, key2, key3, key4) of hashmap.

Step 4 − Then, use len method to calculate the length of the hashmap.

Step 5 − Print the length of the map on the console using Println function from fmt package where ln implies new line.

Example

The following example demonstrates Golang program to get the size of the hash collection using len function

package main import "fmt" func main() { hashmap := make(map[string]int) hashmap["key1"] = 10 hashmap["key2"] = 20 hashmap["key3"] = 30 hashmap["key4"] = 40 fmt.Println("Size of map is:", len(hashmap)) } Output Size of map is: 4 Using the Size Variable

In this method, we will use size variable to calculate the size of hashmap. The hashmap will be created similarly like as it’s created in previous example. Then, it will be iterated and the size variable will be incremented on every iteration.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and Output.

Step 2 − in the main function create a hashmap using make function as did in last example.

Step 3 − Add the values to the key elements Such that, key1, key2, key3 and key4 are created.

Step 4 − Create a variable size which will tell us about the size of the hashmap.

Step 5 − Run a loop till the range of hashmap and in every iteration increment the size variable.

Step 6 − Finally, when the loop terminates print the size of the map using Println function where ln means new line.

Example

The following example illustrates Golang program to get the size of the hash collection using the size variable

package main import "fmt" func main() { hashmap := make(map[string]int) hashmap["key1"] = 10 hashmap["key2"] = 20 hashmap["key3"] = 30 hashmap["key4"] = 40 var size int for range hashmap { size++ } fmt.Println("Size of map is:", size) } Output Size of map: 4 Using the reflect package

In this method, we will write a Golang program to get the size of hash collection using the ValueOf function from the reflect package.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and Output.

Step 2 − Create a main function in which further create a hashmap where keys are of type string and values are of type int

Step 3 − Then, obtain the size of the hash collection using the ValueOf function from the reflect package and Len method

Step 4 − Then, print the size of the hash collection using Println function fmt package where ln means new line

Example

The following example demonstrates Golang program to get the size of the hash collection using the reflect package

package main import ( "fmt" "reflect" ) func main() { hashmap := map[string]int{ "pencil": 10, "pen": 20, "scale": 30, } size := reflect.ValueOf(hash).Len() fmt.Println("The size of hash collection is:", size) } Output Found pen with value 10 Conclusion

We executed this program of getting the size of hash collection using two examples. In the first example we used len method to get the size of the map and in the second example we used a variable size to obtain the size of the map. Both the examples gave desired Output.

Update the detailed information about Golang Program To Calculate The Sum Of Rows Of Matrix Elements on the Cattuongwedding.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!