"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Friday, August 30, 2024

Class 5: Control Structures - Part 2

 Class 5: Control Structures - Part 2


Objective:

Understand and use loops (for, while, do...while) to perform repetitive tasks.

Learn loop control techniques using break and continue.

Introduction to Loops

Loops are fundamental control structures in programming that allow you to repeat a block of code multiple times. This is useful when you need to perform the same operation on a collection of data or when an action needs to be repeated a certain number of times.

1. The for Loop

The for loop is commonly used when you know in advance how many times you want to execute a statement or a block of code.

Syntax:

for (initialization; condition; increment) {

    // Code to be executed

}

Example:

<?php

for ($i = 1; $i <= 5; $i++) {

    echo "Iteration: " . $i . "<br>";

}

?>

Explanation:

Initialization: $i = 1 sets the loop counter to 1.

Condition: $i <= 5 ensures the loop runs while $i is less than or equal to 5.

Increment: $i++ increases the counter by 1 after each iteration.

Output:

Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

2. The while Loop

The while loop is used when you do not know in advance how many times the loop should run. It continues to loop as long as a specified condition is true.

Syntax:

while (condition) {

    // Code to be executed

}

Example:

<?php

$i = 1;

while ($i <= 5) {

    echo "Number: " . $i . "<br>";

    $i++;

}

?>

Explanation:

The loop continues to execute as long as $i is less than or equal to 5.

The counter $i is incremented by 1 in each iteration.

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

3. The do...while Loop

The do...while loop is similar to the while loop, but the condition is checked after the loop has executed. This means that the loop will always run at least once.

Syntax:

do {

    // Code to be executed

} while (condition);

Example:

<?php

$i = 1;

do {

    echo "Count: " . $i . "<br>";

    $i++;

} while ($i <= 5);

?>

Explanation:

The code block is executed once before the condition is tested.

The loop continues to run as long as $i is less than or equal to 5.

Output:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

4 Loop Control Statements

a) break Statement

The break statement is used to exit a loop prematurely when a certain condition is met.

Example:

<?php

for ($i = 1; $i <= 10; $i++) {

    if ($i == 6) {

        break;

    }

    echo "Number: " . $i . "<br>";

}

?>

Explanation:

The loop stops when $i reaches 6, so numbers 1 to 5 are displayed.

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

b) continue Statement

The continue statement skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.

Example:

<?php

for ($i = 1; $i <= 5; $i++) {

    if ($i == 3) {

        continue;

    }

    echo "Iteration: " . $i . "<br>";

}

?>

Explanation:

The number 3 is skipped, so the output only includes numbers 1, 2, 4, and 5.

Output:

Iteration: 1

Iteration: 2

Iteration: 4

Iteration: 5

5. Practical Examples and Exercises

Example 1: 

Sum of Numbers

Write a PHP script using a for loop to calculate the sum of numbers from 1 to 100.

<?php

$sum = 0;

for ($i = 1; $i <= 100; $i++) {

    $sum += $i;

}

echo "The sum of numbers from 1 to 100 is: " . $sum;

?>

Explanation:

This script calculates the sum by adding each number from 1 to 100 and outputs the total.

Example 2: 

Print Even Numbers

Write a PHP script using a while loop to print all even numbers between 1 and 20.

<?php

$i = 2;

while ($i <= 20) {

    echo $i . "<br>";

    $i += 2;

}

?>

Explanation:

This script prints all even numbers between 1 and 20 by incrementing the counter by 2 in each iteration.

Example 3: 

Multiplication Table

Write a PHP script using a do...while loop to generate the multiplication table of 5.

<?php

$i = 1;

do {

    echo "5 x " . $i . " = " . (5 * $i) . "<br>";

    $i++;

} while ($i <= 10);

?>

Explanation:

This script generates the multiplication table of 5 by multiplying 5 with numbers 1 to 10.


Practice Assignment 

1: Factorial Calculation

Objective: 

Write a PHP script that calculates the factorial of a given number using a for loop.

Instructions:

The script should prompt the user to enter a number.

Use a for loop to calculate the factorial of the number.

Display the result.

Example output:

Input: 5

Output: Factorial of 5 is 120

Assignment 2: 

Sum of Even Numbers

Objective: 

Create a PHP script that calculates the sum of all even numbers between 1 and 100 using a while loop.

Instructions:

Use a while loop to iterate through numbers from 1 to 100.

Add only even numbers to the sum.

Display the final sum.

Output: The sum of all even numbers between 1 and 100 is 2550

Assignment 3: 

Reverse a Number

Objective: 

Write a PHP script that reverses a given number using a do...while loop.

Instructions:

The script should prompt the user to enter a number.

Use a do...while loop to reverse the digits of the number.

Display the reversed number.

Input: 12345

Output: The reverse of 12345 is 54321

Assignment 4: 

Generate Fibonacci Sequence

Objective: 

Write a PHP script that generates the first n numbers of the Fibonacci sequence using a for loop.

Instructions:

The script should prompt the user to enter the value of n.

Use a for loop to generate the sequence.

Display the Fibonacci sequence up to n numbers.

Example:

Input: 7

Output: 

Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8

Assignment 5: 

Prime Number Checker

Objective: Create a PHP script that checks whether a given number is prime using a while loop.

Instructions:

The script should prompt the user to enter a number.

Use a while loop to check if the number has any divisors other than 1 and itself.

If the number is prime, display "The number is prime"; otherwise, display "The number is not prime."

Example:

Input: 13

Output: 13 is a prime number

Assignment 6: 

Multiplication Table for a Range

Objective: 

Write a PHP script that generates multiplication tables for numbers within a given range using nested for loops.

Instructions:

The script should prompt the user to enter the starting and ending numbers of the range.

Use nested for loops to generate and display the multiplication tables for all numbers within the range.

Example:

Input: Start = 3, End = 5

Output:

Multiplication Table for 3:

3 x 1 = 3

3 x 2 = 6

...

Multiplication Table for 4:

4 x 1 = 4

4 x 2 = 8

...

Multiplication Table for 5:

5 x 1 = 5

5 x 2 = 10

...

Assignment 7: 

Sum of Digits

Objective: Write a PHP script that calculates the sum of the digits of a given number using a do...while loop.

Instructions:


The script should prompt the user to enter a number.

Use a do...while loop to extract each digit and add it to the sum.

Display the sum of the digits.

Example:

Input: 123

Output: The sum of the digits of 123 is 6

Assignment 8: 

Pattern Printing

Objective: Create a PHP script that prints a pyramid pattern using nested for loops.

Instructions:

The script should prompt the user to enter the number of rows for the pyramid.

Use nested for loops to print the pattern.

Example:

Input: 5

Output:

markdown

Copy code

    *

   ***

  *****

 *******

*********


Code :

Assignment 1: Factorial Calculation

Objective: Write a PHP script that calculates the factorial of a given number using a for loop.

Code:

<?php

// Prompting the user to enter a number

$number = 5; // You can replace this with dynamic input from the user

// Initialize the factorial variable to 1

$factorial = 1;

// Using a for loop to calculate the factorial

for ($i = 1; $i <= $number; $i++) {

    $factorial *= $i; // Multiply the current number to the factorial

}

// Display the result

echo "Factorial of $number is $factorial";

?>

Explanation:

Initialization: Start with factorial = 1.

Loop: Multiply factorial by every number from 1 to $number.

Result: The result will be the product of all numbers from 1 to the given number.

Output: For number = 5, the output will be Factorial of 5 is 120.

Assignment 2: 

Sum of Even Numbers

Objective: Create a PHP script that calculates the sum of all even numbers between 1 and 100 using a while loop.

Code:

<?php

// Initialize variables

$sum = 0;

$i = 2; // Start from the first even number

// Using a while loop to calculate the sum of even numbers

while ($i <= 100) {

    $sum += $i; // Add the current even number to the sum

    $i += 2; // Move to the next even number

}

// Display the result

echo "The sum of all even numbers between 1 and 100 is $sum";

?>

Explanation:

Initialization: Start with i = 2 and sum = 0.

Loop: Add i to sum and increment i by 2 to get the next even number.

Result: The loop continues until i exceeds 100.

Output: The output will be The sum of all even numbers between 1 and 100 is 2550.

Assignment 3: 

Reverse a Number

Objective: Write a PHP script that reverses a given number using a do...while loop.

Code:

<?php

// Prompting the user to enter a number

$number = 12345; // You can replace this with dynamic input from the user

// Initialize variables

$reversed = 0;

do {

    $digit = $number % 10; // Extract the last digit

    $reversed = $reversed * 10 + $digit; // Append the digit to the reversed number

    $number = (int)($number / 10); // Remove the last digit from the original number

} while ($number > 0);

// Display the result

echo "The reverse of the number is $reversed";

?>

Explanation:

Digit Extraction: Use $number % 10 to get the last digit of the number.

Reversing: Multiply reversed by 10 and add the extracted digit.

Loop: Continue until all digits are processed ($number > 0).

Output: For number = 12345, the output will be The reverse of the number is 54321.

Assignment 4: Generate Fibonacci Sequence

Objective: Write a PHP script that generates the first n numbers of the Fibonacci sequence using a for loop.


Code:

<?php

// Prompting the user to enter the value of n

$n = 7; // You can replace this with dynamic input from the user


// Initialize the first two Fibonacci numbers

$first = 0;

$second = 1;


// Display the first two numbers

echo "$first, $second";


// Using a for loop to generate the Fibonacci sequence

for ($i = 3; $i <= $n; $i++) {

    $next = $first + $second; // Calculate the next Fibonacci number

    echo ", $next"; // Display the number


    // Update the values of first and second for the next iteration

    $first = $second;

    $second = $next;

}

?>

Explanation:

Initialization: Start with the first two Fibonacci numbers: 0 and 1.

Loop: Calculate the next number as the sum of the previous two numbers.

Output: For n = 7, the output will be 0, 1, 1, 2, 3, 5, 8.

Assignment 5: 

Prime Number Checker

Objective: 

Create a PHP script that checks whether a given number is prime using a while loop.

Code:

<?php

// Prompting the user to enter a number

$number = 13; // You can replace this with dynamic input from the user

// Initialize variables

$isPrime = true;

$i = 2;

while ($i <= sqrt($number)) { // Only check up to the square root of the number

    if ($number % $i == 0) {

        $isPrime = false; // If divisible, it's not prime

        break;

    }

    $i++;

}

// Display the result

if ($isPrime) {

    echo "$number is a prime number";

} else {

    echo "$number is not a prime number";

}

?>

Explanation:

Prime Check: Check divisibility from 2 to the square root of the number.

Loop: If a divisor is found, set $isPrime to false and exit the loop.

Output: For number = 13, the output will be 13 is a prime number.

Assignment 6: 

Multiplication Table for a Range

Objective: Write a PHP script that generates multiplication tables for numbers within a given range using nested for loops.

Code:

y code

<?php

// Prompting the user to enter the range

$start = 3; // Start of the range

$end = 5; // End of the range


// Outer loop for each number in the range

for ($i = $start; $i <= $end; $i++) {

    echo "Multiplication Table for $i:<br>";

    // Inner loop for generating the multiplication table

    for ($j = 1; $j <= 10; $j++) {

        echo "$i x $j = " . ($i * $j) . "<br>";

    }

    

    echo "<br>"; // Add a line break between tables

}

?>

Explanation:

Outer Loop: Iterate through each number in the given range.

Inner Loop: Generate the multiplication table for each number up to 10.

Output: For a range of 3 to 5, the script will output the multiplication tables for 3, 4, and 5.

Assignment 7: 

Sum of Digits

Objective: Write a PHP script that calculates the sum of the digits of a given number using a do...while loop.

Code:

<?php

// Prompting the user to enter a number

$number = 123; // You can replace this with dynamic input from the user


// Initialize variables

$sum = 0;


do {

    $digit = $number % 10; // Extract the last digit

    $sum += $digit; // Add the digit to the sum

    $number = (int)($number / 10); // Remove the last digit from the original number

} while ($number > 0);


// Display the result

echo "The sum of the digits is $sum";

?>

Explanation:

Digit Extraction: Use $number % 10 to get the last digit of the number.

Summing: Add each extracted digit to sum.

Loop: Continue until all digits are processed ($number > 0).

Output: For number = 123, the output will be The sum of the digits is 6.

Assignment 8: 

Pattern Printing

Objective: Create a PHP script that prints a pyramid pattern using nested for loops.

Code:


<?php

// Prompting the user to enter the number of rows

$rows = 5; // You can replace this with dynamic input from the user


// Outer loop for each row

for ($i = 1; $i <= $rows; $i++) {

    // Print leading spaces

    for ($j = $i; $j < $rows; $j++) {

        echo "&nbsp;&nbsp;"; // Add spaces for alignment

    }

    

    // Print stars

    for ($j = 1; $j <= (2 * $i - 1); $j++) {

        echo "*";

    }

    

    echo "<br>"; // Move to the next line after each row

}

?>

Explanation:

Outer Loop: Iterate through each row of the pyramid.

Leading Spaces: Use the first inner loop to add spaces for alignment.

Stars: Use the second inner loop to print the stars in each row.

Output: For rows = 5, the script will print a pyramid pattern like this:

markdown

Copy code

    *

   ***

  *****

 *******

*********


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template