CPE-PC112 Programming Logic and Design PDF
Document Details
Uploaded by Deleted User
Tags
Related
- GPA 1 - Basics of Industrial Automation & Control (August 2024) PDF
- GPA 1 - Basics of Industrial Automation & Control PDF
- Estructuras selectivas PDF
- 23124/70 Marks PLC Exam Paper PDF
- Fundamentals of Python: First Programs - Chapter 3 Control Statements PDF
- Intro to Computer Science - For Loop & Control Structures PDF
Summary
This document provides an overview of control flow, including repetition and loop structures. It discusses different types of loops, such as while, do-while, and for loops, and includes a discussion on nested loops. Several programming examples are included, demonstrating the use of these concepts. The document contains questions for further practice.
Full Transcript
# CPE-PC112 Programming Logic and Design ## 04 Control Flow Repetition ### Control Flow The term control flow details the direction the program takes (which way program control "flows"). #### Control Structures * Is like a block of programming that analyses variables and chooses a direction in wh...
# CPE-PC112 Programming Logic and Design ## 04 Control Flow Repetition ### Control Flow The term control flow details the direction the program takes (which way program control "flows"). #### Control Structures * Is like a block of programming that analyses variables and chooses a direction in which to go based on given parameters. * Basic types of control structures: * Sequential * Conditional/Selection * Iterative/Repetition ### Control Flow * **Sequential:** Default mode. Sequential execution of code statements (one line after another) - like following a recipe. * **Selection:** Used for decisions, branching - choosing between 2 or more alternative paths. In C, these are the types of selection statements: * if, if/else, if/else if/else * switch * **Repetition:** Used for looping, i.e. repeating a piece of code multiple times in a row. In C, there are three types of loops: * while * do/while * for ### Problem Make a flowchart that will input 10 integers. Output the sum of the inputted integers. Lots of input and not good to see. What if we have hundreds, thousands or even millions of inputs? How to solve this problem? ### Solution: Use Loops #### 3. Iteration/Loop * When is loop required? * **Repeating Statement Execution** * Loop is a sequence of instructions that is continually repeated until a certain condition is reached. It is used to repeat execution of block of code. #### Execution of Loops * Typically this is done inside a loop statement of some sort using a variable as a counter to keep track of which character is to be checked. * The counter variable may be incremented by one, each time through, so that the first element is examined the first time through the loop, the second element the second time, and so forth. #### Execution of Loops * Being able to repeatedly execute a statement or compound statement is an essential feature of programming. ### Loops * There are several loop types. * Depending on situation, sometimes it is better to use one kind of loop than another, but every loop can be transformed into one another. * This is not so important for beginners, you just need to know that there is good and better use of particular loop. ### Control Flow A loop has the following components (* essential): 1. **Initialization of variables** - setting an initial value of zero before the loop statement is reached. 2. **Condition/testing** - (that would evaluate to either true or false) the condition to check is usually made on the current value of the variable initialized in (1) for it controls the loop repetition. 3. **Body** - statements that are repeated in the loop. 4. **Updating** - a statement inside the body of the loop that updates the value of the variable that is initialized during each repetition. ### Control Flow * **3 Types:** * do-while statement * while statement * for statement ### Control Flow - do-while statement * This loop executes a block of codes as long as the specified condition is true. * It is a post checked loop because it checks the controlling condition after the code is executed. * Is usually used when we do not know exactly how many times we need to execute repeating black of code, but we know that we need to execute it at least once. ### Control Flow **Syntax:** ``` do{ statement/s; } while (loop repetition condition); ``` **Example:** ``` c=1; do{ printf("Hello World\n"); C++; } while (c<=5); ``` ### Control Flow - while statement * Like do-while, this will execute a block of codes while the given condition is true. * It is a pre-checked loop because it checks the controlling condition first before the code is executed. * While loop is usually used when we do not know exactly how many times we need to execute repeating block of code. ### Control Flow **Syntax:** ``` while(condition) body; ``` **Example:** ``` c=1; while (c<=5) { printf("Hello World\n"); C++; } ``` ### Flowcharts of while and do while loops **While versus Do-While Loops** <start_of_image> Problem Diagram: | | | |-----------------|--------------------| | while(condition) | do { | | body; | body; | | | } while(condition );| | T | | | Condition? | | | F | | | | T | | | Condition? | | | F | | | | | Body | Body | ### While and do while loops * Both while loops and do-while loops condition-controlled, meaning that they continue to loop until some condition is met. * Both while and do-while loops alternate between performing actions and testing for the stopping condition. ### Control Flow - for statement * A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. * For loops are usually used when we know exactly how many times we need to execute repeating block of code. It is also good for creating definite loops. ### Control Flow **Syntax:** ``` for (initialization; condition; update ){ statement/s; } ``` * The initialization of the for loop is performed only once. * The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned. * The update increases or decreases the counter by a set value. ### Flowchart of for loop For loop flowchart diagram: | Initialization | False | | | |---------------|--------|---|-----------------------------------| | | Condition?| T | body | | | | | Initialization | | | | | Incrementation | **Example:** ``` int number; //for loop to print 1-10 numbers for(number = 1 ; number <= 10 ; number++) { printf("%d\n",number); } ``` ### Multiple initialization inside for Loop in C * We can have multiple initialization in the for loop as shown below. * `for (i=1,j=1;i<10 && j<10; i++, j++)` #### What's the difference between above for loop and a simple for loop? 1. It is initializing two variables. Note: both are separated by comma (,). 2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot use multiple test conditions separated by comma, you must use logical operator such as && or || to join conditions. 3. It has two variables in increment part. Note: Should be separated by comma. ### Loop types (reminder) **Indefinite Loop:** * You do not know ahead of time how many times your loop will execute. * For example, you do not know how many books a person might order. **Definite Loop:** * You know exactly how many times you want the loop to execute. * Not at compile time necessarily. ### Infinite Loop * You can still end up with an infinite loop when using for loops * `for (;;){ //statements; }` * Infinite loops with while and do-while: * `while (1){ //statements; }` * `do{ //statements; } while(1);` * Is this an infinite loop? * `char counter; for (counter = 0; counter <= 10; counter--)` * NO! review data types, specially the range of each data types and how signed numbers and unsigned numbers work. ### Break Statement in C * The break statement is used mainly in in the switch statement. It is also useful for immediately stopping a loop. * We consider the following program which introduces a break to exit a while loop: ``` #include <stdio.h> int main() { int num = 5; while (num > 0) { if (num == 3) break; printf("%d\n", num); num--; } } ``` Output: ``` 5 4 ``` ### Continue Statement in C * When you want to skip to the next iteration but remain in the loop, you should use the continue statement. For example: ``` #include <stdio.h> int main() { int nb = 7; while (nb > 0) { nb--; if (nb == 5) continue; printf("%d\n", nb); } } ``` Output: ``` 6 4 3 2 1 So, the value 5 is skipped. ``` ### When to Use Which Loop ? * If you know (or can calculate) how many iterations you need, then use for loop. * If it is important that the loop complete at least once before checking for the stopping condition, or if it is not possible or meaningful to check the stopping condition before the loop has executed at least once, then use a do-while loop. * Otherwise use a while loop. ## Example 1. Make a flowchart that will input 10 integers. Output the sum of the inputted integers. 2. Make a C program that will input 20 scores of students. Output the average of the scores. 3. Make a C program to input 20 integers. Output the average of all positive odd integers. ## Additional Problems 1. Make a C program that will input integers, positive and negative. The flowchart/program will terminate if a negative number is inputted. Output the average of all positive integers inputted. 2. Make a C program to input at least 2 digit number. Output the number in reverse. **Example:** Enter a number: 534 **Output:** 435 3. Make a C program to input an integer. Output the factorial of the inputted integer. Use while or do while. 4. A perfect number is a positive integer that is the sum of its factors excluding the number itself is equal to the positive integer. The first perfect number is 6, because 1, 2, and 3 are its factors, and 1 + 2 + 3 = 6. Make a C program that will prompts the user to enter a number and determine if it's a perfect number or not. 4. Make a C program to input positive integers. Your program terminates if the sum of the inputted positive integers is greater than or equal to 101. 5. Make a C program to input 10 names of student.. Each student has 5 exam scores. Determine the average exam score of each student. ## Additional Problems * Make a C program to output the following figures shown below: * Figure a: ``` **** **** **** **** ``` * Figure b: ``` * ** * * * * * * ``` * Make a C program to output the number figures shown below: * Figure c: ``` 1 12 123 1234 12345 ``` * Figure d: ``` 12345 1234 123 12 1 ``` * Make a C program to output the number figures shown below: * Figure e: ``` 1 22 333 4444 55555 ``` * Figure f: ``` 1 23 456 7 8 9 10 11 12 13 14 15 ``` ### Loop within a loop (Nested loops) * C programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. * The syntax for a nested for loop statement in C is as follows: ``` for (init; condition; increment) { for (init; condition; increment ) { statement(s); } statement(s); } ``` * The syntax for a nested while loop statement in C programming language is as follows: ``` while(condition) { while(condition) { statement(s); } statement(s); } ``` * The syntax for a nested do...while loop statement in C programming language is as follows: ``` do { statement(s); do { statement(s); }while(condition ); }while(condition ); ``` ### Loop within a loop (Nested loops) * A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. * Some programmers like to use successive integers i, j, k, l, etc. for use in nested for loops. This can be appropriate if the mathematics being implemented uses multiple i j k subscripts. * Other times it can be less confusing to use alternative variables that are more meaningful to the problem at hand, such as the r and c variables used above to keep track of rows and columns. * The limits as to how deeply loops may be nested is implementation dependent, but is usually too high to be of any concern, except in cases of extremely complex or extremely poorly written programs. ## Additional Examples 1. Make a C program to input N number of integers. Output the average of all positive odd integers. Modify your program so that every time you run, it will prompt the user to continue or not. If you press Y it will run again, otherwise if you press any key it terminates. 2. Make a C program to input 10 names of student. Each student has 5 exam scores. Determine the average exam score of each student. Output the highest average exam score. 3. Make a C program to determine the Least Common Denominator of the 2 inputted numbers. 4. Make a C program to input 15 exam scores. Output the average exam score and also the exam scores that are greater than the average exam score. 5. Make a C program to input 10 integers. Output the 4th, 7th and 9th inputted integers only.