Trending February 2024 # Haskell Program To Check Leap Year # Suggested March 2024 # Top 2 Popular

You are reading the article Haskell Program To Check Leap Year updated in February 2024 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 March 2024 Haskell Program To Check Leap Year

In Haskell, we can check whether a given year is a leap year is not using simple boolean expression. A leap year is a year that has an extra day (February 29th) compared to a normal year.

For example, 2004 is a leap year.

To determine if a year is a leap year or not, there are a few rules that must be followed.

Algorithm

Step 1 − The isLeapYear function is defined

Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. In the main function, a year value is defined and passed to isLeapYear function. The result of the function is then printed.

Step 3 − The variable named, “year” is being initialized. It will hold the year which is to be checked whether it is leap year or not.

Step 4 − Then, if else statement is used to print the result to the console using ‘putStrLn’ statement after the function is called.

Example 1

In this example, the isLeapYear function takes an integer (representing a year) as input and returns a Boolean indicating whether or not the year is a leap year. It uses pattern matching to determine whether the year is a leap year based on the following rules −

If the year is evenly divisible by 400, then it is a leap year.

If the year is evenly divisible by 100 but not by 400, then it is not a leap year.

If the year is evenly divisible by 4 but not by 100, then it is a leap year.

If none of the above conditions are met, then it is not a leap year.

isLeapYear year

main :: IO () main = do let year = 2004 if isLeapYear year then putStrLn $ show year ++ ” is a leap year.” else putStrLn $ show year ++ ” is not a leap year.”

Output 2004 is a leap year. Example 2

In this example, a single Boolean expression is used to determine if the year is a leap year. It checks if the year is evenly divisible by 4 and if it is not evenly divisible by 100 or if it is evenly divisible by 400. This implementation is more concise and uses fewer lines of code. The result is the same as the original implementation, but the logic is expressed more succinctly.

main :: IO () main = do let year = 2004 if isLeapYear year then putStrLn $ show year ++ ” is a leap year.” else putStrLn $ show year ++ ” is not a leap year.”

Output 2004 is a leap year. Conclusion

In Haskell, we can define a function that determines if a year is a leap year or not, using the following rules −

If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.

If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.

If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.

The year is a leap year (it has 366 days).

The year is not a leap year (it has 365 days).

You're reading Haskell Program To Check Leap Year

Haskell Program To Calculate The Area Of Cube

This tutorial will help us in calculating the area of a cube. There are various approaches to calculating the area but the mathematical formula to calculate the area will remain the same I.e., 6*(side^2).

Method 1: Using cubeArea Function

This example defines a function cubeArea that takes a single argument, the length of the cube’s sides, and returns the area of the cube. The main function calls the cubeArea function to calculate the area. The result is then printed to the console.

Algorithm

Step 1 − The function cubeArea is being defined on the basis of simple mathematical formula i.e., 6a^2 as, cubeArea side = 6 * (side ^ 2).

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

Step 3 − A variable named, “side” is being initialized. It will contain the length of the side of the cube.

Step 4 − A variable “area” is initialized to hold the computed area value of the cube and the final resultant area value is displayed by using ‘putStrLn’ statement.

Example

In this example, we are going to calculate the area of Cube by using cubeArea function.

module Main where cubeArea side = 6 * (side ^ 2) main :: IO () main = do let side = 4 let area = cubeArea side putStrLn ("The area of the cube is: " ++ show area) Output The area of the cube is: 96.0 Method 2: Using Data.Fixed

In This method , the Data.Fixed library is used to represent the side length of the cube with a fixed precision. The Fixed E2 type is used to represent a fixed-point decimal with 2 decimal places.

The cubeArea function takes a single argument of type Fixed E2, which represents the length of the cube’s sides. It then calculates the area of the cube by multiplying the side length by 6 and raising it to the power of 2.

Algorithm

Step 1 − Data.Fixed module is imported.

Step 2 − The function cubeArea is being defined by taking a single argument of type Fixed E2, which represents the length of the cube’s sides. It then calculates the area of the cube by multiplying the side length by 6 and raising it to the power of 2.

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, “side” is being initialized. It will contain the length of the side of the cube.

Step 5 − A variable “area” is initialized to hold the computed area value of the cube once the function is called and the final resultant area value is displayed by using ‘putStrLn’ statement.

Example

In this example, we are going to calculate the area of Cube by using Data.Fixed to represent the side length with a fixed precision.

import Data.Fixed cubeArea side = 6 * (side ^ 2) main :: IO () main = do let side = 4 let area = cubeArea side putStrLn ("The area of the cube is: " ++ show area) Output The area of the cube is: 96.00 Method 3: Using Pattern Matching

This method defines a data type Cube using record syntax, which has a single field side with a type of Double.

The cubeArea function takes a single argument of type Cube and uses pattern matching to extract the value of the side field. It then calculates the area of the cube by multiplying the side length by 6 and raising it to the power of 2.

Algorithm

Step 1 − A data type Cube using record syntax is defined.

Step 2 − The cubeArea function is defined by taking a single argument of type Cube and uses pattern matching to extract the value of the side field. It then calculates the area of the cube by multiplying the side length by 6 and raising it to the power of 2.

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

Step 4 − A variable named, “side” is being initialized. It will contain the length of the side of the cube.

Step 5 − A variable “area” is initialized to hold the computed area value of the cube once the function is called and the final resultant area value is displayed by using ‘putStrLn’ statement.

Example

In the following example, we are going to calculate the area of Cube by using pattern matching.

data Cube = Cube { side :: Double } cubeArea (Cube side) = 6 * (side ^ 2) main :: IO () main = do let side = 4 let area = cubeArea (Cube side) putStrLn ("The area of the cube is: " ++ show area) Output The area of the cube is: 96.0 Conclusion

There are different ways to calculate the area of a cube. In Haskell, the area of a cube can be calculated by using cubeArea function, by using Data.Fixed library or by using pattern matching.

Haskell Program To Convert A Number Into A Complex Number

This tutorial will help us in converting a number into a complex number. In Haskell, the Data.Complex library provides a Complex type to represent complex numbers. The :+ operator is used to construct a complex number from its real and imaginary parts.

Method 1: Using convertToComplex Function

In this approach, the convertToComplex function takes a real number as input and returns a complex number with the real component equal to the sum of the input and the predefinedReal value and the imaginary component equal to the predefinedImaginary value. The main function gets a real number and then uses convertToComplex to convert it to a complex number, which is then printed to the screen.

Algorithm

Step 1 − ‘Data.Complex’ module is imported.

Step 2 − Predefined real and imaginary values are defined.

Step 3 − convertToComplex() function is defined using predefined real and imaginary values, as (predefinedReal + real) :+ predefinedImaginary

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

Step 5 − A variable named, “real” is being initialized. It will have the real number value that is to be converted into a complex number.

Step 6 − convertToComplex() function is being called and real value will be passed as parameter to it.

Step 7 − Final resultant converted complex number value is displayed.

Example

In the following example, we are going to learn how to use convertToComplex function to convert a number into complex number

import Data.Complex predefinedReal :: Double predefinedReal = 2.0 predefinedImaginary :: Double predefinedImaginary = 3.0 convertToComplex real = (predefinedReal + real) :+ predefinedImaginary main :: IO () main = do let real = 4.0 let complex = convertToComplex real putStrLn $ "Complex number: " ++ show complex Output Complex number: 6.0 :+ 3.0 Method 2: Using mkPolar Function

This approach uses the mkPolar function from Data.Complex to create a complex number from its magnitude and angle, and then adding the real value to the complex number. The main function gets a real number and then uses convertToComplex to convert it to a complex number, which is then printed to the screen.

Algorithm

Step 1 − ‘Data.Complex’ module is imported.

Step 2 − convertToComplex() function is defined as, mkPolar (sqrt (real^2 + imaginary^2)) (atan2 imaginary real)

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

Step 4 − A variable named, “real” is being initialized. It will have the real number value that is to be converted into a complex number. And a variable named, “imaginary” is being initialized, that will contain the imaginary value.

Step 5 − convertToComplex() function is being called and real & imaginary values will be passed as parameter to it.

Step 6 − Final resultant converted complex number value is displayed.

Example

In the following example, we are going to learn how to use mkPolar function to convert a number into complex number

import Data.Complex convertToComplex real imaginary = mkPolar (sqrt (real^2 + imaginary^2)) (atan2 imaginary real) main :: IO () main = do let real = 4.0 let imaginary = 3.0 let complex = convertToComplex real imaginary putStrLn $ "Complex number: " ++ show complex Output Complex number: 4.0 :+ 3.0 Method 3: Using the :+ operator

In this method, we can use the :+ operator to create a complex number, which takes a real number as the first argument and an imaginary number as the second argument.

Algorithm

Step 1 − ‘Data.Complex’ module is imported.

Step 2 − convertToComplex() function is defined using real and imaginary values, as real :+ imaginary

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 − The variables named, “real” and “imaginary” are being initialized. They will have the real and imaginary number value respectively, that is to be converted into a complex number.

Step 5 − convertToComplex() function is being called and real & imaginary value will be passed as parameter to it.

Step 6 − Final resultant converted complex number value is displayed.

Example

In the following example, we are going to learn how to use :+ operator to convert a number into complex number

import Data.Complex convertToComplex real imaginary = real :+ imaginary main :: IO () main = do let real = 4.0 let imaginary = 3.0 let complex = convertToComplex real imaginary putStrLn $ "Complex number: " ++ show complex Output Complex number: 4.0 :+ 3.0 Conclusion

In Haskell, the number can be converted into complex number by various methods including convertToComplex methods using mkPolar, rectangular functionc, etc.

In every approach, the real number that needs to be converted is passed and once you have entered the real number, it will add the predefined real and imaginary values to the input real number, then the resulting complex number will be printed to the screen in the form of (real :+ imaginary).

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 Map

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

Example

In 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 Set

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

Example

In 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 Conclusion

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

Java Program To Display Name Of The Weekdays In Calendar Year

A week in a calendar year consists of 5 weekdays: Monday, Tuesday, Wednesday, Thursday and Friday; the two remaining days (Saturday and Sunday) make up the weekend. If you’re working with dates and calendars as an application developer, manually looking up names for weekdays in a year can be tedious. In this article we will take a deeper dive into various approaches using built-in classes and APIs with detailed code examples provided for both beginners and experienced Java developers alike – giving valuable techniques for simplifying a calendar-related task i.e. to Display Name of the Weekdays in Calendar Year using Java programming languages. The following are the different types of methods to display names of weekdays −

Naïve Method

Using the java.text.DateFormatSymbols class

Using the java.util.Calendar class

Using the java.time.format.DateTimeFormatter class

Using the chúng tôi and java.text.SimpleDateFormat classes

Approach 1: Naïve Method

This is the simplest approach and requires hardcoding the names of each weekday into an array. We then use for each loop to iterate over this array and display their names.

Example public class Weekdays { public static void main(String[] args) { String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; for (String day : weekdays) { System.out.println(day); } } } Output Monday Tuesday Wednesday Thursday Friday Approach 2: Using the java.text.DateFormatSymbols Class

The Java standard library’s chúng tôi package contains the chúng tôi class, which provides a set of symbols used by SimpleDateFormat to format and parse dates and times according to an established pattern. The DateFormatSymbols class provides methods for retrieving and setting the following date and time symbols −

Month and day names and abbreviations

Day of the week names and abbreviations

Era names

AM/PM strings

Time Zone Names and Abbreviations

DateFormatSymbols by default uses the locale-specific symbols for the current default Locale. However, you can create an instance of DateFormatSymbols with a different Locale or custom symbol arrays for any of the above fields. We will make use of the getWeekdays() function which returns an array of weekday names.

Example import java.text.DateFormatSymbols; public class Weekdays { public static void main(String[] args) { DateFormatSymbols symbols = new DateFormatSymbols(); String[] weekdays = symbols.getWeekdays(); for (int i = 2; i <= 6; i++) { System.out.println(weekdays[i]); } } } Output Monday Tuesday Wednesday Thursday Friday Approach 3: Using the java.util.Calendar Class

The Java standard library’s chúng tôi package contains the chúng tôi class, which provides an intuitive, locale-independent way of working with dates and times.

Calendar is an intuitive system that enables date and time manipulation in various ways. It offers methods for retrieving or setting various fields of a date or time, such as year, month, day, hour, minute, second and millisecond; additionally it permits operations on these values like adding or subtracting seconds.

Calendar is an abstract class, so you cannot create an instance directly. Instead, use the getInstance() static factory method to create an instance based on your current time zone and locale settings. Alternatively, use the getInstance(TimeZone zone, Locale aLocale) method for creating a Calendar instance with specific preferences in regard to these factors.

Calendar offers several useful features, like Time zone support, Leap year support as well as Field normalization.

Example import java.util.Calendar; import java.util.Locale; public class Weekdays { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); for (int i = Calendar.MONDAY; i <= Calendar.FRIDAY; i++) { calendar.set(Calendar.DAY_OF_WEEK, i); String name = calendar.getDisplayName( Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()); System.out.println(name); } } } Output Monday Tuesday Wednesday Thursday Friday Approach 4. Using the java.time.format.DateTimeFormatter Class

The Java 8 Date-Time API, particularly the chúng tôi package, includes a DateTimeFormatter class which offers flexible and thread-safe date/time formatting capabilities.

DateTimeFormatter is an application used for formatting and parsing date and time objects. It offers various options for creating formatters based on various patterns such as date-only, time-only or both. Furthermore, it supports multiple chronologies including both ISO calendar systems and non-ISO calendar systems.

DateTimeFormatter can parse and format localized text, such as month and day names, into pattern letters that represent different fields within a date or time object. It supports certain fields like year, month, day, hour, minute, second (including fractions thereof) in these same pattern letters.

Example import java.time.DayOfWeek; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.util.Locale; public class Weekdays { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE", Locale.getDefault()); int c=0; for (DayOfWeek day : DayOfWeek.values()) { if(c<5) { String name = day.getDisplayName(TextStyle.FULL, Locale.getDefault()); System.out.println(name); c++; } } } } Output Monday Tuesday Wednesday Thursday Friday Approach 5: Using the chúng tôi and java.text.SimpleDateFormat Classes

Java’s standard library provides two classes for working with dates and times: chúng tôi and java.text.SimpleDateFormat.

Java.text.SimpleDateFormat is a class that formats and parses dates and times according to an established pattern. It takes an input string specifying how dates should be formatted or parsed; this format string consists of various pattern letters representing fields within a date or time value such as year, month, day, hour, minute, second, and fraction of second.

SimpleDateFormat is not thread-safe, and its use in a multi-threaded environment is discouraged. Instead, the java.time.format.DateTimeFormatter class should be utilized for formatting and parsing dates and times.

Example import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Weekdays { public static void main(String[] args) { SimpleDateFormat simpleDF = new SimpleDateFormat("EEEE", Locale.getDefault()); for (int i = 6; i <= 10; i++) { Date date = new Date(); date.setDate(i); String name = simpleDF.format(date); System.out.println(name); } } } Output Thursday Friday Saturday Sunday Monday Conclusion

Java offers a wide range of libraries which make displaying weekdays from Monday to Friday of a calendar year easy. A total of six techniques have been demonstrated above, all requiring only minimal modifications if one needs to display even weekend days within that same calendar year.

Program To Convert Hexadecimal To Octal In C Program

Output: Octal Value = 646 Explanation:

Input: 1AA Output: 652

Approach we will be using to solve the given problem −

Taking the input and store it as a string.

Convert the hexadecimal number or expression to binary by following the below approach −

Check for all the 16 cases of hexadecimal by adding their respective binary representation.

Return the result.

Convert the binary number to octal number follow the following steps −

Take the 3 places by comparing all the possible cases of binary number to octal.

Set the value of octal = (val * place) + octal;

Divide binary number by 1000

place *= 10

Return the result.

Algorithm Start    Declare variables binary, place    Declare and initialize i = 0, rem, val    Initialize t n = strlen(hex)    Initialize binary = 0ll and place = 0ll    Loop For i = 0 and hex[i] != '' and i++ {       binary = binary * place;       switch (hex[i]) {          case '0':             binary += 0          case '1':             binary += 1          case '2':             binary += 10          case '3':             binary += 11          case '4':             binary += 100          case '5':             binary += 101          case '6':             binary += 110          case '7':             binary += 111          case '8':             binary += 1000          case '9':             binary += 1001          case 'a':          case 'A':             binary += 1010          case 'b':          case 'B':             binary += 1011          case 'c':          case 'C':             binary += 1100          case 'd':          case 'D':             binary += 1101;             break;          case 'e':          case 'E':             binary += 1110;             break;          case 'f':          case 'F':             binary += 1111;             break;          default:             printf("Invalid hexadecimal input.");       }       place = 10000;    }    return binary; } long long int binary_oct(long long binary) {    long long int octal, place;    int i = 0, rem, val;    octal = 0ll;    place = 0ll;    place = 1;       rem = binary % 1000;       switch (rem) {       case 0:          val = 0;          break;       case 1:          val = 1;          break;       case 10:          val = 2;          break;       case 11:          val = 3;          break;       case 100:          val = 4;          break;       case 101:          val = 5;          break;       case 110:          val = 6;          break;       case 111:          val = 7;          break;       }       octal = (val * place) + octal;       binary /= 1000;       place *= 10;    }    return octal; } long long int hexa_oct(char hex[]) {    long long int octal, binary;    // convert HexaDecimal to Binary    binary = hexa_binary(hex);    // convert Binary to Octal    octal = binary_oct(binary);    return octal; } int main() {    char hex[20] = "1a99";    printf("Octal Value = %lld", hexa_oct(hex));    return 0; long long int hexa_binary(char hex[]) {    long long int binary, place;    int i = 0, rem, val;    int n = strlen(hex);    binary = 0ll;    place = 0ll;    for (i = 0; hex[i] != ''; i++) {       binary = binary * place;       switch (hex[i]) {       case '0':          binary += 0;          break;       case '1':          binary += 1;          break;       case '2':          binary += 10;          break;       case '3':          binary += 11;          break;       case '4':          binary += 100;          break;       case '5':          binary += 101;          break;       case '6':          binary += 110;          break;       case '7':          binary += 111;          break;       case '8':          binary += 1000;          break;       case '9':          binary += 1001;          break;       case 'a':       case 'A':          binary += 1010;          break;       case 'b':       case 'B':          binary += 1011;          break;       case 'c':       case 'C':          binary += 1100;          break;       case 'd':       case 'D':          binary += 1101;          break;       case 'e':       case 'E':          binary += 1110;          break;       case 'f':       case 'F':          binary += 1111;          break;       default:          printf("Invalid hexadecimal input.");       }       place = 10000;    }    return binary; } long long int binary_oct(long long binary) {    long long int octal, place;    int i = 0, rem, val;    octal = 0ll;    place = 0ll;    place = 1;    // giving all binary numbers for octal conversion       rem = binary % 1000;       switch (rem) {       case 0:          val = 0;          break;       case 1:          val = 1;          break;       case 10:          val = 2;          break;       case 11:          val = 3;          break;       case 100:          val = 4;          break;       case 101:          val = 5;          break;       case 110:          val = 6;          break;       case 111:          val = 7;          break;       }       octal = (val * place) + octal;       binary /= 1000;       place *= 10;    }    return octal; } long long int hexa_oct(char hex[]) {    long long int octal, binary;    // convert HexaDecimal to Binary    binary = hexa_binary(hex);    // convert Binary to Octal    octal = binary_oct(binary);    return octal; } int main() {    char hex[20] = "5CD";    printf("Octal Value = %lld", hexa_oct(hex));    return 0; } Output Octal Value = 2715

Update the detailed information about Haskell Program To Check Leap Year 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!