Trending December 2023 # Golang Program To Print Right Triangle Star Pattern # Suggested January 2024 # Top 16 Popular

You are reading the article Golang Program To Print Right Triangle Star Pattern updated in December 2023 on the website Bellydancehcm.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 Print Right Triangle Star Pattern

In this tutorial we will write a Go-lang code to print a right Triangle star pattern. We will depict how you can print the star pattern in go language.

* * * * * * * * * * How to print a star pattern?

A right triangle star pattern is shown above, and in that pattern, you can see that stars are increasing with the increase in the number of rows. The pattern goes like this 1 star in first row, 2 stars in second row, and goes on.

For loop statement(s); } Example1: Golang Program To print Right Angled Star Pattern Algorithm

Step 1 − Import the package fmt.

Step 2 − Start function main().

Step 3 − Declare and initialize the integer variables.

Step 4 − Use the first for loop to iterate through the row from 1 to “number of rows”.

Step 5 − Use the second for loop to iterate through columns from 1 to i, to print a star pattern.

Step 5 − After printing all columns of a row move to next line i.e., print new line.

Example

The golang program to print a right triangle star pattern is compiled and executed in the following code −

package

main

import

“fmt”

func

main

(

)

{

var

i

,

j

,

row

int

row

=

5

fmt

.

Println

(

“nRight Angled Star Pattern”

)

for

i

=

1

;

i

<=

row

;

i

++

{

for

j

=

1

;

j

<=

i

;

j

++

{

fmt

.

Print

(

“* “

)

}

fmt

.

Println

(

)

}

}

Output Right Angled Star Pattern * * * * * * * * * * * * * * * Description of the Code

In the above code first we import the main package and the fmt package the fmt package allows us to print anything on the screen.

Then start the main() function.

Declare and initialize i, j and row variables of data type int.

Let us assign 5 to the number of rows i.e for the sake of this example let us print a star pattern with 5 number of rows.

i and j are used to iterate over the for loop. They will select the respective rows and columns for printing the * character.

To print this kind of pattern we need to use a for loop within another for loop. The first for loop is used to select the row, it iterates from 1 to the number that the rows contained by row variable.

The second for loop starts from j = 1 to the value of current row. The value of current row is the value of i variable.

Use the fmt.Print() function to print the * character inside second for loop.

For the first row second for loop will not start and one * character will get printed.

For the second row i = 2 and in this case the second for loop will iterate from j = 1 to j = 2 in this manner in second row two * characters will get printed.

In this manner the right triangle pattern will get printed.

Example 2: Golang Program to Print Right Triangle Star pattern using Recursion Algorithm

Step 1 − Import the package fmt

Step 2 − Define a printSpace() function.

Step 3 − Define a printRow() function to print rows of star pattern recursively.

Step 4 − Define a Star() function to print new line recursively.

Step 5 − Declare and initialize the integer variables.

Step 6 − Call the printRow() function.

Example

package

main

import

“fmt”

func

printRow

(

number

int

)

{

printRow

(

number

1

)

fmt

.

Printf

(

“*”

)

}

}

func

star

(

number

int

)

{

star

(

number

1

)

}

printRow

(

number

)

fmt

.

Println

(

)

}

func

main

(

)

{

var

row

int

=

7

star

(

row

)

}

Output * ** *** **** ***** ****** ******* Description of the Code

In the above code first we import the main package and the fmt package the fmt package allows us to print anything on the screen.

Create two functions naming printRow() and star().

printRow() function will print the star character in the selected number of rows.

Star() function will print new line and will call printRow() function to print * in the selected row.

Then start the main() function.

Initialize row variables of data type int and store number of rows that you want to print in star pattern to it.

Call the star() function and pass row variable as argument to it.

Conclusion

We have successfully compiled and executed a go language program to print a right-angled star pattern.

To print this star pattern, we have used recursion here in which we are calling two functions recursively.

You're reading Golang Program To Print Right Triangle Star Pattern

Swift Program To Print Half Diamond Star Pattern

This tutorial will discuss how to write swift program to print half diamond 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.

Create a half diamond star pattern, we can use any of the following methods −

Using nested for loop

Using init() Function

Using stride Function

Below is a demonstration of the same −

Input

Suppose our given input is −

Num = 7

Output

The desired output would be −

* ** *** **** ***** ****** ******* ****** ***** **** *** ** * Method 1 – Using Nested For Loop

We can create a half diamond 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 for “*”.

Algorithm

Following is the algorithm −

Step 1 − Declare variable to store the height of the half diamond star pattern

For upper half diamond star pattern −

Step 2 − Run an outer for loop from 1 to num. This loop handle the total number of rows are going to print and each row is start with new line.

Step 3 − Run nested for loop from 1 to i. This loop is used print upper half diamond star pattern.

For lower half diamond star pattern −

Step 4 − Again run an outer for loop from 1 to num-1. This loop handle the total number of rows are going to print and each row is start with new line.

Step 5 − Run another nested for loop from 1 to num-j. This loop is used print lower half diamond star pattern.

Example

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

import

Glibc

let

num

=

9

for

i

in

1.

.

.

num

{

for

_

in

1.

.

.

i

{

print

(

“*”

,

terminator

:

“”

)

}

print

(

“”

)

}

for

j

in

1.

.

.

num

1

{

for

_

in

1.

.

.

num

j

{

print

(

“*”

,

terminator

:

“”

)

}

print

(

“”

)

}

Output * ** *** **** ***** ****** ******* ******** ********* ******** ******* ****** ***** **** *** ** *

Method 2 – Using init() Function

Swift provide an in-built function named String.init(). Using this function, we can able to create any pattern. String.init() function create a string in which the given character is repeated the specified number of times.

Syntax

Following is the syntax −

String.init(repeating:Character, count: Int)

Here, repeating represent the character which this method repeats and count represent the total number of time the given character repeat in the resultant string.

Algorithm

Following is the algorithm −

Step 1 − Declare variable to store the length of the half diamond star pattern.

Step 2 − Run a for loop from 1 to num. This loop prints the upper hand diamond star pattern using init() function −

for x in 1...num{ print(String.init(repeating: "*", count: x)) }

Here, in each iteration init() function print “*” according to the value of x. For example if x = 2, then init() prints “**”.

Step 3 − Run another for loop from 1 to num-1. This loop prints the lower half diamond star pattern using init() function −

for x in 1...num-1{ print(String.init(repeating: "*", count: num-x)) } Example

The following program shows how to print half diamond star pattern using string.init() function.

import

Glibc

let

num

=

9

for

x

in

1.

.

.

num

{

print

(

String

.

init

(

repeating

:

“*”

,

count

:

x

)

)

}

for

x

in

1.

.

.

num

1

{

print

(

String

.

init

(

repeating

:

“*”

,

count

:

num

x

)

)

}

Output * ** *** **** ***** ****** ******* ******** ********* ******** ******* ****** ***** **** *** ** * Method 3 – 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 half diamond star pattern using stride() function.

import

Glibc

let

num

=

9

for

i

in

1.

.

.

num

{

for

_

in

1.

.

.

i

{

print

(

“*”

,

terminator

:

“”

)

}

print

(

” “

)

}

for

j

in

1.

.

.

num

1

{

for

_

in

stride

(

from

:

num

,

to

:

j

,

by

:

1

)

{

print

(

“*”

,

terminator

:

“”

)

}

print

(

” “

)

}

Output * ** *** **** ***** ****** ******* ******** ********* ******** ******* ****** ***** **** *** ** *

Golang Program To Convert Numeric Data To Hexadecimal

Example 1: Golang Program Code to Convert Data to Hexadecimal Number Using fmt.Sprintf() Function Syntax func Sprintf(format string, a ...interface{}) string

The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. This function is defined under the fmt package.

This function accepts two parameters format string and a…interface {} and it returns the resulting string.

Algorithm

Step 1 − Import the package fmt.

Step 2 − Start function main ().

Step 3 − Declare and initialize the integer variable.

Step 4 − Calculate the hexadecimal value by calling the function fmt.Sprintf().

Step 5 − Print the result using fmt.Printf().

Example

package

main

import

“fmt”

func

main

(

)

{

fmt

.

Println

(

“Golang Program to convert data to hexadecimal”

)

int_value

:

=

321

hex_value

:

=

fmt

.

Sprintf

(

“%x”

,

int_value

)

fmt

.

Printf

(

“Hex value of %d is = %sn”

,

int_value

,

hex_value

)

hex_value

=

fmt

.

Sprintf

(

“%X”

,

int_value

)

fmt

.

Printf

(

“Hex value of %d is = %sn”

,

int_value

,

hex_value

)

int_value

=

6987

hex_value

=

fmt

.

Sprintf

(

“%x”

,

int_value

)

fmt

.

Printf

(

“Hex value of %d is = %sn”

,

int_value

,

hex_value

)

hex_value

=

fmt

.

Sprintf

(

“%X”

,

int_value

)

fmt

.

Printf

(

“Hex value of %d is = %sn”

,

int_value

,

hex_value

)

}

Output Golang Program to convert data to hexadecimal Hex value of 321 is = 141 Hex value of 321 is = 141 Hex value of 6987 is = 1b4b Hex value of 6987 is = 1B4B Description of the Code

In the above program, we first declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file.

We imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

Declare the integer variable and initialize the variable ‘value’ to an integer value you want to convert to hexadecimal.

Next we call the function fmt.Sprintf() which formats according to a format specifier and returns the resulting string.

When we use %x in fmt.Sprintf(), the result is printed in the lowercase and when we use %X in fmt.Sprintf(), the result is printed in the uppercase.

Finally print the result on the screen using fmt.Printf() which formats according to a format specifier and writes to standard output.

Example 2: Golang Program Code to convert data to Hexadecimal Number using strconv.FormatInt() Function which is Defined in strconv Package Syntax func FormatInt (i int64, base int) string

The range expression is evaluated once before the starting of the loop.

Algorithm

Step 1 − Import the package fmt and package strconv

Step 2 − Start the main () function

Step 3 − Declare and initialize the integer variable

Step 4 − calculate the hexadecimal value by calling the strconv.FormatInt() function

Step 5 − Print the result using fmt.Println().

Example

package

main

import

(

“fmt”

“strconv”

)

func

main

(

)

{

fmt

.

Println

(

“Golang Program to convert data to hexadecimal”

)

var

num int64

num

=

11

hex_num

:

=

strconv

.

FormatInt

(

num

,

16

)

fmt

.

Printf

(

“hexadecimal num of %d is %s”

,

num

,

hex_num

)

num

=

500

hex_num

=

strconv

.

FormatInt

(

num

,

16

)

fmt

.

Printf

(

“nhexadecimal num of %d is %s”

,

num

,

hex_num

)

}

Output Golang Program to convert data to hexadecimal hexadecimal num of 11 is b hexadecimal num of 500 is 1f4 Description of the Code

In the above program, we first declare the package main

We imported the fmt package that includes the files of package fmt and strconv package which implements conversions to and from string representations of basic data types.

Declare the integer variable num and initialize it to the value whose hexadecimal number you need to find.

Next we calculate the hexadecimal value by calling the strconv.FormatInt () function. FormatInt function converts values to strings and returns the string representation of the num variable.

Finally the result is printed on the screen using fmt.Println() function which formats using the default formats for its operands and writes to standard output.

Conclusion

We have successfully compiled and executed the Golang program code to convert data to hexadecimal in the above two examples.

Golang Program To Check If A String Contains A Substring

A substring is a small string in a string and 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.

Syntax strings.Contains(str,substring string)

To determine whether a string contains a particular substring, use the Contains(s, substr string) bool function. If the substring is found in the supplied string, a boolean value indicating its presence is returned.

strings.Index(str, substring string)

The int function index(s, str string) is used to determine the index of the first instance of a specified substring within a given string. It returns either -1 if the substring is missing or the index of the substring within the string.

strings.Index(str, substring string)

The int function index(s, str string) is used to determine the index of the first instance of a specified substring within a given string. It returns either -1 if the substring is missing or the index of the substring within the string.

Algorithm

Step 1 − Create a package main and declare fmt(format package) and strings package

Step 2 − Create a function main and in that function create a string mystr

Step  3 − Using the string function, check whether the string contains the substring or not

Step 4 − Print the output

Example 1

In this example we will see how to check if a string contains a substring using a built-in function strings.Contains(). The output will be a Boolean value printed on the console. Let’s see through the code and algorithm to get the concept easily.

package main import ( "fmt" "strings" ) func main() { mystr := "Hello,alexa!" fmt.Println("The string created here is:", mystr) substring := "alexa" fmt.Println("The substring from the string is:", substring) fmt.Println("Whether the substring is present in string or not?") fmt.Println(strings.Contains(mystr, substring)) } Output The string created here is: Hello,alexa! The substring from the string is: alexa Whether the substring is present in string or not? true Example 2

In this example, we will see how to check if a string contains a substring or not using strings.Index() function.

package main import ( "fmt" "strings" ) func main() { mystr := "Hello, alexa!" fmt.Println("The string created here is:", mystr) substring := "alexa" fmt.Println("The substring from the string is:", substring) fmt.Println("Whether the string contains the substring or not?") fmt.Println("The string contains the substring.") } else { fmt.Println("The string does not contain the substring.") } } Output The string created here is: Hello, alexa! The substring from the string is: alexa Whether the string contains the substring or not? The string contains the substring. Example 3

In this example we will see how to find if a string contains a substring using for loop in strings.Index() function −

package main import ( "fmt" "strings" ) func main() { mystr := "Hello, alexa!" fmt.Println("The string created here is:", mystr) substring := "alexa" fmt.Println("The substring present here is:", substring) fmt.Println("Whether the substring is present in string or not?") found := false for i := 0; i < len(mystr); i++ { if strings.Index(mystr[i:], substring) == 0 { found = true break } } if found { fmt.Println("The string has substring in it.") } else { fmt.Println("The string does not have substring in it.") } } Output The string created here is: Hello, alexa! The substring present here is: alexa Whether the substring is present in string or not? The string has substring in it. Conclusion

We executed the program of checking if a string contains a substring or not using three examples. In the first example we used strings.Contains() function, in the second example we used strings.Index() function and in the third example we used for loop with the former built-in function.

Golang Program To Check A Value Exists In The Hash Collection Or Not

In golang we can check whether a given value exist in hash collection or not by simply using okidiom function or we can even create an if-else user-defined function to do the same. Hashmap is basically a collection of values paired with their keys in hash collection. In this article we are going to look over two different example to understand how we can use the above two techniques to check the given value in hash collection.

Algorithm

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

Create a hashmap using map literal where keys are of type string and values are of type int.

Assign the desired values to the keys.

In this step, use ok idiom to check if a particular mentioned key exists in the map, and if it exists its corresponding value can also be obtained.

Then, if the value exists in the map, ok will be set to true and the success statement is printed.

If value doesn’t exist, ok will be set to false and the failure statement will be printed.

The print statement is executed using Println() function from fmt package where ln means new line.

Example 1

In this example, we will create a hashmap with the help of map literal. Then, with the help of ok idiom we will see if the key exists and if the key exists, does the corresponding value to it exists? If the output is true and success statement is printed else failure statement is printed.

package main import "fmt" func main() { hashmap := map[string]int{ "pencil": 10, "pen": 20, "scale": 15, } fmt.Println("Whether the value exists in the map?") if _, ok := hashmap["pencil"]; ok { fmt.Println("The value exists in the hash collection.") } else { fmt.Println("The value does not exist in the hash collection.") } } Output Whether the value exists in the map? The value exists in the hash collection. Example 2

In this example, we will create a hashmap and iterate it to check if the value exists in it by using conditional if-else statement, if the condition is satisfied the success statement is printed and returned otherwise failure statement is printed.

package main import ( "fmt" ) func main() { hashmap := map[string]string{ "item1": "value1", "item2": "value2", "item3": "value3", } fmt.Println("Whether the value exists in the map?") value := "value2" for _, v := range hashmap { if v == value { fmt.Println("Value exists in the hash collection") return } } fmt.Println("Value does not exist in the hash collection") } Output Whether the value exists in the map? Value exists in the hash collection Conclusion

We executed this program of checking if the value exists int eh hash collection or not using two examples. In the first example we used ok idiom which further directed to true or false indicating the value exists or not whereas in the second example we used conditional statement to execute the program.

Golang To Remove Null From A Slice

In this article, we will learn how to remove a null value from a slice using a variety of examples. A slice is a sequence of elements just like an array. An array is a fixed sequence of elements whereas a slice is a dynamic array, meaning its value is not fixed and can be changed. Slices are more efficient and faster than arrays moreover; they are passed by reference instead of value. Let us learn through examples how it can be executed.

Method 1: Using For Loop

In this method, we will see how to remove a null value from a slice using a for loop in an external function. Let’s see through the algorithm and the code how it’s being done.

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

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

Algorithm

Step 1 − Create a package main and 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 that function create a slice with some values inside that slice including null values.

Step 3 − Create a function named removenullvalue with a slice as a parameter inside it.

Step 4 − Create an empty slice called result and this result will be used to append the non-nil elements inside it.

Step 5 − Run a loop till the length of the slice and in every iteration check if the element of slice is not equal to null append those elements inside the result and move to next iteration.

Step 6 − After the loop terminates return the output slice to the function.

Step 7 − The output slice will be printed on the console using fmt.Println() function where ln means new line.

Example

Golang program to remove null from a slice using for loop in the example.

package main import "fmt" func removenullvalue(slice []interface{}) []interface{} { var output []interface{} for _, element := range slice { if element != nil { output = append(output, element) } } return output } func main() { slice := []interface{}{10, 20, nil, 30, nil, 40} fmt.Println("The original slice is:", slice) slice = removenullvalue(slice) fmt.Println("The slice after removal of null value is:") fmt.Println(slice) } Output The original slice is: [10 20 30 40] The slice after removal of null value is: [10 20 30 40] Method 2: Using a Filter

In this example, we will see how to remove a null value from a slice using a for loop in an external function. Let’s see through the algorithm and the code how it’s being done.

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

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

Algorithm

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

Step 2 − Create main function and in that function create a slice with non-nil and nil values.

Step 3 − Call a function named removenullelement with a slice as a parameter inside it.

Step 4 − In the removenullelement function call the filter function with slice and filter as inputs in it.

Step 5 − Inside the filter function, create an empty slice named output that will be used to append the elements of slice.

Step 6 − Run a loop until the length of slice and the filter function will return a new slice that satisfy the filter.

Step 7 − The returned slice will be obtained by removenullelement function which will use the filter function to remove all nil values from the slices and return it back to main function.

Step 8 − The new slice will be printed on the console using fmt.Println() function where ln means new line.

Example

Golang program to remove null from a slice using filter in the example.

package main import "fmt" func removenullelement(slice []interface{}) []interface{} { return filter(slice, func(i interface{}) bool { return i != nil }) } func filter(slice []interface{}, f func(interface{}) bool) []interface{} { var output []interface{} for _, element := range slice { if f(element) { output = append(output, element) } } return output } func main() { slice := []interface{}{1, 2, nil, 3, nil, 4} fmt.Println("The original slice is:", slice) slice = removenullelement(slice) fmt.Println("The slice after removing null element is:") fmt.Println(slice) } Output The original slice is: [1 2 3 4] The slice after removing null element is: [1 2 3 4] Conclusion

We executed this program of removing the nil elements from the slice using two examples. In the first method, we used for loop to remove nil elements, and in the second method; we used a filter method to remove the null values. Both examples give similar results.

Update the detailed information about Golang Program To Print Right Triangle Star Pattern on the Bellydancehcm.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!