Task 1: Temperature Scale Equal Point
Write a script to find the temperature at which the Fahrenheit and Celsius scales are equal.
Output
The equal point in the Fahrenheit and Celsius scales is -40 °F and -40 °C.
Logic
The conversion formula between Celsius ($C$) and Fahrenheit ($F$) is:
$$C = (F - 32) \times \frac{5}{9}$$
To find where $F = C$, we can solve this algebraically:
$$F = (F - 32) \times \frac{5}{9} \implies 9F = 5F - 160 \implies 4F = -160 \implies F = -40$$
We can also verify this numerically by searching through a range of temperatures from -100 to 212 and testing the condition where $F == C$.
Perl Solution
ch-1.pl
my $fahrenheit;
my $celsius;
for ( $fahrenheit = -100 ; $fahrenheit <= 212 ; $fahrenheit++ ) {
$celsius = ( $fahrenheit - 32 ) * 5 / 9;
if ( $fahrenheit == $celsius ) {
print "The equal point in the Fahrenheit and Celsius scales is $fahrenheit °F and $celsius °C.\n";
last;
}
}
Python Solution
ch-1.py
for fahrenheit in range(-100, 213):
celsius = (fahrenheit - 32) * 5 / 9
if fahrenheit == celsius:
print(
f"The equal point in the Fahrenheit and Celsius scales is {fahrenheit} °F and {celsius} °C."
)
break
Task 2: Identity Matrix
Write a script to create a square identity matrix of size $size.
Example Output (size = 4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Logic
An identity matrix is a square matrix in which all the elements of the principal diagonal are ones, and all other elements are zeros. We can initialize a 2D array of size $N \times N$, and set the element at index [i][j] to 1 if i == j, and 0 otherwise.
Perl Solution
ch-2.pl
my $size = 4;
my @identity_matrix;
for my $i ( 0 .. $size - 1 ) {
for my $j ( 0 .. $size - 1 ) {
if ( $i == $j ) {
$identity_matrix[$i][$j] = 1;
}
else {
$identity_matrix[$i][$j] = 0;
}
}
}
# print the identity matrix
for my $row (@identity_matrix) {
print "@$row\n";
}
Python Solution
ch-2.py
size = 4
identity_matrix = [[0 for x in range(size)] for y in range(size)]
for i in range(size):
identity_matrix[i][i] = 1
# print the identity matrix
for row in identity_matrix:
print(row)