Day - 2
Looping Constructs:
For Loops: Understand how to use for loops to iterate over files or a list of items.
While Loops: Understand how to use while loops for continuous execution until a condition
is met.
1. Standard for Loop Syntax
for variable in list
do
# Commands to execute
done
Example:
for item in apple banana cherry
do echo "Fruit: $item"
done
2. C-Style Loop
for ((initialization; condition; increment))
do
# Commands to execute
done
Example:
for ((i=1; i<=5; i++))
do
echo "Iteration: $i"
done
Factorial of a given number:
#!/bin/bash
# Read the number from the user
echo "Enter a number:"
read number
# Initialize the factorial variable
factorial=1
# Calculate the factorial using a loop
for (( i=1; i<=number; i++ ))
do
factorial=$((factorial * i))
done
# Print the factorial
echo "The factorial of $number is: $factorial"
3. Syntax of while Loop in Shell
while [ condition ]
do
# Commands to execute
done
Example:
count=1
while [ $count -le 5 ]
do
echo "Iteration: $count"
count=$((count + 1)) # Increment counter
done
Sum of digit of a given number:
#!/bin/bash
# Read the number from the user
echo "Enter a number:"
read number
# Initialize the sum variable
sum=0
# Extract digits and calculate the sum
while [ $number -gt 0 ]
do
digit=$(( number % 10 )) # Get the last digit
sum=$(( sum + digit )) # Add the digit to the sum
number=$(( number / 10 )) # Remove the last digit
done
echo "The sum of the digits is: $sum" # Print the sum of the digits
Assignment:
1. Write a shell script to check if a given number is Krishnamurthy (145=1!+4!+5!) or not.
2. Print First 10 Fibonacci Numbers (Using for Loop)
3. To check if a given number is prime or not.
4. Reverse a Number (Using while Loop)
5. Find the greatest common divisor (GCD) of two numbers using a while loop