Hello Steemians, welcome to my post, and stay safe as you read through this post.
Explain the cycles in detail. What are they and how are they used? What is the difference between the While and Do-While cycle?
Cycles Simply put in a layman's understanding, cycles are programming constructs that are used to repeat a block of code multiple (many) times until a certain condition is met.
Cycles are mostly useful in tasks that involve repetition like iterating over elements in performing calculations or in a list repeatedly until a specific result is achieved. In other programming languages, cycles are also known as Loops in this post I believe using a loop in place or cycle is not a bad idea, haha the reason is for you to get exposure.
Types
For Cycles (Loops)
We can use this when the number of iterations is known beforehand.
We can use Iterates over a sequence, For example, a range of numbers, lists, or arrays.
for i in range(5): # Loops from 0 to 4
print(i)
The above code will print numbers from 0 to 4, as the loop runs 5 times.
While Cycle (Loop)
This repeats a block of code while a specified condition is
True
.Also, the condition is checked before executing the loop body, so the loop does not execute if the condition is false from the beginning.
Example in Python program:
i = 0
while i < 5:
print(i)
i += 1
The above cycle will print numbers from 0 to 4, just like that of the for
cycle (loop), but with a separate structure.
Do While Cycle (Loop): C++, and Java is the most supported languages for this.
- The cycle body is executed at least once because the condition is checked after the cycle has been executed.
Example in C++
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);
The above code will print numbers from 0 to 4, but the body will execute before the condition is checked which is the main difference.
Differences Between While and Do-While cycle
Based on Aspect | While | Do-While Cycle |
---|---|---|
Based on condition check | Before the cycle (loop) is executed | After the cycle (loop) is executes |
Based on guaranteed executes | If the condition is false it may not execute | It executes at least once in respective of the condition. |
Based language | C, JavaScript, Python, etc | Java, C, C++ etc. |
Investigate how the Switch-case structure is used and give us an example
The Switch-case structure is a control flow statement that is used in programming to execute one block of code among several options which is based on the value of expression or a variable. It is another way of using multiple if-else
statements, which makes the code more readable and cleaner when a programmer is checking for many conditions.
How The Switch-case Works
The statement evaluates an expression or a variable.
The case labels are what define possible values for expression, and the block of code under the matching
case
is executed.The
break
statement is mostly added after eachcase
to prevent the program from continuing to execute subsequent cases called "fall-through".An optional default block can be added to handle cases where the default
case
value matches the variable or expression is not available.
Syntax (in C-like languages, such as C, C++, Java, and JavaScript):
switch (expression) {
case value1:
// Code to be executed if expression == value1
break;
case value2:
// Code to be executed if expression == value2
break;
// You can have any number of case statements
Default:
// Code to be executed if the expression doesn't match any case
}
Example of a Switch-Case Structure (in C++)
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
Default:
cout << "Weekend" << endl;
break;
}
return 0;
}
Interpretation:
switch (day)
: Theswitch
statement checks the value of the variableday
- Each of the
case
defines a possible value thatday
can be taken from 1 to 5. - If
day==3
, the program will print Wednesday and then exit the switch block because of the use of thebreak
statement. - The
default
block catches any value that doesn't match the specified cases.
If-else vs Switch-case
If-else is more flexible since it allows more complex conditions and expressions whereas switch-case is mostly more efficient easier and simple to read when there are many (multiple) conditions to evaluate.
Fall-through behavior
In C, C++, and several other programming languages, if a break
statement is missing, the execution will continue to the next case which we can see in an example below.
Example with Fall-through:
int day = 2;
switch (day) {
case 1:
cout << "Monday";
case 2:
cout << "Tuesday"; // This will execute
case 3:
cout << "Wednesday"; // This will also execute because there's no break
default:
cout << "Unknown day";
}
Switch-Case in JavaScript
In JavaScript, the structure of Switch-case works similarly to that of Python which we can see from the example given below.
Example in JavaScript:
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
Case 3:
console.log("Wednesday");
break;
default:
console.log("Weekend");
}
From the above, Wednesday
is printed as day ==3
. The default
block acts as feedback for other values that aren't handled by the cases.
In summary, the switch case which we have looked into examples are simple alternative to using multiple if-else
statements when working with a single expression or variable that has many values.
Explain what the following code does
Based on the given code by the professor which is an algorithm that is written in pseudocode using a switchcase
structure, I will be explaining what the code does in detail by breaking everything bit by bit.
Variables:
From the code we have the following;
op, n, a
are integers.exit
is known as a Boolean flag, that is set toFalse
.a
is used to store the sum of numbers that are entered.
Program Logic:
The program runs in a cycle (loop) until
exist
is set toTrue
.User is prompted to select one of the following given options:
Sum numbers
Show results`
End program`
Based on the user's input (
op
), one of the following actions takes place:
Case 1: Summing Numbers
- User is asked how many numbers they want to sum.
- For each of the numbers, the user is prompted to enter a value, which is added to the accumulator variable `a.
- After all numbers have been entered, the program then informs the user that the process is completed and waits for the user to press a key.
Case 2: Show Results
- The program displays the current sum (
a
and waits for the user to press a key.
Case 3: End Program
- The program clears the screen and prints "Bye =)" and then sets
exit
toTrue
, which then breaks the cycle (loop) and ends the program.
Default Case:
- If the user enters an invalid option, the program notifies them and asks them to press a key to continue.
Key Features
The cycle (loop) repeats until the user selects the option to end the program in
case 3
The sum is persistent across different inputs, which means the sum is cumulative unless the program restarts afresh.
Write a program in pseudo-code that asks the user for a number greater than 10 (Do-While), then add all the numbers with an accumulator (While) Example: The user enters 15. The program adds up to 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15.
Here is a program in pseudocode that asks the user for a number greater than 10 (Do-While), then adds all the numbers with an accumulator (While) example.
Algorithm SumNumbers
Define number, sum, and i As Integer
// Step 1: Ask for a number greater than 10
Do
Print "Enter a number greater than 10: "
Read number
While number <= 10
// Step 2: Initialize sum and counter
sum = 0
i = 1
// Step 3: Add all numbers from 1 to the entered number
While i <= number Do
sum = sum + i
i = i + 1
EndWhile
// Step 4: Output the result
Print "The sum of all numbers from 1 to ", number, " is: ", sum
EndAlgorithm
However, after writing the program several times, I kept getting errors while trying to run the program which at first was what I then wrote in Python.
# Online IDE - Code Editor, Compiler, Interpreter
print('Welcome to @josepha!! Happy Coding :)')
# Function to ask for a number greater than 10
def get_number():
number = 0
# Do-While equivalent in Python (using a while loop)
while number <= 10:
number = int(input("Enter a number greater than 10: "))
return number
# Function to calculate the sum from 1 to the entered number
def sum_numbers(number):
sum = 0
i = 1
# While loop to accumulate the sum
while i <= number:
sum += i
i += 1
return sum
# Main program
number = get_number()
result = sum_numbers(number)
print(f"The sum of all numbers from 1 to {number} is: {result}")
Interpretation:
The
get_number()
function is the function that keeps asking the user for a number greater than 10 using awhile
loop. The loop breaks only when a valid number that is greater than 10 is entered.The
sum_numbers(number)
function is the function that uses a loop to add all numbers from1
to the entered number. This function accumulates the result in thesum
variable.The Main program is known as the
get_number()
function that is used to get a valid input and then callssum_number,(number)
to calculate the sum and show the result.
Example;
I enter 20
the program calculates the sum of numbers from 1 to 20 as 1+2+3+3+4+5.......20 = 210
.
I am inviting: @kuoba01, @simonnwigwe, and @ruthjoe
@tipu curate
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Upvoted 👌 (Mana: 0/6) Get profit votes with @tipU :)
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Upvoted. Thank You for sending some of your rewards to @null. It will make Steem stronger.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit