This document introduces repetitive statements in three sentences or less:
The chapter describes FOR, WHILE, and REPEAT statements to repeatedly execute blocks of code. It provides examples and step-by-step explanations of how each statement type works. Exercises are included to have the reader write repetitive statements and use them for different types of sorting.
The document discusses several topics related to programming and algorithms:
1. It defines what an algorithm is and provides examples like musical scores, knitting patterns, and recipes.
2. It explains the basic steps in designing an algorithm - analyzing the problem, developing the algorithm, converting it to code, and testing it.
3. It provides a detailed example algorithm for making a cup of tea that is refined in steps.
4. It discusses some basic programming concepts like variables, assignment, declaring variables, and control structures like conditional statements.
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlENGWAU TONNY
The document discusses different types of flow control in programming including sequential, selection, and repetition structures. It provides examples of if/else statements, nested ifs, if-else ladders, and the conditional operator. It also covers switch-case statements as an alternative for complex decisions. Finally, it poses challenges for readers to code decision-making structures using if/else and switch-case statements.
Control statements allow altering the sequential flow of program execution. There are three main types of control statements in C: conditional statements like if-else that allow branching based on boolean conditions, loop statements like while and for that repeat execution of a block of code a specified number of times, and switch statements that choose among multiple code blocks to execute based on a variable's value. Well-structured programs use control statements to make decisions and repeat tasks to process data efficiently.
The document discusses different types of program control statements in 3 categories: selection statements (if, switch), iteration statements (for, while, do-while, foreach), and jump statements (break, goto, continue, return, throw). It provides details on switch statements, including their general form and use of break. It also covers fallthrough in switch statements, which allows continuous execution of consecutive cases without break, and how to force fallthrough using goto. The document concludes with an overview of foreach loops, which iterate over an expression similar to for loops but do not allow changing the iteration variable.
This document provides an overview of different types of statements and flow control constructs in C++ programming. It discusses sequential, selection, and iteration statements. Selection statements covered include if, if-else, switch, and ternary operator. Iteration statements discussed are for, while, do-while, and nested loops. Jump statements like break, continue, goto, and exit function are also summarized. Examples are provided for most constructs to illustrate their usage.
5. using variables, data, expressions and constantsCtOlaf
The document discusses best practices for using variables, data, expressions, and constants in programming. It covers principles for initializing variables, variable scope and lifetime, naming conventions, and using expressions and constants. Guidelines are provided for initializing variables, reducing variable span and live time, single purpose naming, and following standard naming conventions.
The document discusses different types of control statements in C programming including sequential, selective, and iterative statements. It provides examples and explanations of common control statements like if, if-else, if-else ladder, switch case, for, while, do-while, and goto statements. Control statements are used to control the flow and logic of a program by allowing conditional execution, repetition, and branching in code. They help structure programs, improve clarity, and facilitate debugging.
This document provides an introduction to decision statements in C programming. It discusses if, else if, else statements, switch statements, nested if/else, and conditional operators. Examples are given to check even/odd numbers, profit/loss calculation, and character classification. The importance of break statements in switch is explained. Operator precedence is also briefly covered.
The document discusses several topics related to programming and algorithms:
1. It defines what an algorithm is and provides examples like musical scores, knitting patterns, and recipes.
2. It explains the basic steps in designing an algorithm - analyzing the problem, developing the algorithm, converting it to code, and testing it.
3. It provides a detailed example algorithm for making a cup of tea that is refined in steps.
4. It discusses some basic programming concepts like variables, assignment, declaring variables, and control structures like conditional statements.
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlENGWAU TONNY
The document discusses different types of flow control in programming including sequential, selection, and repetition structures. It provides examples of if/else statements, nested ifs, if-else ladders, and the conditional operator. It also covers switch-case statements as an alternative for complex decisions. Finally, it poses challenges for readers to code decision-making structures using if/else and switch-case statements.
Control statements allow altering the sequential flow of program execution. There are three main types of control statements in C: conditional statements like if-else that allow branching based on boolean conditions, loop statements like while and for that repeat execution of a block of code a specified number of times, and switch statements that choose among multiple code blocks to execute based on a variable's value. Well-structured programs use control statements to make decisions and repeat tasks to process data efficiently.
The document discusses different types of program control statements in 3 categories: selection statements (if, switch), iteration statements (for, while, do-while, foreach), and jump statements (break, goto, continue, return, throw). It provides details on switch statements, including their general form and use of break. It also covers fallthrough in switch statements, which allows continuous execution of consecutive cases without break, and how to force fallthrough using goto. The document concludes with an overview of foreach loops, which iterate over an expression similar to for loops but do not allow changing the iteration variable.
This document provides an overview of different types of statements and flow control constructs in C++ programming. It discusses sequential, selection, and iteration statements. Selection statements covered include if, if-else, switch, and ternary operator. Iteration statements discussed are for, while, do-while, and nested loops. Jump statements like break, continue, goto, and exit function are also summarized. Examples are provided for most constructs to illustrate their usage.
5. using variables, data, expressions and constantsCtOlaf
The document discusses best practices for using variables, data, expressions, and constants in programming. It covers principles for initializing variables, variable scope and lifetime, naming conventions, and using expressions and constants. Guidelines are provided for initializing variables, reducing variable span and live time, single purpose naming, and following standard naming conventions.
The document discusses different types of control statements in C programming including sequential, selective, and iterative statements. It provides examples and explanations of common control statements like if, if-else, if-else ladder, switch case, for, while, do-while, and goto statements. Control statements are used to control the flow and logic of a program by allowing conditional execution, repetition, and branching in code. They help structure programs, improve clarity, and facilitate debugging.
This document provides an introduction to decision statements in C programming. It discusses if, else if, else statements, switch statements, nested if/else, and conditional operators. Examples are given to check even/odd numbers, profit/loss calculation, and character classification. The importance of break statements in switch is explained. Operator precedence is also briefly covered.
Control structures in C++ Programming LanguageAhmad Idrees
This document discusses various control structures in C++ for selection and branching, including if/else statements, switch statements, logical operators, and the assert function. If/else statements allow for two-way selection based on a logical expression being true or false. Switch statements allow for multi-way branching depending on the value of an expression. Logical operators like && and || are used to combine logical expressions. The assert function halts a program if a specified condition is false, which is useful for debugging.
this slide is for to understand the conditions which are applied in C++ programming language. I hope u would understand better by viewing this presentation.
The document discusses various control structures used in programming, including sequence, repetition (loops), and selection (branching). It covers common loop and conditional statements like while, for, if/else, switch/case. Control structures allow programs to execute instructions in different orders depending on conditions or to repeat steps multiple times. Keywords like break and continue change the normal flow of loops.
1. C programs consist of functions that perform specific tasks. The main() function is where program execution begins.
2. This example program prints "Welcome to C" by using functions like printf() to output text and getch() to pause the program.
3. The #include directives tell the compiler to include header files containing declarations for functions like printf() and clrscr() that are used in the program.
The document discusses control structures and functions in C programming. It defines variables and data types in C. It describes different control structures like sequence, selection, and repetition. It explains basic loops like while, for, and do-while loops. It also discusses functions, how to define functions, pass parameters, and return values. It provides examples of string handling and manipulation functions in C.
The future of DSLs - functions and formal methodsMarkus Voelter
I have used domain-specific languages to empower non-programmers in healthcare, finance, aerospace, automotive and public administration for years. My approach relies on growing the DSL from a functional programming core, combining the flexibility and power of an algorithmic language with domain-specific constructs that range from temporal data types, state machines and data models to polymorphic dispatch between versions of calculation rules. I rely on the open source MPS workbench to define the languages and their IDE. I am looking to incremental model transformations to desugar domain-specific constructs back to a minimal core language in realtime. That core language will have an interpreter for in-IDE execution and a compiler for deployment. The language will be integrated with formal methods to verify properties of programs, enabling advanced analyses for DSL users. In this talk, I will demo some existing DSLs, provide an illustration of how they are built, and demo prototypes of the future approach while discussing their integration with formal methods.
The document discusses various control structures in C++ like conditional statements (if-else, switch), loops (while, for, do-while), and jump statements (break, continue, goto). It provides examples to explain if-else, switch, while, for, do-while loops. Nested loops and break/continue statements are also covered. The last section briefly explains unconditional jump with goto statement.
This document discusses iterative statements in four programming language paradigms: imperative, object-oriented, functional, and logical. It defines key terms and provides examples of iterative constructs like for loops, while loops, and recursion in languages from each paradigm (C, Java, Lisp, Prolog). The implementation and readability of iterations are compared across paradigms. Imperative languages use loops, functional languages rely more on recursion due to lack of variables, and logical languages only use recursion to iterate.
The document discusses best practices for naming variables. It recommends initializing variables as they are declared, giving variables descriptive names to indicate their purpose, and adopting naming conventions to make code more consistent and readable for multiple programmers. Standardized prefixes and abbreviations can make long names more compact while retaining clarity. Overall, the goal is to use variable names that are meaningful, unambiguous, and help convey the essential logic of the code at a glance.
There are three main types of control structures in computer programming: sequential logic, selection logic, and iteration logic. Sequential logic executes code line-by-line. Selection logic (e.g. if/else statements) allows executing code conditionally. Iteration logic (e.g. for loops) repeats code execution in loops. The document provides examples of if/else, nested if, switch statements, and the conditional operator for implementing various control structures in C programming.
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming languages:
Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program. We will discuss these in turn.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
Branching, Looping, Conditional Statement, Exit function, Difference between break and exit. Some of the codes and some of the branching techniques are covered in this unit. Check conditional statement looping and exit functions too
https://github.com/ashim888/csit-c
Savannahs are grasslands located in Africa, India, South America, and Australia, with scattered trees and a warm climate between 20 to 30 degrees Celsius. They are dominated by grasses and shrubs and support many large herbivores and predators, though hunting, overgrazing, destruction and extinction threaten the ecosystem.
There are many criterias based on which one can choose the credit card. Some things are listed here which will help one to decide on to what basis one can choose credit card.
This document provides recommendations for mobile tools and apps for work, including the top Android phones and tablets as well as tools for email, note-taking, file storage, photo sharing, presentations, and accepting payments on mobile devices. It recommends Android and Apple devices and apps like Touchdown for email on Kindle Fire, Just Lists for notes, cloud storage options, messaging apps, read-it-later tools, news readers, and password managers. It also discusses Microsoft Office web apps and accepting payments via mobile.
The document describes several major biomes including tropical rain forests, tropical savannas, deserts, temperate grasslands, temperate forests, and tundra. Each biome has characteristic abiotic factors like climate and soil that support distinctive plant and animal communities. The document provides details on the location, climate, plants, and animals found in each biome.
The savannas are located in Africa, South America, Australia and parts of India. Animals in the savanna have developed adaptations like cheek pockets in baboons to store food and razor sharp teeth to defend against predators. Savanna plants also have adaptations like the baobab tree storing water in its thick trunk to survive dry seasons. However, human activities like fires, agriculture and hunting are threatening savanna ecosystems.
Response to Intervention (RtI) is a support system designed to identify and assist struggling students through intervention. It has three levels called tiers to monitor student progress and provide increasingly intensive interventions. While it can be effective for increasing student achievement and addressing individual student needs, implementing RtI can be time consuming for classroom teachers.
The document discusses different types of looping statements in VB.NET, including While, Do, For, and For Each loops. It provides examples and syntax for each type of loop. The key types of loops are:
- While loops repeat statements as long as a condition is true.
- Do loops execute statements first, then check a condition to repeat.
- For loops repeat a set number of times, specified by a start and end value.
- For Each loops iterate through each element of a collection, such as an array.
Control structures in C++ Programming LanguageAhmad Idrees
This document discusses various control structures in C++ for selection and branching, including if/else statements, switch statements, logical operators, and the assert function. If/else statements allow for two-way selection based on a logical expression being true or false. Switch statements allow for multi-way branching depending on the value of an expression. Logical operators like && and || are used to combine logical expressions. The assert function halts a program if a specified condition is false, which is useful for debugging.
this slide is for to understand the conditions which are applied in C++ programming language. I hope u would understand better by viewing this presentation.
The document discusses various control structures used in programming, including sequence, repetition (loops), and selection (branching). It covers common loop and conditional statements like while, for, if/else, switch/case. Control structures allow programs to execute instructions in different orders depending on conditions or to repeat steps multiple times. Keywords like break and continue change the normal flow of loops.
1. C programs consist of functions that perform specific tasks. The main() function is where program execution begins.
2. This example program prints "Welcome to C" by using functions like printf() to output text and getch() to pause the program.
3. The #include directives tell the compiler to include header files containing declarations for functions like printf() and clrscr() that are used in the program.
The document discusses control structures and functions in C programming. It defines variables and data types in C. It describes different control structures like sequence, selection, and repetition. It explains basic loops like while, for, and do-while loops. It also discusses functions, how to define functions, pass parameters, and return values. It provides examples of string handling and manipulation functions in C.
The future of DSLs - functions and formal methodsMarkus Voelter
I have used domain-specific languages to empower non-programmers in healthcare, finance, aerospace, automotive and public administration for years. My approach relies on growing the DSL from a functional programming core, combining the flexibility and power of an algorithmic language with domain-specific constructs that range from temporal data types, state machines and data models to polymorphic dispatch between versions of calculation rules. I rely on the open source MPS workbench to define the languages and their IDE. I am looking to incremental model transformations to desugar domain-specific constructs back to a minimal core language in realtime. That core language will have an interpreter for in-IDE execution and a compiler for deployment. The language will be integrated with formal methods to verify properties of programs, enabling advanced analyses for DSL users. In this talk, I will demo some existing DSLs, provide an illustration of how they are built, and demo prototypes of the future approach while discussing their integration with formal methods.
The document discusses various control structures in C++ like conditional statements (if-else, switch), loops (while, for, do-while), and jump statements (break, continue, goto). It provides examples to explain if-else, switch, while, for, do-while loops. Nested loops and break/continue statements are also covered. The last section briefly explains unconditional jump with goto statement.
This document discusses iterative statements in four programming language paradigms: imperative, object-oriented, functional, and logical. It defines key terms and provides examples of iterative constructs like for loops, while loops, and recursion in languages from each paradigm (C, Java, Lisp, Prolog). The implementation and readability of iterations are compared across paradigms. Imperative languages use loops, functional languages rely more on recursion due to lack of variables, and logical languages only use recursion to iterate.
The document discusses best practices for naming variables. It recommends initializing variables as they are declared, giving variables descriptive names to indicate their purpose, and adopting naming conventions to make code more consistent and readable for multiple programmers. Standardized prefixes and abbreviations can make long names more compact while retaining clarity. Overall, the goal is to use variable names that are meaningful, unambiguous, and help convey the essential logic of the code at a glance.
There are three main types of control structures in computer programming: sequential logic, selection logic, and iteration logic. Sequential logic executes code line-by-line. Selection logic (e.g. if/else statements) allows executing code conditionally. Iteration logic (e.g. for loops) repeats code execution in loops. The document provides examples of if/else, nested if, switch statements, and the conditional operator for implementing various control structures in C programming.
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming languages:
Like many other procedural languages, C++ provides different forms of statements for different purposes. Declaration statements are used for defining variables. Assignment-like statements are used for simple, algebraic computations. Branching statements are used for specifying alternate paths of execution, depending on the outcome of a logical condition. Loop statements are used for specifying computations which need to be repeated until a certain logical condition is satisfied. Flow control statements are used to divert the execution path to another part of the program. We will discuss these in turn.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
Branching, Looping, Conditional Statement, Exit function, Difference between break and exit. Some of the codes and some of the branching techniques are covered in this unit. Check conditional statement looping and exit functions too
https://github.com/ashim888/csit-c
Savannahs are grasslands located in Africa, India, South America, and Australia, with scattered trees and a warm climate between 20 to 30 degrees Celsius. They are dominated by grasses and shrubs and support many large herbivores and predators, though hunting, overgrazing, destruction and extinction threaten the ecosystem.
There are many criterias based on which one can choose the credit card. Some things are listed here which will help one to decide on to what basis one can choose credit card.
This document provides recommendations for mobile tools and apps for work, including the top Android phones and tablets as well as tools for email, note-taking, file storage, photo sharing, presentations, and accepting payments on mobile devices. It recommends Android and Apple devices and apps like Touchdown for email on Kindle Fire, Just Lists for notes, cloud storage options, messaging apps, read-it-later tools, news readers, and password managers. It also discusses Microsoft Office web apps and accepting payments via mobile.
The document describes several major biomes including tropical rain forests, tropical savannas, deserts, temperate grasslands, temperate forests, and tundra. Each biome has characteristic abiotic factors like climate and soil that support distinctive plant and animal communities. The document provides details on the location, climate, plants, and animals found in each biome.
The savannas are located in Africa, South America, Australia and parts of India. Animals in the savanna have developed adaptations like cheek pockets in baboons to store food and razor sharp teeth to defend against predators. Savanna plants also have adaptations like the baobab tree storing water in its thick trunk to survive dry seasons. However, human activities like fires, agriculture and hunting are threatening savanna ecosystems.
Response to Intervention (RtI) is a support system designed to identify and assist struggling students through intervention. It has three levels called tiers to monitor student progress and provide increasingly intensive interventions. While it can be effective for increasing student achievement and addressing individual student needs, implementing RtI can be time consuming for classroom teachers.
The document discusses different types of looping statements in VB.NET, including While, Do, For, and For Each loops. It provides examples and syntax for each type of loop. The key types of loops are:
- While loops repeat statements as long as a condition is true.
- Do loops execute statements first, then check a condition to repeat.
- For loops repeat a set number of times, specified by a start and end value.
- For Each loops iterate through each element of a collection, such as an array.
This document provides information about loop statements in programming. It discusses the different parts of a loop, types of loops including while, for, and do-while loops. It also covers nested loops and jump statements like break and continue. Examples are given for each loop type. The document concludes with multiple choice and program-based questions as exercises.
Visual Basic provides various control structures like selection statements (if/else), looping statements (for, while), and arrays to control program flow and work with multiple data elements. Selection statements allow programs to make decisions and perform different actions based on certain conditions. Looping statements let programs repeat blocks of code until a condition is met. Arrays allow programs to work with multiple values as a single variable. Functions and procedures let programmers organize code into reusable blocks to make programs clearer and easier to debug.
The document provides an introduction to control structures and programming concepts in Visual Basic, including decision making statements, looping statements, arrays, functions, procedures, and control arrays. It discusses various conditional structures like if-then and select-case statements. It also covers different types of loops like for-next loops and do-while loops. The use of arrays, both fixed-size and dynamic, in VB programming is explained. Finally, it discusses various built-in functions and different types of procedures in Visual Basic.
The document discusses do-while loops and switch statements in C++. It provides explanations of the syntax and flow of do-while loops, including that the code block is executed at least once before the condition is checked. It also explains switch statements, including that they provide an alternative to nested if-else statements when there are multiple choices and only one should be executed. Examples are provided of using do-while loops to display numbers and switch statements to perform arithmetic operations based on an operator.
VBScript is a lightweight scripting language that can be used for both client-side and server-side programming. It is a light version of Visual Basic. VBScript supports variables, arrays, procedures, functions, conditional statements like If-Else and Select Case, and loops like For Each, Do While, and Do Until loops. Built-in functions provide date, time, and mathematical capabilities.
The document discusses control flow statements in Java, which break up the sequential flow of execution and enable conditional execution of code blocks. It covers the following key control flow statements:
- If-then and if-then-else statements allow conditional execution based on boolean tests.
- Switch statements allow multiple possible execution paths based on a variable's value.
- Loops - while, do-while and for statements - repeatedly execute a block of code while/until a condition is met.
- Branching statements like break, continue and return alter the flow of loops or methods.
The document provides examples to illustrate the usage of each statement type.
This document discusses different types of program control statements in C++. It covers selection statements like if-else and switch that allow conditional execution of code. It also covers iteration statements like for, while, and do-while loops that allow repetitive execution of code. Additionally, it discusses jump statements like break, continue, goto, and return that allow changing the normal sequential flow of code execution. The document provides syntax and examples to explain how each of these statement types work.
The document discusses how to build high productivity applications by controlling complexity through proper use of control structures like conditionals and loops. It emphasizes keeping code easy to understand through minimum complexity, clear boolean expressions, and avoiding deeply nested structures. Following these practices improves collaboration and quality of code.
The document provides an introduction to the C programming language. It discusses the fundamentals of C including data types, variables, operators, control structures, arrays, functions, pointers, structures, unions, and file handling. The three key modules covered are: 1) C fundamentals, 2) arrays, functions, and strings, and 3) pointers, structures, unions, and file handling.
Variable, constant, operators and control statementEyelean xilef
The document discusses different programming concepts including variables, constants, operators, and control statements. It defines variables as areas of memory that hold temporary data, constants as meaningful names that do not change value, and operators as symbols that indicate operations to be performed on data. The document also examines different types of conditional statements such as if-then, if-then-else, and select case that allow a program to respond differently depending on conditions.
Variable, constant, operators and control statementEyelean xilef
The document discusses different programming concepts including variables, constants, operators, and control statements. It defines variables as areas of memory that hold temporary data, constants as meaningful names that do not change value, and operators as symbols that indicate operations to be performed on data. The document also examines different types of conditional statements such as if-then, if-then-else, and select case that allow a program to respond differently depending on conditions.
This document provides an overview of programming concepts such as what programming is, programming languages, how to write programs, and key elements of programs like variables, functions, loops, and decisions. Specifically:
- Programming involves writing instructions for a computer to accomplish tasks, using programming languages that the computer can understand. Programs must be compiled or interpreted before running.
- Pseudocode and flowcharts are used to plan programs by listing steps in plain English or using graphic symbols. Variables store data, and functions perform sub-tasks. Loops and decisions allow programs to repeat actions and make choices.
- Debugging fixes errors by testing programs step-by-step. Key symbols represent starting, input/output,
The document discusses repetition (looping) control structures in C++, including count-controlled, sentinel-controlled, and flag-controlled loops. It covers the general form of the while statement, how to properly initialize and update the loop control variable, and provides examples of using while loops to output a series of numbers, calculate a sum, and display even numbers between ranges.
Programming involves using assembly language as the common language between the programmer and microcontroller. Assembly language is translated into machine language (binary) by an assembler. Basic elements of assembly language include labels, instructions, operands, directives, and comments. Assembly language programs define parameters like the oscillator type and use directives like _CONFIG to set configuration bits before writing the code. Control directives like IF, WHILE, and FOR are used for conditional programming.
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRKrishna Raj
This document provides an overview of different types of loop statements in computer programming, including while loops, for loops, do-while loops, and nested loops. It also discusses jump statements like break, continue, goto, and exit that change the normal flow of loops. The key types of loops covered are while loops, which repeat a statement as long as a condition is true, for loops, which allow initialization of loop variables, testing a condition, and updating variables each iteration, and do-while loops, which first execute the statement and then check the condition.
Fundamentals of Programming Lecture #1.pptxEyasu46
This document provides an overview of programming and problem solving concepts. It discusses that a problem is a situation that needs resolution, while a solution removes the problematic situation. Problem solving is the process of deriving a solution. Programming involves creating computer solutions to problems through algorithms expressed as programs. Key steps for problem solving are understanding the problem, planning an algorithm/solution, implementing it as a program, testing the program, documenting it, and maintaining it for changes. Pseudocode and flowcharts are common ways to describe algorithms before implementing them as programs.
The document discusses different control structures in C++ programs including sequence, selection, and repetition. It defines each structure and provides examples. Sequence refers to executing statements in order. Selection (branching) executes different statements depending on conditions. Repetition (looping) repeats statements while conditions are met. Common control structures in C++ include if/else statements, switch statements, and various loops like while, for, and do-while loops. The document provides details on the syntax and flow of each structure.
Functions allow programmers to organize code into reusable units and divide large programs into smaller, more manageable parts. The document discusses key concepts related to functions in Python like defining and calling user-defined functions, passing arguments, scope, and recursion. It provides examples of different types of functions and how concepts like mutability impact parameter passing. Functions are a fundamental part of modular and readable program design.
This document provides an overview of programming concepts including what programming is, programming languages, how to write programs, and key elements of programs such as variables, commands/syntax, loops, decisions, and functions. It defines programming as a series of instructions for a computer to accomplish a task. It explains that programming languages allow writing programs and different languages have different rules. The document outlines the steps to write a program including using pseudocode or flowcharts, translating to a programming language, testing, and debugging. It also defines and provides examples of common programming elements.
1. Chapter 14: Repetitive Statements
CHAPTER 14: REPETITIVE STATEMENTS
Objectives
The objectives are:
• Introduce repetitive statements.
• Describe FOR statements, and provide a step-by-step examination of
a block of code containing this statement.
• Describe WHILE …DO statements, and provide a step-by-step
examination of a block of code containing this statement.
• Describe REPEAT…UNTIL statements, and provide a step-by-step
examination of a block of code containing this statement.
• Add repetitive statements to your test form, and examine the effects
of three types of sorting.
Introduction
Repetitive statements are statements that enable developers to execute one or
more other statements multiple times. There are several different types of
repetitive statements, including FOR statements, WHILE…DO statements, and
REPEAT…UNTIL statements.
This section describes these types of repetitive statements and the best
circumstances for using them. It also provides a step-by-step guide for each code
element to explain what happens at each point in an example. Finally, this section
provides several exercises that enable you to write your own repetitive
statements, and use them for different types of sorting.
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 277
Your use of this content is subject to your current services agreement
2. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
Repetitive Statements
A repetitive statement is a statement that allows developers to execute one or
more other statements multiple times. There are several kinds of repetitive
statements. One of the differences between each type of repetitive statement is
the number of times their statements are executed, and how that number is
determined. A repetitive statement is often called a loop, because when the
execution reaches the end of the repetitive statement, it loops back to the
beginning.
This section reviews three different types of repetitive statements:
• FOR statements
• WHILE…DO statements
• REPEAT…UNTIL statements
FOR Statements
The FOR statement is used when a statement is to be executed a predetermined
number of times. There are two FOR statements:
• FOR…TO
• FOR…DOWNTO
FOR…TO Statements
The most common FOR statement, FOR…TO, has this syntax:
FOR <control variable> := <start value> TO <end value> DO
<statement>
The control variable must be a variable of type Boolean, Date, Time, or any
numeric type. The start value and the end value must be either expressions that
evaluate to the same data type as the control variable or be variables of that same
data type. For example:
FOR idx := 4 TO 8 DO
Total := Total + 2.5;
In this case, the control variable (idx), the start value (4) and the end value (8) are
all integers. The following steps describe what happens:
Page 278 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
3. Chapter 14: Repetitive Statements
Step Code
1. The start value expression idx := 4
is evaluated and the
control variable is set to
the result.
2. The end value expression End value is 8
(after the TO) is evaluated.
3. The control variable is IF idx > 8, THEN
compared to the end value. The FOR statement ends.
If it is greater than the end
value, the FOR statement
is terminated.
4. The statement (after the Total := Total + 2.5
DO) is executed.
5. The control variable is idx := idx + 1 (5)
incremented by one.
6. Go to step 3 and test the
control variable again.
The net result, for this example, is that the Total variable is increased by 2.5 a
total of 5 times, therefore increasing it by 12.5. Note that both the start value and
the end value are evaluated only one time, at the beginning of the FOR statement.
Also note that the control variable's value is not changed in the FOR loop, as the
results of doing so is not predictable. Also, the value of the control variable
outside of the FOR loop (after it ends) is not defined.
Using BEGIN and END
If several statements need to be run inside the loop, then developers use a
compound statement by adding BEGIN and END. Here is an example:
FOR idx := 4 TO 8 DO BEGIN
Total := Total + 2.5;
GrandTotal := GrandTotal + Total;
END;
FOR…DOWNTO Statement
The second FOR statement, the FOR.. DOWNTO statement, has this syntax:
FOR <control variable> := <start value> DOWNTO <end value>
DO <statement>
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 279
Your use of this content is subject to your current services agreement
4. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
The rules for the control variable, start value and end value are the same as for
the FOR…TO statement. The only difference between the two is that in the
FOR… TO statement, the control variable increases in value until it is greater
than the end value, whereas in the FOR.. DOWNTO statement, the control
variable decreases in value until it is less than the end value. Here is an example
and the explanation using an array and a compound statement:
FOR idx := 9 DOWNTO 1 DO BEGIN
TotalSales := TotalSales + Sales[idx];
NumberSales := NumberSales + 1;
END;
This process for executing this code is explained in the following steps.
Step Code
1. The start value expression Idx := 9
is evaluated and the
control variable is set to
the result.
2. The end value expression End value is 1
(after the TO) is evaluated.
3. The control variable is IF idx < 1, THEN
compared to the end value. The FOR statement ends.
If it is less than the end
value, the FOR statement
is terminated.
4. The statement (after the TotalSales := TotalSales + Sales[9];
DO) is executed. NumberSales := NumberSales + 1;
5. The control variable Idx := idx - 1 (8)
decrements by one.
6. Go to step 3 and test the
control variable again.
Through each execution of the first statement in the compound statement, a
different element of the Sales array is accessed − first 9 and then 8, and so on.
The WHILE…DO Statement
The WHILE loop is used when a statement is to be executed as long as some
condition holds true. Here is the syntax of a WHILE statement:
WHILE <Boolean expression> DO <statement>
Page 280 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
5. Chapter 14: Repetitive Statements
This is simpler than the FOR statement. As long as the Boolean expression
evaluates to True, the statement, or statements if using BEGIN and END, are
executed repeatedly. Once the Boolean expression evaluates to False, the
statement is skipped and execution continues with the statement following it.
Here is an example, showing the use of a compound statement:
WHILE Sales[idx + 1] <> 0 DO BEGIN
idx := idx + 1;
TotalSales := TotalSales + Sales[idx];
END;
Here is the explanation of this code:
Step Code
1. The Boolean expression is Is Sales[idx + 1] <> 0?
evaluated. If it is true,
continue with step 2. If
not, the WHILE statement
is terminated.
2. The statement (after the idx := idx + 1;
DO) is executed. TotalSales := TotalSales + Sales[idx];
3. Go to step 1 and test the
Boolean expression again.
Note that the Boolean expression is tested before the statement is even executed
one time. If it evaluates to False from the beginning, the statement is never
executed.
Also, note that the Sales[idx] that is added to Total Sales in the WHILE loop is
the same value that was tested in the Sales[idx + 1] at the beginning of the
WHILE loop. The intervening idx := idx + 1 statement is what causes this. In
addition, once the WHILE loop has ended, idx still refers to the last non-zero
element in the Sales array.
The REPEAT…UNTIL Statement
The REPEAT statement is used when one or more statements are to be executed
until some condition becomes true. Here is the syntax of the REPEAT statement:
REPEAT <statement> { ; <statement> } UNTIL <Boolean
expression>
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 281
Your use of this content is subject to your current services agreement
6. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
There are several differences between the REPEAT and WHILE statements:
• First, there can be more than one statement between the REPEAT
and the UNTIL, even if no BEGIN and END is used.
• Secondly, the Boolean expression is not evaluated until the end, after
the statements have already been executed once.
• Third, when the Boolean expression is evaluated, it loops back to the
beginning if the expression evaluates to False and terminates the
loop if the expression evaluates to True.
Here is an example, which is almost identical to the example used for the
WHILE statement:
REPEAT
idx := idx + 1;
TotalSales := TotalSales + Sales[idx];
UNTIL Sales[idx] = 0;
The following table offers an explanation.
Step Code
1. The statements (between idx := idx + 1;
the REPEAT and the TotalSales := TotalSales + Sales[idx];
UNTIL) are executed.
2. The Boolean expression is Is Sales[idx] = 0?
evaluated. If it is true, the
REPEAT statement is
terminated. If not, go back
to step 1.
Note that since the Boolean expression is not evaluated until the end, the
statements incrementing the index and adding the TotalSales are executed even
though the value of those Sales might be zero. Therefore, at the end of this loop,
idx refers to the first Sales which equals zero, rather than the last non-zero Sales
as in the WHILE loop.
Also note that the Boolean expression had to be rewritten, since you are now
testing for a False condition to continue the loop, rather than a True expression as
in the WHILE loop.
Page 282 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
7. Chapter 14: Repetitive Statements
Lab 14.1 − Code with Repetitive Statements
In the previous section on arrays, the test form was left so that the first 10 items
you added to the list were listed, but from then on, nothing showed in the list.
You now change this so that the last ten items you added to the list always show.
Steps: Add a FOR Loop
The steps are as follows.
1. Design form 123456756.
2. Click VIEW→C/AL GLOBALS and add a variable named idx of type
integer to the current variable list.
3. Select the Execute button and open the C/AL Editor to access the
OnPush trigger code.
4. Find the code following the comment that says "Display results in
Amount column on form." Modify it so that it looks like this:
Counter := Counter + 1;
IF Counter > ARRAYLEN(Amount) THEN BEGIN
Counter := ARRAYLEN(Amount);
FOR idx := 2 TO Counter DO
Amount[idx-1] := Amount[idx];
END;
Amount[Counter] := Result;
Note that once Counter becomes greater than the length of the
Amount array, you set it back to be equal to that length.
5. Then, move each of the elements in the Amount array up by one
index, using a FOR statement. Element 2 is moved to element 1, then
element 3 is moved to element 2, and so on. Finally, element 10 is
moved to element 9 and then the FOR loop ends. The new result is
then moved into the last element in the array.
6. Close, compile, save, and then run the form.
7. Enter some values, click the Execute button, and watch what
happens. Until the list is filled, nothing changes, but watch what
happens when you have pressed the Execute button more than ten
times.
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 283
Your use of this content is subject to your current services agreement
8. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
Steps: Sorting − Phase I
The sorting steps are as follows.
1. Design the form and add a new Command button with its Caption
property set to Sort.
2. Select the Sort button and press F9 to open the C/AL Editor. In the
OnPush trigger, add the following code:
FOR idx := ARRAYLEN(Amount) DOWNTO 2 DO
IF Amount[idx] < Amount[idx-1] THEN BEGIN
TempAmount := Amount[idx];
Amount[idx] := Amount[idx-1];
Amount[idx-1] := TempAmount;
END;
3. For this code to compile, you also need to add a variable called
TempAmount of type Decimal.
4. Close, save, compile, and then run the form.
5. Fill in some values and click the Execute button, entering differing
quantities each time until the column is full.
6. Click the Sort button.
What happens?
7. Click the Sort button again.
What happened this time?
8. Continue clicking the Sort button until nothing further happens.
Note that at this point all entries are sorted. Now, examine the
previous code and answer the following questions. Execute the code
manually if necessary.
o Why in the FOR statement do we only go down to 2
rather than all the way to 1?
o Why do we not need a BEGIN after the DO in the FOR
statement?
o What is taking place in the three lines of the compound
statement (between BEGIN and END)?
Page 284 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
9. Chapter 14: Repetitive Statements
o Why is TempAmount used for this?
o If the entries in the column had been made exactly in the
wrong order (highest to lowest), how many times does
the Sort button have to be clicked to sort the list?
Steps: Sorting − Phase II
Obviously, it is better if the user just clicks the Sort button once and has the list
completely sorted. Note, however, that sometimes one click of the button may
work, while other times more are needed. A FOR loop is inappropriate for this,
because you do not know in advance how many times it takes.
For this situation, a REPEAT loop works best.
1. Add a new variable called IsSorted of type Boolean.
2. Modify the Sort button's OnPush code as follows:
REPEAT
IsSorted := TRUE;
FOR idx := ARRAYLEN(Amount) DOWNTO 2 DO
IF Amount[idx] < Amount[idx-1] THEN BEGIN
TempAmount := Amount[idx];
Amount[idx] := Amount[idx-1];
Amount[idx-1] := TempAmount;
IsSorted := FALSE;
END;
UNTIL IsSorted;
Note that the IsSorted variable is used as a signal to tell whether you
are finished sorting.
3. Set the IsSorted variable to TRUE at the beginning of each
REPEAT loop, and if you ever have to swap two elements because
the list is not in order, set it to FALSE.
4. At the end of the REPEAT loop, check to see if it is TRUE. If it is,
all of the elements are in order, since none needed to be swapped and
therefore you can exit the loop.
If not, the loop is repeated again. When using a Boolean variable as a
signal in this way, programmers sometimes call it a flag.
Also, note that you cannot tell whether the list is sorted unless it is
actually run through at least one time. That is why REPEAT is used
here, rather than a WHILE loop.
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 285
Your use of this content is subject to your current services agreement
10. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
5. Close, save, compile, and run the form.
6. Perform the same experiment as before, filling in the table with
values and then clicking the Sort button. Note that the list is
completely sorted with one click.
o Look at the IF statement again. You used the less than
(<) operator to compare the elements. What happens if
you changed this to the greater than (>) operator?
o Test the case where two elements happen to have the
same value. Once you find out, change it back to the less
than operator for the next exercise.
Steps: Sorting − Phase III
You now have a perfectly good sorting routine, which works well for small
arrays. But notice that you wrote it so that it can take arrays of any size. In cases
where you have 100 elements, 1,000 elements, or 10,000 elements, you need a
really efficient sorting routine. You created "nested" loops when you put one
loop (the FOR loop) inside another loop (the REPEAT loop). Whenever there are
nested loops, there is always a potential for inefficiency, especially as the number
of elements increase. The question becomes how many times will the innermost
loop be executed
For example, in the case in the Sorting – Phase II section, whenever the FOR
loop is executed once, the IF statement is executed 9 times, because the length of
the array is 10, but you are not going all the way to 1. If the REPEAT loop has to
be executed 9 times, the FOR loop will be executed nine times and the IF
statement will be executed 9 * 9 = 81 times. However, if the array length goes up
to 100, the IF statement will be executed 99 times per FOR statement and the
FOR statement may be executed by the REPEAT loop up to 99 times. In this
situation, the IF statement might be executed up to 99 * 99 = 9,801 times.
You can reduce this substantially, by remembering what happened when the FOR
loop was written by itself. Every time it ran, the lowest element rose to the top.
That means that the first element never needs to be tested again, once the first
FOR loop was run. Once the second FOR loop was run, you never need to test
the first two elements again. Each loop needs fewer and fewer tests to do its job.
And this is the worst case. Sometimes, when the Sort button was clicked, the
first three elements became sorted and you never needed to test any of the first
three again.
Here is how you can take advantage of this.
1. First, create an integer variable called LowestSwitch.
2. Rewrite the sorting routine so it looks like this:
Page 286 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
11. Chapter 14: Repetitive Statements
LowestSwitch := 2;
REPEAT
IsSorted := TRUE;
FOR idx := ARRAYLEN(Amount) DOWNTO LowestSwitch
DO
IF Amount[idx] < Amount[idx-1] THEN BEGIN
TempAmount := Amount[idx];
Amount[idx] := Amount[idx-1];
Amount[idx-1] := TempAmount;
IsSorted := FALSE;
LowestSwitch := idx + 1;
END;
UNTIL IsSorted;
Instead of sorting down to 2 (comparing with 1) every time, now the
FOR loops says to sort down to LowestSwitch (comparing with
LowestSwitch - 1). LowestSwitch starts out as 2, but each time two
values are switched (in the THEN clause of the IF statement), it is
reset to one more than the element currently being switched.
Since the FOR loop works down, at the end, LowestSwitch is the
lowest element to test next time around. Even in the worst case, it is
one higher than the previous value and it might be several higher.
Each one higher is one less to test and the savings are compounded
as you go through the sort.
For example, if the array has ten elements, then in the worst case,
you will execute the innermost IF statement 9 * 9 = 81 times. In the
worst case, you will execute the innermost IF statement 9 + 8 + 7 + 6
+ 5 + 4 + 3 + 2 + 1 times = 45 times. If the array has 100 elements,
the worst case goes from 9,801 executions down to 4,950.
In other words, this simple modification makes the sort go twice as
fast and therefore takes half as long to execute.
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 287
Your use of this content is subject to your current services agreement
12. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
Conclusion
This section has described repetitive statements, which are statements that enable
developers to execute one or more other statements multiple times. Several types
of repetitive statements, including FOR statements, WHILE…DO statements,
and REPEAT…UNTIL statements have been described and examples of each
have been provided. You have written your own FOR loops, and then you have
sorted your amounts in three ways, FOR and REPEAT statements. The next
section describes WITH and CASE statements.
Page 288 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement
13. Chapter 14: Repetitive Statements
Test Your Knowledge
1. Which repetitive statement do you use if you can determine, before
you started, how many times your statements have to be executed?
2. Which repetitive statement does not require a BEGIN and END to
execute more than one statement repetitively?
3. Which repetitive statements test the condition at the beginning of
each loop?
4. Rewrite the following WHILE statement as a REPEAT statement.
Describe the differences in how it is executed.
WHILE X > 0 DO BEGIN
Y := A * X * X + B * X + C;
X := X - 1;
END;
Microsoft Official Training Materials for Microsoft Dynamics ™ Page 289
Your use of this content is subject to your current services agreement
14. C/SIDE Introduction in Microsoft Dynamics NAV 5.0
Quick Interaction: Lessons Learned
Take a moment to write down three key points you have learned from this
chapter:
1.
2.
3.
Page 290 Microsoft Official Training Materials for Microsoft Dynamics ™
Your use of this content is subject to your current services agreement