You are reading the article Golang Program To Check Whether The Given String Is Pangram updated in December 2023 on the website Tai-facebook.edu.vn. 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 Check Whether The Given String Is Pangram
In this article, we will understand different golang examples to check whether a given string is pangram. A statement known as a pangram uses each letter of the alphabet at least once. A pangram is a string in the programming language Golang that contains every letter of the alphabet, regardless of case.
Syntax strings.ToLower(str)Using strings in Go (golang), you can change a string’s case to lowercase. The strings package’s ToLower() function.
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
Method 1: Using a MapIn this method, we are going to use map to check Whether the Given String is Pangram. Along with that we are going to use internal function like ToLower and Make functions.
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 isPangram and inside that function use the method ToLower() to change the given string’s case to lowercase using
Step 3 − To store the frequency of each letter in the string, create a map using make function.
Step 4 − Go through the string’s characters one at a time.
Step 5 − Increase the character’s frequency in the map if it is a letter and repeat this process for each letter (from “a” to “z”) in the alphabet.
Step 6 − Verify if the current letter on the map has a frequency greater than zero and return false if any letter’s frequency is zero.
Step 7 − Return true if the sum of all letter frequencies is greater than zero.
Step 8 − By counting the frequency of each letter and determining if it is greater than zero, this algorithm determines whether every letter of the alphabet is present in the string. The string is regarded as a pangram if every letter has a positive frequency.
ExampleIn this example, we will see how to check whether a given string is pangram using map
package main import ( "fmt" "strings" ) func isPangram(str string) bool { str = strings.ToLower(str) m := make(map[rune]int) for _, c := range str { m[c]++ } } for i := 'a'; i <= 'z'; i++ { if m[i] == 0 { return false } } return true } func main() { str := "I am a frontend developer" fmt.Println("The pangram is checked as:") if isPangram(str) { fmt.Println(str, "is a pangram") } else { fmt.Println(str, "is not a pangram") } } Output The pangram is checked as: I am a frontend developer is not a pangram Method 2: Using a SetIn this method, we are going to use set to check Whether the Given String is Pangram.
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 isPangram and inside that function to store the string’s unique characters, create a set.
Step 3 − Use the strings.ToLower() to change the given string’s case to lowercase.
Step 4 − Go through the string’s characters one at a time.
Step 5 − Add the character to the set if it is a letter and verify that the set is 26 pieces long.
Step 6 − Return true if there are 26 distinct characters in the set and return false if there are fewer than 26 unique characters in the set.
Step 7 − By adding unique characters to a set and determining whether the set’s length is 26, this algorithm determines whether every letter of the alphabet is included in the string. If it is, true is returned; otherwise, false. If every letter of the alphabet is included in the string, there will be 26 different characters in the set.
ExampleIn this example, we will check whether the given string is pangram using a set
package main import ( "fmt" "strings" ) func isPangram(str string) bool { set_create := make(map[rune]bool) str = strings.ToLower(str) for _, c := range str { set_create[c] = true } } return len(set_create) == 26 } func main() { str := "I am a frontend developer" if isPangram(str) { fmt.Println(str, "is a pangram") } else { fmt.Println(str, "is not a pangram") } } Output I am a frontend developer is not a pangram ConclusionWe executed the program of checking whether a given string is pangram using two examples. In the first example, we used map and in the second example, we used set to execute the program.
You're reading Golang Program To Check Whether The Given String Is Pangram
Golang Program To Find The Current Working Directory
In go language we can use the functions present in os package like Getwd() and Args to find the current directory in which our code is getting executed.
The directory from which the program is currently being run is called the current directory. It is also known as present working directory.
The directory in which the program is currently running is called the working directory. It is the parent directory for any files or the or directory that are created during runtime.
Algorithm
First, we need to import the “fmt” and “os” packages.
Then, start the main() function. Inside the main() call the required method present in the respective package.
Check if there is an error by checking if “err” is not nil
If there is an error, print the error and stop the further execution of the program.
If there is no error, print the current working directory, which is stored in the “dir” variable.
Syntax funcGetwd() (dir string, err error)The Getwd() function is present in os package and is used to get the rooted path of a particular directory. The function returns two values. One is the string variable containing the path length of directory and other is the error message. The error is not null if there is some problem in getting the required result.
funcDir(path string) stringThe Dir() function is present in the filepath package and is used to return all the elements of the specified path except the last element. The function accepts one argument which is the path length of the directory and returns all the elements of the specified path except the last element.
funcAbs(path string) (string, error)The Abs() function is present in path package and is used to return an absolute representation of specified path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The function accepts the specified path as an argument and returns the absolute representation of the specified path along with the error.
Example 1In this Example we will write a go language program to find the current working directory by using the Getwd() function present in os package.
package main import ( "fmt" "os" ) func main() { dir, err := os.Getwd() if err != nil { fmt.Println(err) return } fmt.Println("Current working directory:", dir) } Output Current working directory: C:UsersLENOVODesktopgo Example 2Another way to find the current working directory in Golang is by using the os.Args[0] value. This value represents the name of the executable program. By using this value, we can find the current working directory of the program by removing the program name from the full path of the program.
package main import ( "fmt" "os" "path/filepath" ) func main() { dir := filepath.Dir(os.Args[0]) fmt.Println("Current working directory:", dir) } Output Current working directory: C:UsersLENOVOAppDataLocalTempgo-build3596082773b001exe Example 3We can also use other methods to find the current working directory in Golang by using the chúng tôi and chúng tôi functions from the path/filepath package. The chúng tôi function returns the absolute path of a file, and the chúng tôi function returns the directory of a file. We can use these two functions together to find the current working directory of the Go program.
package main import ( "fmt" "path/filepath" "os" ) func main() { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { fmt.Println(err) return } fmt.Println("Current working directory:", dir) } Output Current directory: C:UsersLENOVOAppDataLocalTempgo-build514274184b001exe ConclusionC++ Program To Find The Arctangent Of The Given Value
The ratios we use the most in trigonometry include sine, cosine, tangent, and a few more. You can calculate these ratios using an angle. If we are aware of the ratio values, we may also calculate the angle using inverse trigonometric functions.
This lesson will show you how to compute the angle using the tangent value, in radians, using C++’s inverse-tangent (arctan) function.
The atan() functionThe angle is calculated using the atan() technique and the inverse trigonometric tangent function. The C++ standard library contains this function. We must import the cmath library before we can utilize this approach. This method returns the angle in radians and takes a tangent value as an argument. The following uses the simple syntax −
SyntaxThe cosine value must be in the range [-infinity to infinity]. The returned value will be in the range $mathrm{[-:frac{pi}{2},frac{pi}{2}]}$ (both included)
Algorithm
Take tangent value x as input
Use atan( x ) to calculate the tan−1(x)
Return result.
Exampleusing
namespace
std
;
float
solve
(
float
x
)
{
float
answer
;
answer
=
atan
(
x
)
;
return
answer
;
}
int
main
(
)
{
float
angle
,
ang_deg
;
angle
=
solve
(
1
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given tangent value 1 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
0
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given tangent value 0 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
999999
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given tangent value 999999 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
angle
=
solve
(
–
999999
)
;
ang_deg
=
angle
*
180
/
3.14159
;
cout
<<
“The angle (in radian) for given tangent value -999999 is: “
<<
angle
<<
” = “
<<
ang_deg
<<
” (in degrees)”
<<
endl
;
}
Output The angle (in radian) for given tangent value 1 is: 0.785398 = 45 (in degrees) The angle (in radian) for given tangent value 0 is: 0 = 0 (in degrees) The angle (in radian) for given tangent value 999999 is: 1.5708 = 90 (in degrees) The angle (in radian) for given tangent value -999999 is: -1.5708 = -90 (in degrees)The atan() method, which receives the tangent value in this case, returns the angle in radian format. We converted this output from radians to degrees using the formula below.
$$mathrm{theta_{deg}:=:theta_{rad}:times:frac{180}{pi}}$$
ConclusionTo perform the inverse trigonometric operation from the cosine value we use the acos() function from the cmath library. This function takes the cosine value as input and returns the given angle in the radian unit. In older versions of C / C++, the return type was double, but later versions in C++ used the overloaded form for float and long-double additionally. While an integer value is passed as an argument, it will cast the input parameter into double and call the acos() method corresponding to the double-type parameter.
Swift Program To Iterate Through Each Character Of The String
In Swift, we can iterate through each character of the string very easily. For the iteration, Swift provides the following methods −
Using for-in loop
Using forEach() function
Using enumerated() function
Method 1: Using for-in loopWe can use a for-in loop for the iteration. It iterates through each character of the string and then performs the expressions given inside the loop body or can display them on the output screen.
Syntax for x in mstr{ }Here mstr is the string and x stores the current character from the string in each iteration.
ExampleIn the following Swift program, we will iterate through each character of the string. So first we will create a string and then we use a for-in loop to iterate through each character and display the output on the output screen.
import Foundation import Glibc let InputString = "This is Swift Tutorial" print("Characters in the current string: (InputString) are:") for char in InputString { print(char) } Output Characters in the current string: This is Swift Tutorial are: T h i s i s S w i f t T u t o r i a l Method 2: Using forEach() methodWe can also use a forEach() method for the iteration. It calls the specified closure on each character of the given string and displays the output.
Syntax mStr.forEach{mBody}Here mStr is the string and mBody is a closure which takes each character from the given string as a parameter and returns the result according to the expression present in the closure.
ExampleIn the following Swift program, we will iterate through each character of the string. So first we will create a string and then we pass a closure in the forEach() method to iterate through each character of the input string and then display the output on the output screen.
import Foundation import Glibc let InputString = "This is Swift 7 Tutorial" print("Characters in the current string: (InputString) are:") InputString.forEach{C in print(C)} Output Characters in the current string: This is Swift 7 Tutorial are: T h i s i s S w i f t 7 T u t o r i a l Method 3: Using enumerated() methodWe can also use an enumerated() method for the iteration. It generally returns a sequence of pairs(m, n), where m represents the index and n represents its associated character. Or we can say that using the enumerated() method you can get the character as well as its associated index value.
Syntax for(idx, char) in mStr.enumerated(){ }Here mStr is the string and mBody is the body of the loop. The idx represents the index and the char represents the current character.
ExampleIn the following Swift program, we will iterate through each character of the string. So first we will create a string and then we use the enumerated() method to iterate through each character and its corresponding index and then display the output.
import Foundation import Glibc let InputString = "Swift Tutorial" print("Characters in the current string: (InputString) are:") for (idx, char) in InputString.enumerated() { print("Character = (char) and index = (idx)") } Output Characters in the current string: Swift Tutorial are: Character = S and index = 0 Character = w and index = 1 Character = i and index = 2 Character = f and index = 3 Character = t and index = 4 Character = and index = 5 Character = T and index = 6 Character = u and index = 7 Character = t and index = 8 Character = o and index = 9 Character = r and index = 10 Character = i and index = 11 Character = a and index = 12 Character = l and index = 13 ConclusionGolang Program To Calculate The Volume And Area Of The Cylinder
In this tutorial, we will be discussing the approach to calculate the volume and area of a cylinder in Golang programming using its height and radius.
But before writing the code for this, let’s briefly discuss the cylinder and its volume and area.
CylinderA cylinder is a three-dimensional figure whose base has a circular shape. The distance between the two bases is known as the cylinder’s height ‘h’ and the radius of the base is denoted by ‘r’. A cold drink can is a good example of a cylinder.
Volume of a cylinderThe capacity of the cylinder is generally termed its volume. Calculating the volume of a cylinder can be beneficial in situations where we want to know the capacity of a bottle or a container.
$$mathrm{Volume , =, pi * left ( r right )^{2} * h}$$
Area of a cylinderThe total area enclosed by the cylinder is known as the surface area of a cylinder.
$$mathrm{Area , =, 2ast pi * r * left ( h+r right )}$$
Example
Height = 7, Radius = 5
Volume of cylinder = 550
Area of cylinder = 377.1428571428571
Explanation
Volume of cylinder = π * (r)2 * h
= (22/7) * 5 * 5 * 7
= 550
Area of cylinder = 2 * π * r * (h + r)
= 2 * (22/7) * 5 * (7 + 5)
= 377.1428571428571
Height = 21, Radius = 10
Volume of cylinder = 6600
Area of cylinder = 1948.5714285714284
Explanation
Volume of cylinder = π * (r)2 * h
= (22/7) * 10 * 10 * 21
= 6600
Area of cylinder = 2 * π * r * (h + r)
= 2 * (22/7) * 10 * (21 + 10)
= 1948.5714285714284
Calculating the volume and area of a cylinder: AlgorithmStep 1 − Declare a variable for storing the height of the cylinder- ‘h’.
Step 2 − Declare a variable for storing the radius of the cylinder- ‘r’.
Step 3 − Declare a variable for storing the area of the cylinder- ‘area’ and declare another variable for storing the volume- ‘volume’ and initialize both the variables with value 0.
Step 4 − Calculate the volume using the formula- Volume = π * (r)2 * h, and store it in the ‘volume’ variable in the function calculateVolumeOfCylinder().
Step 5 − Calculate the area using the formula- Area = 2 * π * r * (h + r), and store it in the ‘area’ variable in the function calculateAreaOfCylinder().
Step 6 − Print the calculated volume and area of the cylinder, i.e, the value stored in the ‘volume’ and ‘area’ variables.
Exampleimport
“fmt”
func
calculateVolumeOfCylinder
(
h
,
r float64
)
float64
{
var
volume float64
=
0
volume
=
(
22.0
/
7.0
)
*
r
*
r
*
h
return
volume
}
func
calculateAreaOfCylinder
(
h
,
r float64
)
float64
{
var
area float64
=
0
area
=
2
*
(
22.0
/
7.0
)
*
r
*
(
h
+
r
)
return
area
}
func
main
(
)
{
var
h float64
=
7
var
r float64
=
5
var
area
,
volume float64
fmt
.
Println
(
“Program to calculate the volume and area of the Cylinder n”
)
volume
=
calculateVolumeOfCylinder
(
h
,
r
)
area
=
calculateAreaOfCylinder
(
h
,
r
)
fmt
.
Println
(
“Height of the cylinder : “
,
h
)
fmt
.
Println
(
“Radius of the cylinder : “
,
r
)
fmt
.
Println
(
“Therefore, Volume of cylinder : “
,
volume
)
fmt
.
Println
(
“Area of cylinder : “
,
area
)
}
Output Program to calculate the volume and area of the Cylinder Height of the cylinder : 7 Radius of the cylinder : 5 Therefore, Volume of cylinder : 550 Area of cylinder : 377.1428571428571 Description of code
var h float64 = 7, var r float64 = 5 − In this line, we are declaring the variables for height ‘h’ and radius ‘r’. As the height and radius will be of data type float, that’s why we are using the float64 data type.
calculateVolumeOfCylinder(h, r float64) float64 − This is the function where we are calculating the volume of the cylinder. The function has the variable ‘h’ and ‘r’ of data type float64 as the parameter and also has a return type of float64.
volume = (22.0 / 7.0) * r * r * h − If we desire the output to be of data type float, we explicitly need to convert the values, that is the reason we are using values 22.0 and 7.0 instead of 22 and 7. Using the above formula, we calculate the volume of the cylinder.
return volume − for returning the volume of the cylinder.
volume = calculateVolumeOfCylinder(h, r) − We are calling the function calculateVolumeOfCylinder() and storing the calculated value in the ‘volume’ variable.
calculateAreaOfCylinder(h, r float64) float64 − This is the function where we are calculating the area of the cylinder. The function has the variable ‘h’ and ‘r’ of data type float64 as the parameter and also has a return type of float64.
area = 2 * (22.0 / 7.0) * r * (h + r) − Since we are desiring the output to be of data type float, we explicitly need to convert the values here as well, that is the reason we are using values 22.0 and 7.0 instead of 22 and 7. Using the above formula, we calculate the area of the cylinder.
return area − for returning the area of the cylinder
area = calculateAreaOfCylinder(h, r) − We are calling the function calculateAreaOfCylinder() and storing the calculated value in the ‘area’ variable.
Therefore, Volume of the cylinder = (22/7) * 5 * 5 * 7
= 550
Area of the cylinder = 2 * (22/7) * 5 * (7 + 5)
= 377.1428571428571
ConclusionThis is all about calculating the volume and area of a cylinder using Go programming. We have also maintained code modularity by using separate functions for calculating the area and volume which also increases the code reusability. You can explore more about Golang programming using these tutorials.
Golang Program To Read And Print Two
What is a 2D array?
A two-dimensional array is a collection of data that are arranged in rows and columns. In go we can use the for loops to iterate and print elements of the 2d arrays.
Here is an example of the same below −
0 1 2 4 5 6 8 9 10 Method 1: Using For LoopsIn this method, we will use for loops in golang to iterate over the arrays and catch each element then we will print that element unless the whole array is iterated upon.
Algorithm
Step 1 − Import the fmt package.
Step 2 − Now we need to start the main() function.
Step 3 − Then create a two-dimensional matrix naming matrix and store data to it.
Step 4 − Now, use two for loops to iterate over the array elements. Using the first for loop will get the row of the multi-dimensional array while the second for loop gives us the column of the two-dimensional array.
Step 5 − Once a particular matrix element is obtained, print that element on the screen and move on to the next element until the loop gets completed.
ExampleIn this example, we will use for loops to read and print the elements of two-dimensional arrays by using for loops.
package main import "fmt" func main() { var array [][]int var row int var col int array = make([][]int, row) for i := range array { array[i] = make([]int, col) } array = [][]int{ {0, 1, 2}, {4, 5, 6}, {8, 9, 10}, } fmt.Println("The given matrix is:") for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { fmt.Print(array[i][j], "t") } fmt.Println() } fmt.Println() } Output The given matrix is: 0 1 2 4 5 6 8 9 10 Method 2: Using Internal FunctionIn this method, we are going to use the range function in the first example and array slicing in the second example.
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 data to it.
Step 4 − Now use the range function to iterate over the matrix elements and print each element of the matrix on the screen.
Example 1In this example, we will use the range function of go Programming to get the elements of two-dimensional arrays with the combination of range function and for loop.
package main import "fmt" func main() { var array [][]int var row int var col int array = make([][]int, row) for i := range array { array[i] = make([]int, col) } array = [][]int{ {10, 13, 21}, {47, 54, 63}, {82, 91, 0}, } fmt.Println("The required array is:") for _, row := range array { for _, val := range row { fmt.Print(val, "t") } fmt.Println() } } Output The required array is: 10 13 21 47 54 63 82 91 0 Example 2In this program, we will print a 2-D array by using the concept of array slicing property of go language.
package main import "fmt" func main() { var array [][]int var row int var col int array = make([][]int, row) for i := range array { array[i] = make([]int, col) } array = [][]int{ {10, 13, 21}, {47, 54, 63}, {82, 91, 0}, } fmt.Println("The required array is:") for _, j := range array { fmt.Print(j, "t") fmt.Println() } fmt.Println() } Output The required array is: [10 13 21] [47 54 63] [82 91 0] Method 3: Using RecursionIn this method, we will use the concept of recursion to read and print the elements of two-dimensional arrays on the screen.
Algorithm
Step 1 − First, we need to import the fmt package.
Step 2 − Now, create a recursive function called printMatrix() that accepts the multidimensional array as argument to it along with the current row index that should be printed.
Step 3 − Now, if the current row variable is equal to the length of the multidimensional array then the program will end.
Step 4 − A for loop is used to iterate over the array and print the current element. Once the current row is printed the function calls itself again by incrementing the row variable.
Step 5 − In this way all the three rows of the array are printed on the screen.
Step 6 − Now, start the main() function. Inside the main() initialize a 2-D array and assign value to it.
Step 7 − Now, call the printMatrix() function by passing the matrix along with the current row position as argument to the function.
ExampleThe following code uses recursion method to to read and print two-dimensional array
package main import "fmt" func printMatrix(matrix [][]int, row int) { if row == len(matrix) { return } for _, element := range matrix[row] { fmt.Print(element, "t") } fmt.Println() printMatrix(matrix, row+1) } func main() { var array [][]int var row int var col int array = make([][]int, row) for i := range array { array[i] = make([]int, col) } array = [][]int{ {12, 13, 21}, {47, 54, 23}, {28, 19, 61}, } fmt.Println("The given matrix is:") printMatrix(array, 0) } Output The given matrix is: 12 13 21 47 54 23 28 19 61 ConclusionWe have successfully compiled and executed a go language program to read and print the elements of multi-dimensional arrays. In the first example we have only used the for loop while in the second example we have used the combination of range function and for loops. In the third example we have used the concept of recursion where we call the function from itself until the execution is completed.
Update the detailed information about Golang Program To Check Whether The Given String Is Pangram on the Tai-facebook.edu.vn 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!