// 1.
Write a Scala program using a for loop to calculate the sum of all elements in a list of
integers. n = 10
val limit = 10
val intList = [Link](1, limit + 1)
var totalSum = 0
for (num <- intList) {
totalSum += num
println(s"The sum of elements from 1 to $limit is: $totalSum")
// 2. Use a for loop to print the multiplication table of a given number n. N = 5
val multiplier = 5
println(s"Multiplication Table for $multiplier:")
for (multiplierIndex <- 1 to 10) {
println(s"$multiplier * $multiplierIndex = ${multiplier * multiplierIndex}")
}
// 3. Write a for loop that prints all even numbers between 1 and 50.
println("Even numbers between 1 and 50:")
for (evenNum <- 1 to 50 if evenNum % 2 == 0) {
println(evenNum)
}
// 4. Create a Scala program using a nested for loop to print a pyramid pattern of asterisks.
val pyramidRows = 5
println("Pyramid Pattern:")
for (pyramidRow <- 1 to pyramidRows) {
for (space <- 1 to pyramidRows - pyramidRow) {
print(" ")
for (asterisk <- 1 to (2 * pyramidRow - 1)) {
print("*")
println()
// 5. Write a Scala program using a while loop to calculate the factorial of a given number. Val n =
5.
val factNum = 5
var factorial = 1
var factIndex = 1
while (factIndex <= factNum) {
factorial *= factIndex
factIndex += 1
println(s"The factorial of $factNum is: $factorial")
// 6. Write a Scala program that uses a while loop to find the sum of the digits of a given number.
Num = 1234
val digitNum = 1234
var digitSum = 0
var tempDigitNum = digitNum
while (tempDigitNum > 0) {
digitSum += tempDigitNum % 10
tempDigitNum /= 10
println(s"The sum of the digits of $digitNum is: $digitSum")
// 7. Use a while loop to reverse the digits of an integer. Num = 5678
val reverseNum = 5678
var reversed = 0
var tempNum = reverseNum
while (tempNum > 0) {
reversed = reversed * 10 + (tempNum % 10)
tempNum /= 10
println(s"The reverse of $reverseNum is: $reversed")
// 8. Write a Scala program using if statements to check if a number is positive, negative, or zero.
Num = -10
val checkNum = -10
if (checkNum > 0) {
println(s"$checkNum is a positive number.")
} else if (checkNum < 0) {
println(s"$checkNum is a negative number.")
} else {
println("The number is zero.")
}
// 9. Write an if statement to check if a given year is a leap year. year = 2024
val yearToCheck = 2024
if ((yearToCheck % 4 == 0 && yearToCheck % 100 != 0) || (yearToCheck % 400 == 0)) {
println(s"$yearToCheck is a leap year.")
} else {
println(s"$yearToCheck is not a leap year.")
// 10. Write a Scala program using an if statement to check if a number is odd.
val oddEvenNum = 7
if (oddEvenNum % 2 == 0) {
println(s"$oddEvenNum is an even number.")
} else {
println(s"$oddEvenNum is an odd number.")