Trending March 2024 # Swift Program To Print Hollow Rectangle Star Pattern # Suggested April 2024 # Top 7 Popular

You are reading the article Swift Program To Print Hollow Rectangle Star Pattern updated in March 2024 on the website Moimoishop.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 Swift Program To Print Hollow Rectangle Star Pattern

This tutorial will discuss how to write swift program to print hollow rectangle 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 hollow rectangle 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 −

Length = 10 Width = 6

Output

The desired output would be −

* * * * * * * * * * * * * * * * * * * * * * * * * * * * Method 1- Using nested for loop

We can create a hollow rectangle star pattern 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, and nested for loop is used to print “*” in columns.

Example

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

import Foundation import Glibc var Rlen = 10 var Rwid = 6 for x in 1..<Rwid+1{ for y in 1..<Rlen+1{ print("*", terminator:" ") } else{ print(" ", terminator:" ") } } print("") } Output * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Here, in the above code, we have length = 10 and width = 6. Now we use nested for loops to print hollow rectangle star pattern. The outer most for loop(starts from 1 to 6) is use to handle the total number of rows are going to print and each row is start with new line. Now the nested for loop(starts from 1 to 10) is used to print “*” for first or last row or for first or last column, otherwise print blank space.

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 hollow rectangle star pattern using stride() function.

import Foundation import Glibc var Rlen = 9 var Rwid = 5 for x in stride(from:1, to:Rwid+1, by: 1){ for y in stride(from:1, to:Rlen+1, by: 1){ print("*", terminator:" ") } else{ print(" ", terminator:" ") } } print("") } Output * * * * * * * * * * * * * * * * * * * * * * * *

Here, in the above code, we have length = 9 and width = 5. Now we uses nested for loops. The outermost for loop(starts from 1 to 9) with stride() is used to handle the total number of rows are going to print and each row starts with a new line. The nested for loop is used to print hollow rectangle star pattern using stride() function −

for y in stride(from:1, to:Rlen+1, by: 1){ print("*", terminator:" ") } else{ print(" ", terminator:" ") } }

Here the iteration starts from 1 to Rlen+1 and each iteration increased by one. In this loop, we print star for first or last row or for first or last column, otherwise print blank space. So this is how we print hollow rectangle star pattern.

You're reading Swift Program To Print Hollow Rectangle Star Pattern

C Program To Print Hollow Pyramid And Diamond Pattern

int main() {    int n, i, j;    printf(“Enter number of lines: “);    scanf(“%d”, &n);    for(i = 1; i<=n; i++) {       for(j = 1; j<=(n-i); j++){          printf(” “);       }          stars continuously          for(j = 1; j<=i; j++) {             printf(“* “);          }       } else {          printf(“*”);          position          for(j = 1; j<=2*i-3; j++) {             printf(” “);          }          printf(“*”);       } } }

Output Enter number of lines: 20                                          *                                        *   *                                       *     *                                      *       *                                     *         *                                    *           *                                   *             *                                  *               *                                 *                 *                                *                   *                               *                     *                              *                       *                             *                         *                            *                           *                           *                             *                          *                               *                         *                                 *                        *                                   *                       *                                     * int main() {    int n, i, j, mid;    printf("Enter number of lines: ");    scanf("%d", &n);    if(n %2 == 1) {       n++; } mid = (n/2); for(i = 1; i<= mid; i++) {     for(j = 1; j<=(mid-i); j++){       printf(" ");     }     if(i == 1) {       printf("*");     } else {       printf("*");       position       for(j = 1; j<=2*i-3; j++){           printf(" ");       }       printf("*");     } } for(i = mid+1; i<n; i++) {    for(j = 1; j<=i-mid; j++) {       printf(" ");    }    if(i == n-1) {       printf("*");    } else {       printf("*");       position       for(j = 1; j<=2*(n - i)-3; j++) {         hollow         printf(" ");       }       printf("*");    } } Output Enter number of lines: 15                       *                     *   *                   *       *                  *         *                 *           *                *             *               *               *              *                 *               *               *                *             *                 *           *                  *         *                    *     *                     *   *                       *

Swift Program To Multiply Two Matrices Using Multi

In this article, we will learn how to write a swift program to multiply two matrices using multi-dimensional arrays.

A matrix is a mathematical structure in which the elements are present in rows and columns format. For example, the first element is present at the a00 location, the second at a01, and so on. Therefore, to multiply two matrices, we multiply the mth row of the first matrix by an nth column of the second matrix and add the products. This will create an element at the mth row and nth columns of the resultant matrix. For example −

Matrix 1 −

$mathrm{begin{bmatrix}2 & 3 & 4 newline5 & 2 & 7 newline9 & 3 & 2end{bmatrix}}$

Matrix 2 −

$mathrm{begin{bmatrix}4 & 7 & 1 newline1 & 1 & 4 newline5 & 7 & 2end{bmatrix}}$

So the product = Matrix 1 * Matrix 2

$mathrm{begin{bmatrix}(2^{*}4+3^{*}1+4^{*}4) & (2^{*}7+3^{*}1+4^{*}7) & (2^{*}1+3^{*}4+4^{*}2) newline(5^{*}4+2^{*}1+7^{*}4) & (5^{*}7+2^{*}1+7^{*}7) & (5^{*}1+2^{*}4+7^{*}2) newline(9^{*}4+3^{*}1+2^{*}4) & (9^{*}7+3^{*}1+2^{*}7) & (9^{*}1+3^{*}4+2^{*}2)end{bmatrix}}$

$mathrm{begin{bmatrix}27 & 45 & 22 newline50 & 86 & 27 newline47 & 80 & 25end{bmatrix}}$

Algorithm

Step 1 − Define the size of the rows and columns.

Step 2 − Create two matrices of the same rows and columns using multidimensional arrays.

Step 3 − Create an empty matrix with a same number of rows and columns.

Step 4 − Run nested for loop to iterate through each element of both matrices.

Step 5 − Multiple the element at [x][z] position of matrix1 with each element of the row of matrix2 and add the values, store the values at [x][y] position of the resultant matrix. This process will continue until the last element of the matrix1

Step 6 − Print the resultant matrix.

Example

Following the Swift program to multiply two matrices using multidimensional arrays.

import Foundation import Glibc var row = 4 var col = 4 var matrix1 : [[Int]] = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] print("Matrix 1:") for x in 0..<row { for y in 0..<col { print(matrix1[x][y], terminator:" ") } print("n") } var matrix2 : [[Int]] = [[1, 0, 0, 1], [2, 0, 0, 2], [3, 0, 0, 3], [4, 0, 0, 4]] print("Matrix 2:") for x in 0..<row { for y in 0..<col { print(matrix2[x][y], terminator:" ") } print("n") } var Mul = Array(repeating: Array(repeating: 0, count: 4), count: 4) for x in 0..<row { for y in 0..<col { for z in 0..<row { Mul[x][y] += matrix1[x][z] * matrix1[z][y] } } } print("Resultant matrix:") for x in 0..<row { for y in 0..<col { print(Mul[x][y], terminator:" ") } print("n") } Output Matrix 1: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 Matrix 2: 1 0 0 1 2 0 0 2 3 0 0 3 4 0 0 4 Resultant matrix: 10 10 10 10 20 20 20 20 30 30 30 30 40 40 40 40

Here in the above code, we create two 4×4 matrices along with values and one empty 4×4 matrix to store the result using multi-dimensional arrays. Now we run nested for loop to iterate through each element of both the matrices. Now we multiply the element of matrix1 at [x][z] position with each element of the row of the matrix2 using the * operator and add the values and store the result at [x][y] position of the resultant matrix. Repeat this process for all the elements of matrix1.

Conclusion

Therefore, this is how we can multiply the matrix using multi-dimensional arrays. You can also create any size of matrices like 4×4, 6×3, and 2×3 using a multi-dimensional array and can able to perform multiplication on them.

Haskell Program To Initialize And Print A Complex Number

This tutorial will help us in initializing and printing a complex number. In Haskell, the Data.Complex library provides a Complex type to represent complex numbers.

Method 1: Using Complex data type

This method defines a Complex data type that holds the real and imaginary parts of a complex number, and an instance of the Show type class for Complex, which allows it to be printed using the putStrLn function.

In the main function, it creates a complex number object with real part and imaginary part. Then it prints the complex number using the putStrLn function and the show function.

Algorithm

Step 1 − Complex data type is defined, that will hold the real and imaginary parts of the complex number.

Step 2 − Show instance is defined to represent the complex number.

Step 3 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do.

Step 4 − A variable named, “c” is being initialized. It will have the real and imaginary number value that is to be represented as a complex number.

Step 5 − Final resultant complex number value is displayed by using ‘putStrLn’ statement.

Example

Program to initialize and print a complex number by using Complex data type.

data Complex = Complex { real :: Double, imag :: Double } instance Show Complex where show (Complex r i) = (show r) ++ " + " ++ (show i) ++ "i" main :: IO () main = do let c = Complex { real = 3.0, imag = 4.0 } putStrLn $ "The complex number is: " ++ (show c) Output The complex number is: 3.0 + 4.0i Method 2: Using a custom data type with a constructor and type class

In this method, a custom data type Complex is defined with a constructor that takes in two double values, representing the real and imaginary parts of the complex number. The ComplexNumber type class is defined which has 3 functions real, imag and toString to access the real and imaginary parts and to convert it to string. An instance of the ComplexNumber type class is defined for the Complex data type. The putStrLn function is used to print the complex number using the toString function.

Algorithm

Step 1 − Custom data type, Complex is defined to hold the real and imaginary parts.

Step 2 − ComplexNumber type class is defined which has 3 functions real, imag and toString to access the real and imaginary parts and to convert it to string.

Step 3 − An instance of the ComplexNumber type class is defined for the Complex data type using above three functions.

Step 4 − Program execution will be started from main function. The main() function has whole control of the program.

Step 5 − A variable named, “c” is being initialized. It will have the real and imaginary number value that is to be represented in the form of a complex number.

Step 6 − Final resultant complex number value is displayed by using ‘putStrLn’ statement.

Example 1

Program to initialize and print a complex number using a custom data type with constructor and type class.

data Complex = Complex Double Double deriving Eq class ComplexNumber a where instance ComplexNumber Complex where real (Complex r _) = r imag (Complex _ i) = i toString c = (show $ real c) ++ " + " ++ (show $ imag c) ++ "i" main :: IO () main = do let c = Complex 3.0 4.0 putStrLn $ "The complex number is: " ++ (toString c) Output The complex number is: 3.0 + 4.0i  Example 2

In this example, a tuple is used to represent a complex number, with the first element being the real part and the second element being the imaginary part. The putStrLn function is used to print the complex number, which is automatically converted to a string using the show function.

type Complex = (Double, Double) main :: IO () main = do let c = (3.0, 4.0) putStrLn $ "The complex number is: " ++ (show c) Output The complex number is: (3.0,4.0) Conclusion

In Haskell, the number can be initialized and printed as a complex number by various methods including Complex data type, Custom data type with constructor and type class or by using tuple, etc.

In every approach, the real and imaginary parts are passed that needs to be represented in the form of complex number.

Golang Program To Print First Letter Of Each Word Using Regex

A string of characters known as a regular expression (regex or regexp) creates a search pattern. Regular expressions are frequently employed to carry out string matching, sometimes known as “find and replace,” or pattern matching with strings. Input validation, parsing, and other tasks are also possible with them. Regular expressions use special characters and metacharacters to specify the pattern to be matched, and their syntax differs widely between computer languages. Let’s see different Golang examples to get a clear view of the concept.

Method 1: Using regex.MustCompile() function

In this example, we will see how to print first letter of each word using regex.MustCompile() chúng tôi program creates a regular expression that matches the initial letter of each word using the regexp library. The input string is searched for every instance of the regular expression that matches it using the FindAllString method, and the resulting slice of strings is reported to the console. Let’s go through the Example: and algorithm to get a clear understanding of the concept.

Syntax regex.MustCompile()

The Go standard library’s regexp package contains a function called MustCompile() that converts a regular expression pattern into a regexp. struct with regex. Then, using functions like FindAllString(), FindString(), and ReplaceAllString, this struct may be used to compare against other strings (). A convenience function, MustCompile() panics if the expression cannot be parsed and wraps the Compile() function.

Algorithm

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

Step 2 − Create a function main and in that function create a regular expression object that matches the initial letter of each word by using the regexp.MustCompile function.

Step 3 − To discover every instance of the regular expression in the input string, use the FindAllString function on the regular expression object.

Step 4 − Put the FindAllString function’s output in a variable named print_firstletter.

Step 5 − To print the resulting slice of strings to the console, use the fmt.Println method.

Step 6 − This algorithm prints out all words that match the input string’s first letter using regular expressions.

Example package main import ( "fmt" "regexp" ) func main() { mystr := "Hello, alexa!" fmt.Println("The inital value of string is:", mystr) reg := regexp.MustCompile("b[a-zA-Z]") print_firstletter := reg.FindAllString(mystr, -1) fmt.Println("The first letter of each word is:") fmt.Println(print_firstletter) } Output The inital value of string is: Hello, alexa! The first letter of each word is: [] Method 2: Using strings.Field() function

In this method, we use the fields function, the input string is divided into a word-by-word iteration using a for loop. It uses string indexing to print the first letter of each word inside the loop. Let’s go through the Example: and algorithm to see its execution.

Syntax strings.Fields()

The Golang function fields() is used to slice a string into many substrings based on whitespace. All of the substrings of the original text that are separated by whitespace characters are included in the slice that this method returns (spaces, tabs, and newlines). This action does not change the original string.

Algorithm

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

Step 2 − Create a function main and in that function create a string variable that holds the input value named mystr.

Step 3 − Use the strings.Fields() to slice the input string into words and to iterate over the words use a for loop.

Step 4 − Use string indexing within the loop to retrieve the current word’s initial letter.

Step 5 − Print the word’s first letter using the fmt.Println() function where ln means new line.

Step 6 − For each word, follow steps 4-6 once again.

Step 7 − This algorithm loops through the words in the input string and prints the initial letter of each word after each iteration. It is more memory-efficient and does not employ regular expressions.

Example

In this example we will learn how to print first letter of each word using strings.Field() function.

package main import ( "fmt" "strings" ) func main() { mystr := "Hello, alexa!" fmt.Println("The string created here is:", mystr) words := strings.Fields(mystr) fmt.Println("The initial character of the mystr is:") for _, word := range words { fmt.Print(string(word[0])) } } Output The string created here is: Hello, alexa! The initial character of the mystr is: Ha Conclusion

We executed the above program of printing the first character of each word using two examples. In the first example we used regex.MustCompile function and in the second example we used strings.Fields() function. Both the programs give similar output.

How To Dismiss Viewcontroller In Swift?

In Swift, we have a dismiss method of the class UIViewController that can be used to dismiss a ViewController in Swift. In this method, a Boolean value is used as an argument. There is an argument in this argument that asks whether the dismissed controller should be animated. By default, this is true in this method.

The following example shows how to dismiss a UIViewController screen in Swift.

First view controller setup import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() initialSetup() } private func initialSetup() { view.backgroundColor = .white navigationItem.title = "First Controller" } let secondController = SecondViewController() self.present(secondController, animated: true) } }

In the above code, we added a button to the controller’s view to present the target controller. We applied some basic customization to the button to give it a better look. After customization, we added some required constraints to the button.

Second View Controller Setup

In this step, we will set up the second view controller with a basic user interface. In this controller, we will add a button in the center to dismiss the controller (self).

import UIKit class SecondViewController: UIViewController { private let backButton = UIButton() override func viewDidLoad() { super.viewDidLoad() initialSetup() } private func initialSetup() { view.backgroundColor = .white navigationItem.title = "Second Controller" backButton.backgroundColor = .darkGray backButton.setTitle("Dismiss", for: .normal) backButton.setTitleColor(.white, for: .normal) backButton.layer.cornerRadius = 8 backButton.addTarget(self, action: #selector(handleBackButtonTapped), for: .touchUpInside) view.addSubview(backButton) backButton.translatesAutoresizingMaskIntoConstraints = false backButton.heightAnchor.constraint(equalToConstant: 50).isActive = true backButton.widthAnchor.constraint(equalToConstant: 200).isActive = true backButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true backButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } @objc private func handleBackButtonTapped() { self.dismiss(animated: true) } }

The dismiss method is used to dismiss a presented view controller and navigate back to the presented view controller. When dismissing a view controller, you can specify whether the dismissal should be animated and provide a completion block that is executed after the dismissal is completed.

Output Conclusion

The dismiss method takes two parameters

animated − A boolean value that determines whether the dismissal should be animated.

completion − An optional closure that is called after the dismissal has been completed.

By passing true to the animated parameter, you are asking the parent view controller to animate the dismissal of the child view controller. The completion parameter is optional and can be used to perform additional tasks after the dismissal has been completed.

Update the detailed information about Swift Program To Print Hollow Rectangle Star Pattern on the Moimoishop.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!