Controlling Program Flow(Its all about how you practice)😁

Section Overview:

Sequence
  1. Ordering Statements sequentially
Selection
  1. Making Decisions
Iteration
  1. Looping or Repeating
Important! with Sequence, Selection, and Iteration we can implement any algorithm.

Selection - Decision Making:
  • if statement
  • If-Else statement 
  • Nested if statement 
  • Switch Statement 
  • Conditional Operator ? :
Iteration - Looping
  • For loop
  • Range-based For loop
  • While loop
  • do-while Loop
  • continue and break
  • Infinite Loops
  • Nested Loops

If Statement:

if (expression)
                statement

  • If the expression is true then execute the statement
  • If the expression is false then skip the statement


If statement - Block:


if (expression){
statement 1;
statement 2;
}
  • Create a block of code by including more than one statement in code block {}.
  • Blocks can also contain variable declarations.
  • These variables are visible only within the block - local scope.

Exercise:

In this exercise, you will use a simple if statement to decide if someone can drive into the pub or not. Let us assume that anyone 18+ can enter the pub legally. So write a program to take input from the user and check whether he is allowed to enter the pub or not.

If - Else Statement:


if (expression)
      statement 1;
else (expression1)
      statement 2;    

The flow chart of if-else is simple it works like if statement, but if a statement is false then the program will shift to else.


Exercise:

In this exercise, you will use a simple if-else statement to decide if someone can drive into the pub or else notify them that they should not enter this pub now. Let us assume that anyone 18+ can enter the pub legally. So write a program to take input from the user and check whether he is allowed to enter the pub or not. If he is not allowed to enter the pub give him the reason that you can come back in n where n is how many years until the person turns 16 years old.

Nested-If Statement:


if (expression1)
       if (expression2)
             statement1;
       else
             statement2;
  • If the expression is true then execute statement1
  • If the expression is false then execute statement2

Exercise:
In this exercise, you will use a simple nested if statement.
Conditions:
  • If someone who is 16 years or elder but doesn't have a car should get a warning.
  • If someone who has a car but does not have required age to enter the pub should get a warning
  • If someone 16 years or elder and have a car can enter the pub.

Switch-Case Statement:


switch (integer_control_expression){
case expression_1: statement_1; break;
case expression_2: statement_2; break;
case expression_3: statement_3; break;
case expression_4: statement_4; break;
. . .
case expression_n: statement_n; break;
default: statement_default;
  • The control expression must evaluate to an integer type.
  • The case expressions must be constant expressions that evaluate to integer or integers literals.
  • Once a match occurs all the following case selections are executed UNTIL a break is reached the switch completely.
  • Best practice - provide a break statement for each case.
  • Best practice - Default is optional but should be handled.

Conditional Operator:


(Conditional_expression) ? expression1 : expression2

  • Conditional_expression evaluates to a boolean expression
  1. If Conditional_expression is true then the value of expression1 is returned
  2. If Conditional_expression is false then the value of expression2 is returned
  • Similar to the if-else construct
  • Ternary Operator
  • Very useful when used inline
  • Very easy to abuse!

Looping:

  • The third basic building block of programming
  1. Sequence, selection, iteration
  • Iteration or Repetition
  • Allows the execution of a statement or block of statements repeatedly 
  • Loops are made up of a loop condition and the body that contains the statements to repeat.
Some typical use cases:
  • A specific number of times 
  • For each element in a collection
  • While a specific condition remains true
  • Until a specific condition becomes false 
  • Until we reach the end of some input stream
  • ForeverπŸ˜‚
  • many, many more 🀣
For loop 
  • Iterate a specific number of times
Range-based for loop 
  • One iteration for each element in a range or collection
While Loop 
  • Iterate while a condition remains true
  • Stop when the condition becomes false
  • Check the condition at the beginning of every iteration
Do-while loop 
  • Iterate while a condition remains true
  • Stop when the condition becomes false
  • Check the condition at the end of every iteration

For Loop:


for (Initialization; Condition; Increment)
      Statement1

for (initialization; Condition; Increment){
      Statement(s)
}

Some other details:
  • The basic fo loop is very clear and concise
  • Since the for loop's expressions are all optional, it is possible to have 
  • No initialization
  • No test No increment 
for(;;)
   cout<<"Endless Loop" << endl;


In the above figure first for loop iterates 10 times and prints the output 1...10. I hope by this example you understood the basic working of for loop, How it works, How it iterates, How it increments its initiated values.
In the last example, we used a vector, we can use size() function to iterate till the end of the vector.

Exercise:

Write a code that uses a for loop to calculate the sum of odd integers from 1 to 15, inclusive. The final result should be stored in an integer variable named the sum.

Range-based For loop:

for(variable_type variable_name: sequence)
statement;

for(variable_type variable_name: sequence){
statements;
}


In this project, we will go through a couple of examples of integers, vectors, and strings.
  • In the first example, we will iterate through those integers using range-based for loop. auto automatically deduces the type of the variable specified. Sometimes it is very difficult to detect the type of a variable but C++ has a nice feature.
  • In the second example, we will iterate through those vector elements to calculate the average of all elements. temp is the variable where we will store each value in the iteration. But make sure that the size of the vector should not be 0. Right before the output, we used one of the IO Manipulators (set precision(1)) this is an IO Manipulators which helps to structure our output.
  • In the third example, we declared values in the range-based for loop itself, this is not something which we will not see often but I wanted to show you in case if you see it. It will iterate through that collection given below and prints the output.
  • In the last example, we iterated through the bunch of characters, even though we will discuss this in the next session, I gave a small glimpse in how we can iterate through characters, how to replace spaces with tabs.
Exercise:

Use a Range-Based for loop to loop through the initialized vector of integers by the user and determine how many elements in the vector are evenly divisible by either 3 or 5.

While Loop:


while(expression)
statement;

while(expression){
statements;
}



  • In this project, we programmed some examples in which something counts down and counts up and a couple of different examples.
  • In the first example, The main idea is we ask the user to enter a number and our program counts it down like 5,4,3,2,1, and exits the loop to print "BLAST OFF!!".
  • In the second example, We are declaring and defining the same variable num to be an integer for the user to enter a positive integer. we keep on incrementing till num is greater than or equal to i.
  • In the third example, we want to do some input validation. we want to loop while that number they enter is not less than 100. When this condition fails, then we got the correct number. Basically, this is the basics of input validation. 
  • In the fourth example, we've got a flag called done and we're initializing it to faults, fault means that we are not right, We still need to get more input from the user for whatever reason either we haven't started yet or they've entered something illegal. And I've got this variable right here that I've declared here called number that's the integer. That's what we are going to read into. Now it's important that we set that flag to false to begin because that's how we're getting into this. The first time, So don't just leave that true or just don't leave it at nothing and take a chance that it is false. Explicitly said it's false because that's going to get us in that loop the first time. So the first time we are going to say while isn't done right it's false. So we are in and we ask the user to enter an integer between 1 and 5 and they type the number right. Now we do a check if the number is less than or equal to one. If the user enters the correct number we will output thanks, and we will set the flag to true,  or else we will ask the user to enter the number again.

Do While Loop:



do{
statements;
}while(expression); 


In this simple menu project, The main difference between while loop and do-while loop is, While loop gives the output only if the condition is true if it is false then it will return from the loop. In the case of do-while, the given instructions in the do loop will print the output at most once and then it will check the given condition. The rest of the working of do-while is the same as while loop.

Continue and Break:


Break :
You have already seen the break statement used in the switch case statement. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of the loop.

Continue:
The continue statement breaks one iteration in the loop if a specified condition occurs, and continues with the next iteration in the loop.

Infinite Loops:

  • Loops whose condition expression always evaluates to true.
  • Usually, this is unintended and a programmer error.
  • Sometimes programmers use infinite loops and include and break statements in the body to control them,
  • Sometimes infinite loops are exactly what we need 
  1. Event loop in an event-driven program. 
  2. Operating system.

Challenge:


This challenge is about using the collection of integers and allows the user to select an option to perform a menu Operations on the list.
P: Print Numbers
A: Add a number
M: Display mean of the numbers
S: Display the smallest number
L: Display the largest number
Q: Quit

The program should only accept valid choices from the user, both upper and lowercase selections should be allowed. If an illegal choice is made, you should display, "Unknown selection, "Please try again" and the menu options should be displayed again.

If the user enters 'P' or 'p', you should display all the elements in the list. If the list is empty you should display "[] - The list is empty ". If the list is not empty then all the list elements should be displayed inside the square brackets separated by a space. For example, [1 2 3 4 5]

If the user enters "A"  or 'a' then you should prompt the user for an integer to add to the list, which you will add to the list and then display it was added. For example, if the user enters 5, you should display, "5 added". Duplicate list entries are OK.

If the user enters' or 'm', you should calculate the mean or average of the elements in the list and display it. If the list is empty you should display, "Unable to calculate the mean - no data".

If the user enters 'S' or 's' you should display the smallest elements in the list. For example, if the list contains [ 2 4 5 1], you should display, "The smallest number is 1".
If the list is empty you should display, "Unable to determine the smallest number - List is empty".

If the user enters 'L' or 'l' you should display the largest element in the list. For example, if the list contains [2 4 5 1], you should display, "The largest number is 5". If the list is empty you should display, "Unable to determine the largest number - List is empty".

If the user enters 'Q' or 'q' then you should display 'Good Bye😁" and the program should terminate.

Before you begin. Write out the steps you need to take and decide in what order they should be done. Think about what loops you should use as well as what you will use for your selection logic.

This exercise can be challenging! It may likely take a few attempts before you complete it --- that's OK!
Finally, be sure to test your program as you go and at the end.
Hint: Use a vector!
Additional functionality id you wish to extend this program:
- Search for a number in the list and if found display the number of times it occurs in the list.
- Clearing out the list ( make it empty again) ( Hint: The class has a .clear() method)
- Do not allow duplicate entries.
- "Come up with your own ideas and this is SUPER IMPORTANT!!!🧠".

Note: 
  • It is all about how you use, how we implement, how we practice, examples we choose. 
  • We are almost entered the real C++ programming to have fun in our life. Again!!, It's all about how you practice.

Comments

Post a Comment

Popular posts from this blog

Basic things You need to Know in C++😁

Arrays and Vectors ❤️