Trending December 2023 # Golang Program To Add Two Matrix Using Multi # Suggested January 2024 # Top 15 Popular

You are reading the article Golang Program To Add Two Matrix Using Multi updated in December 2023 on the website Minhminhbmm.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 Add Two Matrix Using Multi

In this tutorial, we will write a go language program to add two matrices. The difference between a single-dimension array and a multidimensional array is that the former holds an attribute while the latter holds another array on the index. Additionally, every element of a multidimensional array will have the same data type.

Adding Two Matrices Using Loops

Let us now look at a go language program to add two matrices using loops.

Algorithm to the Above Program

Step 1 − Import the fmt package.

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

Step 3 − Then we are creating two matrices named matrixA and matrixB and store values in them.

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

Step 5 − Initialize a new matrix of type int to hold the result.

Step 6 − To add the two matrices use the for loop to iterate over the two matrices

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 new matrix has the sum of the two matrices.

Step 9 − Print the elements of the new matrix using for loops and fmt.Println() function.

Example package main import ( "fmt" ) func main() { var i, j int var matrixC [3][3]int matrixA := [3][3]int{ {0, 1}, {4, 5}, {8, 9}, } matrixB := [3][3]int{ {10, 11, 12}, {13, 14, 15}, {16, 17, 18}, } fmt.Println("The first matrix is:") for i = 0; i < 3; i++ { for j = 0; j < 2; j++ { fmt.Print(matrixA[i][j], "t") } fmt.Println() } fmt.Println() fmt.Println("The second matrix is:") for i = 0; i < 3; i++ { for j = 0; j < 3; j++ { fmt.Print(matrixB[i][j], "t") } fmt.Println() } fmt.Println() fmt.Println("The results of addition of matrix A & B: ") for i = 0; i < 3; i++ { for j = 0; j < 3; j++ { matrixC[i][j] = matrixA[i][j] + matrixB[i][j] } } for i = 0; i < 3; i++ { for j = 0; j < 3; j++ { fmt.Print(matrixC[i][j], "t") } fmt.Println() } } Output The first matrix is: 0 1 4 5 8 9 The second matrix is: 10 11 12 13 14 15 16 17 18 The results of addition of matrix A & B: 1012 12 17 19 15 24 26 18 Add Two Matrices Using an External Function

In this example, we will use user-defined functions to add two matrices.

Algorithm to the Above Program

Step 1 − Import the fmt package.

Step 2 − Create a function to add two matrices.

Step 3 − In this function use make() function to create a slice of the matrix and the range function to iterate over the matrix to find the sum

Step 4 − Start the main function.

Step 5 − Initialize two matrices and store elements to them print the matrices on the screen.

Step 6 − Call the AddMatrices() function by passing the two matrices as arguments to the function.

Step 7 − Store the result obtained and print it on the screen.

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 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.

Example package main import ( "fmt" ) func AddMatrix(matrix1 [3][3]int, matrix2 [3][3]int) [][]int { result := make([][]int, len(matrix1)) for i, a := range matrix1 { for j, _ := range a { result[i] = append(result[i], matrix1[i][j]+matrix2[i][j]) } } return result } func main() { matrixA := [3][3]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 10}, } matrixB := [3][3]int{ {10, 11}, {13, 14}, {16, 17}, } fmt.Println("The first matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(matrixA[i][j], "t") } fmt.Println() } fmt.Println() fmt.Println("The second matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 2; j++ { fmt.Print(matrixB[i][j], "t") } fmt.Println() } fmt.Println() result := AddMatrix(matrixA, matrixB) fmt.Println("The results of addition of matrix A & B: ") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(result[i][j], "t") } fmt.Println() } } Output The first matrix is: 0 1 2 4 5 6 8 9 10 The second matrix is: 10 11 13 14 16 17 The results of addition of matrix A & B: 10 12 2 17 19 6 24 26 10 Conclusion

We have successfully compiled and executed a go language program to add to matrices along with examples. In the first example, we have implemented the logic in the main() function while in the second one we have used external functions to implement the above logic.

You're reading Golang Program To Add Two Matrix Using Multi

Golang Program To Calculate Difference Between Two Time Periods

In this tutorial, we will write a golang programs to calculate the difference between two time periods given in the following programs. To get the time difference between two time periods we can either use a library function or can create a separate user-defined function to achieve the results.

Method 1: Calculate the Difference between Two Time Periods using Internal Function

In this method, we will write a go language program to find the difference between time periods using pre-defined functions in go programming language.

Syntax func (t Time) Sub(u Time) Duration

The sub() function in go is used to get the difference between two dates. In this function the first two parameters i.e., t and u are date values and this function returns the difference between two values in hours, minutes, and seconds.

Algorithm

Step 1 − First, we need to import the fmt and time. The time package allows us to use other predefined packages like time.Date().

Step 2 − Start the main() function.

Step 3 − Initialize firstDate and secondDate variables by passing the dates and times in time.Date() function in the order of yy/mm/dd/hrs//min//sec

Step 4 − Find the difference between the given dates using Sub() function this function takes the second date as an argument and calculates the required difference.

Step 5 − Print the result on the screen in various formats.

Step 6 − We can print the years, days, months, weeks, hours, second, milliseconds, etc.

Example

Golang program to calculate the difference between two time periods using internal function

package main import ( "fmt" "time" ) func main() { firstDate := time.Date(2023, 4, 13, 3, 0, 0, 0, time.UTC) secondDate := time.Date(2010, 2, 12, 6, 0, 0, 0, time.UTC) difference := firstDate.Sub(secondDate) fmt.Println("The difference between dates", firstDate, "and", secondDate, "is: ") fmt.Printf("Years: %dn", int64(difference.Hours()/24/365)) fmt.Printf("Months: %dn", int64(difference.Hours()/24/30)) fmt.Printf("Weeks: %dn", int64(difference.Hours()/24/7)) fmt.Printf("Days: %dn", int64(difference.Hours()/24)) fmt.Printf("Hours: %.fn", difference.Hours()) fmt.Printf("Minutes: %.fn", difference.Minutes()) fmt.Printf("Seconds: %.fn", difference.Seconds()) fmt.Printf("Nanoseconds: %dn", difference.Nanoseconds()) } Output The difference between dates 2023-04-13 03:00:00 +0000 UTC and 2010-02-12 06:00:00 +0000 UTC is: Years: 12 Months: 148 Weeks: 634 Days: 4442 Hours: 106629 Minutes: 6397740 Seconds: 383864400 Nanoseconds: 383864400000000000 Method 2: Calculate the Difference between Two Time Periods using a User-Defined Function

In this method, we will create a different function to calculate the difference between the two provided dates. The function will take the two dates as arguments and return the respective result.

Algorithm

Step 1 − First, we need to import the fmt and time packages. The time package allows us to use other predefined functions like time.Date().

Step 2 − Create the leapYear() function to calculate the number of leap years between the two dates.

Step 3 − Also create the getDifference() to get the difference between date and time. getDifference() function returns the days, hours, minutes, and seconds.

Step 4 − Start the main() function.

Step 5 − Initialize date1 and date2 variables by passing the dates and times in time.Date() function in the order of yy/mm/dd/hrs//min//sec.

Step 6 − Swap the two dates if date1 occurs after date2.

Step 7 − Call the getDifference() by passing the two dates as arguments to the function.

Step 8 − Store the result obtained by the function in a different variable and print them on the screen in different formats using fmt.Println() function.

Example

Golang program to calculate the difference between two time periods using a user-defined function

package main import ( "fmt" "time" ) func leapYears(date time.Time) (leaps int) { y, m, _ := date.Date() if m <= 2 { y-- } leaps = y/4 + y/400 - y/100 return leaps } func getDifference(a, b time.Time) (days, hours, minutes, seconds int) { monthDays := [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} y1, m1, d1 := a.Date() y2, m2, d2 := b.Date() h1, min1, s1 := a.Clock() h2, min2, s2 := b.Clock() totalDays1 := y1*365 + d1 for i := 0; i < (int)(m1)-1; i++ { totalDays1 += monthDays[i] } totalDays1 += leapYears(a) totalDays2 := y2*365 + d2 for i := 0; i < (int)(m2)-1; i++ { totalDays2 += monthDays[i] } totalDays2 += leapYears(b) days = totalDays2 - totalDays1 hours = h2 - h1 minutes = min2 - min1 seconds = s2 - s1 if seconds < 0 { seconds += 60 minutes-- } if minutes < 0 { minutes += 60 hours-- } if hours < 0 { hours += 24 days-- } return days, hours, minutes, seconds } func main() { date1 := time.Date(2023, 4, 27, 23, 35, 0, 0, time.UTC) date2 := time.Date(2023, 5, 12, 12, 43, 23, 0, time.UTC) if date1.After(date2) { date1, date2 = date2, date1 } days, hours, minutes, seconds := getDifference(date1, date2) fmt.Println("The difference between dates", date1, "and", date2, "is: ") fmt.Printf("%v daysn%v hoursn%v minutesn%v seconds", days, hours, minutes, seconds) } Output The difference between dates 2023-05-12 12:43:23 +0000 UTC and 2023-04-27 23:35:00 +0000 UTC is: 716 days 10 hours 51 minutes 37 seconds Conclusion

We have successfully compiled and executed a go language program to get the difference between two time periods along with examples. In the first example, we used internal functions and in the second example, we used a user-defined function to obtain the results.

Golang Program To Get The Relative Path From Two Absolute Paths

To get the relative path from two absolute paths in golang, we use filepath and string packages. Relative paths tell the location of file with respect to present working directory whereas absolute paths tell the location of file starting from root directory. In the first method we will use filepath package functions and in the second method we will use strings package function.

Method 1: Using Filepath Package

In this program, the base name of the file, which is the file name without the directory path, is extracted using the chúng tôi function from the path/filepath package. The name of the extracted file is then displayed on the console using fmt package.

Syntax filepath.Rel

This function is used to find the relative path between two file paths. It takes two inputs- the basepath and the targetpath.

Algorithm

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

Step 2 − Create a function main and in that function create two path variables path1 and path and assign them absolute path.

Step 3 − Now use chúng tôi function to get the relative path from the two absolute paths.

Step 4 − If the path is obtained successfully, its printed on the console but when it’s not obtained successfully print the error on the console and return.

Step 5 − The print statement is executed using fmt.Println() function

Example

In this example, we will use chúng tôi function to get the relative path from two absolute paths. Let’s have a look at the code.

package main import ( "fmt" "path/filepath" ) func main() { relPath, err := filepath.Rel(Path1, Path2) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Relative path:", relPath) } Output Relative path: ../folder2 Method 2: Using Strings Package

In this method, the absolute paths are first divided into their component parts using the strings.Split function. In the next step components are iterated and compared to find the common prefix between the two pathways. An error is returned if there is no common prefix between the paths. Otherwise, the remaining components in Path1 are added first, followed by the remaining components in Path2, to create the relative path.

Syntax func Split(str, sep string) []string

Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.

func len(v Type) int

The len() function is used to get the length of 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.

Algorithm

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

Step 2 − Create a function relativePath with two absolute paths defined in main function and an error of string type.

Step 3 − In this step, split the paths into components using strings.Split function.

Step 4 − Then, iterate the components1 and components2 to check if they have any common prefix or they are equal.

Step 5 − If the paths do not have a common prefix, print it on the console.

Step 6 − Then, Build a relative path by adding ../ in the remaining components of the absolute path.

Step 7 − After all the previous steps performed return the relative path to the function.

Step 8 − In the main if the relative path is obtained successfully, it will be printed on the console but if an error occurs while obtaining the path, print the error and return.

Step 9 − The print statement is executed using fmt.Println() function

Example

In this example, we will use strings.Split function to split the paths into components and build relative paths.

package main import ( "fmt" "strings" ) func relativePath(Path1, Path2 string) (string, error) { components1 := strings.Split(Path1, "/") components2 := strings.Split(Path2, "/") var i int for i = 0; i < len(components1) && i < len(components2); i++ { if components1[i] != components2[i] { break } } if i == 0 { return "", fmt.Errorf("Paths do not have a common prefix") } var relativePath string for j := i; j < len(components1)-1; j++ { relativePath += "../" } for j := i; j < len(components2); j++ { relativePath += components2[j] + "/" } return relativePath, nil } func main() { relPath, err := relativePath(Path1, Path2) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Relative path:", relPath) } Output Relative path: folder2/ Conclusion

We executed the program of getting a relative path from two absolute paths using two examples. In the first example we used chúng tôi to find the relative path and in the second example we used strings package functions.

Using Data For Successful Multi

How to use data to optimise your multi-channel marketing

Multi-channel marketing provides businesses with the opportunity to engage with consumers across a variety of different fronts, tailoring messages for specific groups while maintaining a consistent message and brand. But it’s not simply a matter of sending your message blindly out into the ether – to achieve true success over multiple channels you need to make effective use of the data at your disposal.

This article demystifies this process, helping you understand what this data is, where you need to find it and what you need to do with it. As with all marketing, a little bit of considered thought at the start of the campaign makes a real difference in the result.

Tracking your data

This may seem obvious, but the actual obtaining of your data is the most important place to start and tracking a campaign is really the only way to determine whether your marketing efforts are having a positive effect on your business’s bottom line.

In the digital world, track conversion metrics broken down by target audience and geography. When offline, data should be tracked at the lowest level possible to ensure clarity and simplicity. Something else to consider is the manner in which this data will be stored. Marketing produces a high volume of data, and it’s important to ensure you will have an intuitive system for tracking and managing this information. It may even be an idea to outsource this aspect of the process, for simplicities sake.

Analyse your data

Now that you have your data, it’s important to understand what it’s telling you. Consider a consumer’s interaction with your brand as a path, from discovering the initial message to ultimately making a purchase/interacting with your service.

Discovering and acknowledging the channels different groups are using to interact with your brand is a good way to understand improvements you can make on a broader level, as well as some quick victories that can streamline processes.

A thorough data analysis is also a good way to gain a thorough understanding of the consumers who are interacting with your brand. Find out who the high value consumers are and determine ways in which you can enhance engagement. Also, consider the devices they are using in their interactions. You’re as good as your data in marketing, and a thorough analysis will ensure you get more bang for your buck.

Develop a strategy

Now that you’ve analysed your data, it’s time to decide how you’re going to respond to it. You’ve discovered the channels your consumers are responding to and the groups of consumers are of highest value, so now it’s time to maximise this and develop a message that will achieve results for your business.

There are a few things to consider in this process. For instance, it’s important to make sure the message that passes through to your customers across multiple channels is a consistent, effective one. It’s also important to make sure the consumer’s journey through different channels is as seamless as possible. An online clothes retailer may have people browsing on mobile devices during the day but only making the purchase when they get home, so keep this in mind at all times.

Respond through preferred channels

Now you’ve analysed your data and formulated an effective strategy, it’s time to bring it all together. Multi-channel marketing allows you to engage different groups of consumers with tailor-made messages, but as mentioned before, it’s important to ensure these messages are consistent with the overall identity of your brand.

Test, test, test

The most important part here is tracking your results, responding and testing. Look for different aspects of your campaign to test and make sure you integrate them into your planning. Think about different conversation metric variables and see how you can tinker with them to achieve different results. As with any marketing, it’s not likely you’re going to find the thing that works best with your first effort, so be flexible and willing to incorporate new ideas into your campaign. The world moves at a fast pace these days and if you’re not willing to keep up, it will be to the detriment of your multi-channel marketing campaign. Testing and a degree of flexibility in your approach allows you to keep track of what is and isn’t working and stay ahead of the curve.

Multi-channel marketing is one of the most effective ways to engage with consumers in 2023. But it’s important to do it correctly. Track your data, analyse your data and develop a strategy that allows you to respond effectively in the appropriate channels. And once you’ve done this test, test and test some more! A proactive approach can achieve serious results for your business, allowing you to maintain a consistent message across multiple platforms and maximise the yield from your consumers.

At the end of the day, multi-channel marketing is about getting as much bang for your buck as possible. An acute awareness of what your data is telling you and how to respond will help your business grow and separate you from the rest of the pack.

Java Menu Driven Program To Perform Matrix Operation

Array in Java is called as a non primitive data type which stores a fixed number of single type values. It is called a one-dimensional array. Whereas matrix refers to a rectangular array or Two-Dimensional array.

In this article, we will see how to perform different matrix operations like addition, subtraction, and multiplication by using Java Menu driven program. We will be implementing the application using a switch case.

To show you some instances  Instance-1 Suppose we have inserted two different matrices of 2 rows and 3 columns. Then we will perform matrix addition and print the result. Let the matrix be: First Matrix: 2 3 5 9 8 7 Second Matrix: 6 4 8 9 5 4 Matrix after addition: 8 7 13 18 13 11 Instance-2 Suppose we have inserted two different matrices of 2 rows and 3 columns. Then we will perform matrix subtraction and print the result. Let the matrix be: First Matrix: 2 3 5 9 8 7 Second Matrix: 6 4 8 9 5 4 Matrix after Subtraction: -4 -1 -3 0 3 3 Instance-3 Suppose we have inserted two different matrices of 2 rows and 3 columns. Then we will perform matrix multiplication and print the result. Let the matrix be: First Matrix: 2 3 5 9 8 7 Second Matrix: 6 4 8 9 5 4 Matrix after Multiplication: 12 12 40 81 40 28 Syntax

To calculate the matrix addition, subtraction and multiplication we use a for loop with some basic logic.

Following is the syntax for “for loop” −

for (statement 1; statement 2; statement 3) { } Algorithm

Step-1 − Ask the user to input the two matrices.

Step-2 − Display the menu.

Step-3 − Ask the user to enter their choice.

Step-4 − Use a switch case to go to the choice and perform the operation.

Step-5 − Print the result.

Let’s see the program to understand it clearly.

Example

import

java

.

util

.

*

;

public

class

Main

{

public

static

void

main

(

String

args

[

]

)

{

Scanner

s

=

new

Scanner

(

System

.

in

)

;

int

p

,

q

,

m

,

n

;

System

.

out

.

print

(

"Enter number of rows in first matrix: "

)

;

p

=

s

.

nextInt

(

)

;

System

.

out

.

print

(

"Enter number of columns in first matrix: "

)

;

q

=

s

.

nextInt

(

)

;

System

.

out

.

print

(

"Enter number of rows in second matrix: "

)

;

m

=

s

.

nextInt

(

)

;

System

.

out

.

print

(

"Enter number of columns in second matrix: "

)

;

n

=

s

.

nextInt

(

)

;

int

a

[

]

[

]

=

new

int

[

p

]

[

q

]

;

int

b

[

]

[

]

=

new

int

[

m

]

[

n

]

;

int

c

[

]

[

]

=

new

int

[

m

]

[

n

]

;

System

.

out

.

println

(

"Enter all the elements of first matrix:"

)

;

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

q

;

j

++

)

{

a

[

i

]

[

j

]

=

s

.

nextInt

(

)

;

}

}

System

.

out

.

println

(

"Enter all the elements of second matrix:"

)

;

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

b

[

i

]

[

j

]

=

s

.

nextInt

(

)

;

}

}

System

.

out

.

println

(

"First Matrix:"

)

;

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

q

;

j

++

)

{

System

.

out

.

print

(

a

[

i

]

[

j

]

+

" "

)

;

}

System

.

out

.

println

(

""

)

;

}

System

.

out

.

println

(

"Second Matrix:"

)

;

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

System

.

out

.

print

(

b

[

i

]

[

j

]

+

" "

)

;

}

System

.

out

.

println

(

""

)

;

}

mainLoop

:

while

(

true

)

{

System

.

out

.

println

(

"n***Menu***"

)

;

System

.

out

.

println

(

"1. Matrix Addition"

)

;

System

.

out

.

println

(

"2. Matrix Subtraction"

)

;

System

.

out

.

println

(

"3. Matrix Multiplication"

)

;

System

.

out

.

println

(

"4. Terminate the program"

)

;

System

.

out

.

println

(

"Enter action number (1-4): "

)

;

int

command

;

if

(

s

.

hasNextInt

(

)

)

{

command

=

s

.

nextInt

(

)

;

s

.

nextLine

(

)

;

}

else

{

System

.

out

.

println

(

"nILLEGAL RESPONSE. YOU MUST ENTER A NUMBER."

)

;

s

.

nextLine

(

)

;

continue

;

}

switch

(

command

)

{

case

1

:

if

(

p

==

m

&&

&

q

==

n

)

{

for

(

int

i

=

0

;

i

<

p

;

i

++

)

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

for

(

int

k

=

0

;

k

<

q

;

k

++

)

{

c

[

i

]

[

j

]

=

a

[

i

]

[

j

]

+

b

[

i

]

[

j

]

;

}

}

}

System

.

out

.

println

(

"Matrix after addition:"

)

;

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

System

.

out

.

print

(

c

[

i

]

[

j

]

+

" "

)

;

}

System

.

out

.

println

(

""

)

;

}

}

else

{

System

.

out

.

println

(

"Addition would not be possible"

)

;

}

break

;

case

2

:

if

(

p

==

m

&&

q

==

n

)

{

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

for

(

int

k

=

0

;

k

<

q

;

k

++

)

{

c

[

i

]

[

j

]

=

a

[

i

]

[

j

]

-

b

[

i

]

[

j

]

;

}

}

}

System

.

out

.

println

(

"Matrix after Subtraction:"

)

;

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

System

.

out

.

print

(

c

[

i

]

[

j

]

+

" "

)

;

}

System

.

out

.

println

(

""

)

;

}

}

else

{

System

.

out

.

println

(

"Subtraction would not be possible"

)

;

}

break

;

case

3

:

if

(

p

==

m

&&

q

==

n

)

{

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

for

(

int

k

=

0

;

k

<

q

;

k

++

)

{

c

[

i

]

[

j

]

=

a

[

i

]

[

j

]

*

b

[

i

]

[

j

]

;

}

}

}

System

.

out

.

println

(

"Matrix after Multiplication:"

)

;

for

(

int

i

=

0

;

i

<

p

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

System

.

out

.

print

(

c

[

i

]

[

j

]

+

" "

)

;

}

System

.

out

.

println

(

""

)

;

}

}

else

{

System

.

out

.

println

(

"Multiplication would not be possible"

)

;

}

break

;

case

4

:

System

.

out

.

println

(

"Program terminated"

)

;

break

mainLoop

;

default

:

System

.

out

.

println

(

"Wrong choice!!"

)

;

}

}

}

Output Enter number of rows in first matrix: 2 Enter number of columns in first matrix: 2 Enter number of rows in second matrix: 2 Enter number of columns in second matrix: 2 Enter all the elements of first matrix: 1 2 3 4 Enter all the elements of second matrix: 5 6 7 8 First Matrix: 1 2 3 4 Second Matrix: 5 6 7 8 ***Menu*** 1. Matrix Addition 2. Matrix Subtraction 3. Matrix Multiplication 4. Terminate the program Enter action number (1-4): 1 Matrix after addition: 6 8 10 12 ***Menu*** 1. Matrix Addition 2. Matrix Subtraction 3. Matrix Multiplication 4. Terminate the program Enter action number (1-4): 2 Matrix after Subtraction : -4 -4 -4 -4 ***Menu*** 1. Matrix Addition 2. Matrix Subtraction 3. Matrix Multiplication 4. Terminate the program Enter action number (1-4): 3 Matrix after Multiplication: 5 12 21 32 ***Menu*** 1. Matrix Addition 2. Matrix Subtraction 3. Matrix Multiplication 4. Terminate the program Enter action number (1-4): 4 Program terminated

In this article, we explored how to perform matrix operations in Java by using a menu driven approach.

Golang Program To Swapping Pair Of Characters

A string in Golang is a collection of characters. Since strings in Go are immutable, they cannot be modified after they have been produced. Concatenating or adding to an existing string, however, enables the creation of new strings. A built-in type in Go, the string type can be used in a variety of ways much like any other data type. Let’s see how the logic can be executed. In this article, we will inculcate the ways to swap pair of characters in the string using different set of examples.

Syntax 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.

Method 1 : By converting the string to byte slice

Here, in increments of 2, the method iterates through the input string after converting it to a byte slice. Using a multiple assignment statement, it switches the current character with the following one after each iteration. After that, the obtained byte slice is changed back into a string and given back.

Algorithm

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

Step 2 − Create a function swap_pairs and in that function create a byte slice from the input string.

Step 3 − Set the value of a variable i to 0 and use a for loop to go through the bytes, increasing i by 2 each time.

Step 4 − Use a multiple assignment statement inside the for loop to swap the current character (at index i with the following character (at index i+1)).

Step 5 − Return the string-to-byte slice conversion after the for loop terminates and the output is printed on the console using fmt.Println() function where ln means new line.

Step 6 − It only iterates through the string once and executes the swap operation “in-place” on the byte slice, this approach makes it possible to efficiently swap pairs of characters in the input string.

Example

In this example we will see how to swap pair of characters by converting the string to byte.

package main import ( "fmt" ) func swap_pairs(str string) string { b := []byte(str) for i := 0; i < len(b)-1; i += 2 { b[i], b[i+1] = b[i+1], b[i] } return string(b) } func main() { str := "hello" fmt.Println("The string created here is:", str) fmt.Println("The string with characters swapped is:") fmt.Println(swap_pairs(str)) } Output The string created here is: hello The string with characters swapped is: ehllo Method 2: Using Recursion Method

In this example, we will see how to swap pair of characters using recursion. Recursion is used by the function to repeatedly swap the string’s initial two characters, after which the remaining characters are passed on to the subsequent call. When the input string contains fewer than two characters, the recursion’s base case, the string is returned in its original form. Each recursive call returns the string’s first character concatenated with its second character, along with the remainder of the string that will be sent to the following recursive call. Let’s see the Example: and the algorithm to know its execution.

Algorithm

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

Step 2 − Create a function swap_pairs_recursive with one string parameter whose pair of character is to be swapped.

Step 3 − In the function, verify that the input string is only two characters or less. In that case, simply return the string.

Step 4 − Return the second character concatenated with the first character, concatenated with the outcome of executing swap_pairs_recursive on a substring of the input string beginning with the third character, if the input string is longer than 2 characters.

Step 5 − On the input string, call the swap_pairs_recursive function.

Step 6 − The function call’s output should be printed using fmt.Println() function where ln means new line.

Step 7 − Recursion is used in this approach to transmit the remaining characters to the subsequent recursive call while repeatedly swapping the first two characters of the input string. Due to the several function calls and string concatenation required, it is less effective than the prior technique.

Example

In this example, we will see how to swap pair of characters using recursion.

package main import ( "fmt" ) func swap_pairs_recursive(str string) string { if len(str) < 2 { return str } return str[1:2] + str[0:1] + swap_pairs_recursive(str[2:]) } func main() { str := "hello" fmt.Println("The string created here is:", str) fmt.Println("The string with characters swapped is:") fmt.Println(swap_pairs_recursive(str)) } Output The string created here is: hello The string with characters swapped is: ehllo Conclusion

We executed the program of swapping pair of characters using two examples. In the first example we used the string to byte conversion and in the second example we used recursion to swap characters.

Update the detailed information about Golang Program To Add Two Matrix Using Multi on the Minhminhbmm.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!