# Trending December 2023 # Swift Program To Calculate The Sum Of Rows Of Matrix Elements # Suggested January 2024 # Top 17 Popular

You are reading the article Swift Program To Calculate The Sum Of Rows 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 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[0].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[0].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[0].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.

You're reading Swift Program To Calculate The Sum Of Rows Of Matrix Elements

## 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[0]); 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[0]); 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[0]) { 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[0]); 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.

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

## Swift Program To Check If A Given Square Matrix Is An Identity Matrix

In this article, we will learn how to write a swift program to check if a given square matrix is the identity matrix. The identity matrix is an MxM square matrix in which the main diagonal consists of ones and other elements are all zero. For example −

\$mathrm{M:=:begin{bmatrix}1 & 0 & 0 & 0newline0 & 1 & 0 & 0 newline0 & 0 & 1 & 0 newline0 & 0 & 0 & 1end{bmatrix}}\$

Whereas a square matrix is a matrix in which the number of rows is equal to number of columns and it may or may not contain zeros and ones, means apart from 0s and 1s it contain other numbers. For example −

\$mathrm{M:=:begin{bmatrix}1 & 3 & 4 & 0newline6 & 4 & 0 & 6 newline3 & 6 & 1 & 0 newline4 & 4 & 0 & 1end{bmatrix}}\$

Algorithm

Step 1 − Create a function to check the given matrix is the identity matrix.

Step 2 − In this function, first we check the given matrix is the square matrix by checking the total number of rows and columns.

Step 3 − Using for loop, we check all the elements present in the main diagonal should be one.

Step 4 − Using nested for loop, we check all the elements other than diagonals elements are zero.

Step 5 − If all the conditions mentioned in steps 2, 3, and 4 are true, then this function will return true. Otherwise, return false.

Step 6 − Create three test matrices of integer type.

Step 7 − Call the function and pass the created matrices as a parameter in it.

Step 8 − Print the output.

Example

Following Swift program to check if a given square matrix is identity matrix.

import Foundation import Glibc { if mxt.count != mxt[0].count { return false } for x in 0..<mxt.count { if mxt[x][x] != 1 { return false } } for m in 0..<mxt.count { for n in 0..<mxt[0].count { if m != n && mxt[m][n] != 0 { return false } } } return true } var matrix1 = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] print("Is matrix 1 is an identity matrix?: ", CheckIdentityMatrix(mxt: matrix1)) var matrix2 = [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 1]] print("Is matrix 2 is an identity matrix?: ", CheckIdentityMatrix(mxt: matrix2)) var matrix3 = [[2, 1, 4], [2, 1, 1], [4, 5, 0], [3, 4, 1]] print("Is matrix 3 is an identity matrix?: ", CheckIdentityMatrix(mxt: matrix3)) Output Is matrix 1 is an identity matrix?: true Is matrix 2 is an identity matrix?: false Is matrix 3 is an identity matrix?: false

Here in the above code, we create a function to check whether the given matrices are the identity matrices or not. Therefore, for that, we check the given matrix for three different conditions −

Given matrix is a square matrix or not?

The main diagonal of the given matrix consists of ones (all the elements of the main diagonal) or not.

Elements other than the main diagonal should be zero or not.

If any of the above conditions return false, then the given matrix is not the identity matrix. Alternatively, if all the above three conditions return true, then the given matrix is an identity matrix.

Conclusion

So this is how we can if a given square matrix is an identity matrix or not. If you multiply two identity matrices with each other, then the resultant matrix is also the identity matrix.

## Swift Program To Print 8 Star Pattern

This tutorial will discuss how to write swift program to 8 star pattern.

Star pattern is a sequence of “*” which is used to develop different patterns or shapes like pyramid, rectangle, cross, etc. These star patterns are generally used to understand or practice the program flow controls, also they are good for logical thinking.

To create a 8 star pattern we can use any of the following methods −

Using nested for loop

Using stride Function

Below is a demonstration of the same −

Input

Suppose our given input is −

Num = 5

Output

The desired output would be −

*** * * * * * * *** * * * * * * *** Algorithm

Following is the algorithm −

Step 1 − Declare a variable named rows to store the number of columns.

Step 2 − Declare another variable to store rows −

var val = row * 2 - 1

Step 3 − Run outer for loop starting from 0 to val. This loop handle the rows.

Step 5 − Print the output.

Method 1 – Using Nested for Loop

We can create a 8 pattern of “*” or any other pattern using nested for loops. Here each for loop handle different tasks such as outermost for loop is used for new rows, etc.

Example

The following program shows how to print 8 star pattern using nested for loop.

var row = 10 var val = row * 2 - 1 for x in 1...val{ for y in 1...row{ print(" ", terminator:"") } else{ print("*", terminator:"") } } } else{ for y in 1...row{ print("*", terminator:"") } else{ print(" ", terminator: "") } } } print(" ") } Output ******** * * * * * * * * * * * * * * * * ******** * * * * * * * * * * * * * * * * ******** Method 2 – Using Stride Function

Swift provide an in-built function named stride(). The stride() function is used to move from one value to another with increment or decrement. Or we can say stride() function return a sequence from the starting value but not include end value and each value in the given sequence is steps by the given amount.

Syntax

Following is the syntax −

stride(from:startValue, to: endValue, by:count)

Here,

from − Represent the starting value to used for the given sequence.

to − Represent the end value to limit the given sequence

by − Represent the amount to step by with each iteration, here positive value represent upward iteration or increment and negative value represent the downward iteration or decrement.

Example

The following program shows how to print 8 star pattern using stride() function.

import Swift import Foundation var row = 9 var k = row * 2 - 1 for i in stride(from:1, to:k+1, by:1){ for j in stride(from:1, to:row+1, by:1){ print(" ", terminator:"") } else{ print("*", terminator:"") } } } else{ for j in stride(from:1, to:row+1, by:1){ print("*", terminator:"") } else{ print(" ", terminator: "") } } } print(" ") } Output ******* * * * * * * * * * * * * * * ******* * * * * * * * * * * * * * * *******

Update the detailed information about Swift Program To Calculate The Sum Of Rows 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!