This document outlines an introductory chapter on control structures in programming. It discusses various programming concepts like algorithms, pseudocode, control structures including sequence, selection, and repetition structures. Specific control structures covered include if, if/else, while, for, switch, do/while, break and continue. Logical operators and the difference between equality and assignment operators are also mentioned. The chapter provides examples and case studies to explain counter-controlled and sentinel-controlled repetition with while loops. It introduces various C++ keywords and shows how pseudocode can be translated to C++ code. Flowcharts are used to visualize program flow and control structures.
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...ronistgdr
The document discusses various control structures used in programming, including selection structures like if/else and repetition structures like while and for loops. It provides examples of pseudocode and C++ code to illustrate counter-controlled and sentinel-controlled repetition. Key control structures like if/else and while are explained, along with flowcharts to visualize program logic. Top-down and stepwise refinement techniques are covered for developing algorithms.
Control structures allow programs to execute code conditionally or repeatedly. There are three basic structures: sequence, selection, and repetition. Selection structures like if/else are used to choose between alternatives. Repetition structures like while loops repeat an action as long as a condition is true. Programs can be represented graphically with flowcharts to show how the structures are combined.
more loops lecture by Professor Evan korth hammad ali
The document summarizes an upcoming lecture on loops. It provides the schedule, outlines topics to be covered including sentinels, sentinel-controlled loops, and nested control structures. Examples of using sentinels to end a loop based on user input and a case study on analyzing test results are discussed. Key terms like sentinel, initialization, processing, and termination are also introduced.
This document outlines control structures in programming, including selection structures like if/else and repetition structures like while and for loops. It provides examples of algorithms using pseudocode and C++ code that employ counter-controlled and sentinel-controlled repetition. Key concepts covered include flowcharts, logical operators, and avoiding logic errors. Nested control structures and the switch statement are also discussed.
This document discusses control structures in programming, including sequence, selection, and repetition structures. It provides examples of if/else selection structures and while repetition structures in pseudocode and C++ code. It also covers nested control structures, flowcharts, and different types of repetition structures like counter-controlled and sentinel-controlled loops. Examples are provided to calculate a class average based on grades input by the user using these different looping techniques.
The Three Basic Selection Structures in C++ Programming ConceptsTech
Now check the powerpoint presentation about selection structures in programming. For more visit www.techora.net
Three types of selection structures are available like :
1 - Sequence Structure
2 - Selection Strcuture
3 - Repetition Structure
In this PPT slide, we discuss about the selection structure
1 - if statements
2 - if else statement
3 - switch statement
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
This document provides an overview of primitive data types, expressions, and definite loops (for loops) in Java. It discusses Java's primitive types like int, double, char, and boolean. It covers arithmetic operators, precedence rules, and mixing numeric types. It also introduces variables, declarations, assignments, and using variables in expressions. Finally, it explains the syntax of for loops using initialization, a test condition, and an update to repeat a block of code a specified number of times.
The document discusses loops and repetition structures in C++. It explains while loops, their syntax, and how they work. A while loop repeats actions while a condition is true. Each iteration, the condition is evaluated. If true, the loop body executes and control returns to the condition. If false, execution continues after the loop. Pseudocode and C++ code examples are provided to illustrate how a while loop can be used to repeatedly purchase items from a shopping list until it is empty. Flowcharts further demonstrate the flow of control in a while loop.
The document provides an overview of computational thinking and problem solving. It discusses key concepts like algorithms, the building blocks of algorithms including statements, state, control flow, functions. It also covers different notations for representing algorithms - pseudocode, flowcharts, programming languages. Some key aspects covered include the definition of an algorithm, properties and qualities of a good algorithm. Examples are provided for different algorithm concepts like finding the minimum/maximum value, sorting cards etc.
The document discusses problem-solving and design skills needed for computer programming. It covers several key topics:
1. Candidates should understand top-down design and be able to break down computer systems into subsystems using structure diagrams, flowcharts, pseudocode, and subroutines.
2. Candidates should be able to work with algorithms - explaining them, suggesting test data, and identifying/fixing errors. They should be able to produce algorithms for problems.
3. Top-down design is described as the process of breaking down a computer system into subsystems, then breaking each subsystem into smaller subsystems, until each performs a single action.
The document is an outline from a textbook on C programming. It covers basic concepts like simple programs to print text and perform math operations, use of variables and data types, memory concepts, decision making using if statements and relational operators. It includes examples of simple C programs and explanations of the core components like main function, comments, preprocessor directives, functions etc.
The Triangle class lab involves creating a Triangle class that defines properties and methods for triangles. The Triangle class contains private data members for the three sides of the triangle. It includes public methods to calculate the area and perimeter of a triangle using the side lengths, get the side lengths, set the side lengths, determine the triangle type, and print triangle information. The main() function constructs a Triangle object and calls its methods to demonstrate the class functionality in 3 sentences or less.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
The document is a chapter from an introductory C programming textbook. It covers basic C concepts like comments, variables, data types, functions, input/output, arithmetic operators, and conditional statements. It includes examples of simple C programs that print text, get user input, perform addition, and test for equality/relations between numbers. The chapter lays out fundamental building blocks to prepare the reader for more advanced C programming concepts covered later.
The document discusses algorithms and their implementation in computer programs. It defines algorithms as step-by-step instructions to solve a problem and provides examples like recipes and driving directions. Computer algorithms are implemented as programs through programming languages. The document also discusses different types of control structures like sequential, selection, and iteration logic that are used to control the flow and logic of algorithms and programs.
This document provides an overview of introductory concepts in C programming, including simple programs to print text and perform arithmetic. It covers basic syntax like comments, functions, variables, data types, operators, input/output, and conditional statements. Memory concepts are introduced, as well as the preprocessor, standard libraries, and control flow structures like if/else. Examples are provided to demonstrate printing text, taking user input, performing calculations, and making decisions based on relational comparisons.
This document provides an overview of problem solving and Python programming. It discusses computational thinking and problem solving, including identifying computational problems, algorithms, building blocks of algorithms, and illustrative problems. It also discusses algorithmic problem solving techniques like iteration and recursion. Finally, it briefly introduces the course titled "GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING".
This document outlines the phases of making an executable code from a problem statement. It discusses drawing a flowchart to represent the logical steps, then translating this into a program using a programming language. The key phases are:
1) Drawing a flowchart to plan the program's logic and data flows
2) Writing code by translating the flowchart into a programming language
3) Compiling and debugging the code to fix any syntax errors
4) Testing the executable program to check for logic errors
5) Documenting the program for future use and maintenance
The document discusses various software testing strategies and techniques. It begins by explaining the importance of testing software before customers use it in order to reduce errors. It then describes different testing techniques including white-box testing, which tests the internal logic and paths of a program, and black-box testing, which tests the inputs and outputs against requirements without considering internal logic. The document provides examples of specific strategies like branch coverage, basis path testing, and boundary value analysis. It also discusses test case documentation and different testing phases from unit to integration to system testing.
Introduction to ANN, McCulloch Pitts Neuron, Perceptron and its Learning
Algorithm, Sigmoid Neuron, Activation Functions: Tanh, ReLu Multi- layer Perceptron
Model – Introduction, learning parameters: Weight and Bias, Loss function: Mean
Square Error, Back Propagation Learning Convolutional Neural Network, Building
blocks of CNN, Transfer Learning, R-CNN,Auto encoders, LSTM Networks, Recent
Trends in Deep Learning.
This research is oriented towards exploring mode-wise corridor level travel-time estimation using Machine learning techniques such as Artificial Neural Network (ANN) and Support Vector Machine (SVM). Authors have considered buses (equipped with in-vehicle GPS) as the probe vehicles and attempted to calculate the travel-time of other modes such as cars along a stretch of arterial roads. The proposed study considers various influential factors that affect travel time such as road geometry, traffic parameters, location information from the GPS receiver and other spatiotemporal parameters that affect the travel-time. The study used a segment modeling method for segregating the data based on identified bus stop locations. A k-fold cross-validation technique was used for determining the optimum model parameters to be used in the ANN and SVM models. The developed models were tested on a study corridor of 59.48 km stretch in Mumbai, India. The data for this study were collected for a period of five days (Monday-Friday) during the morning peak period (from 8.00 am to 11.00 am). Evaluation scores such as MAPE (mean absolute percentage error), MAD (mean absolute deviation) and RMSE (root mean square error) were used for testing the performance of the models. The MAPE values for ANN and SVM models are 11.65 and 10.78 respectively. The developed model is further statistically validated using the Kolmogorov-Smirnov test. The results obtained from these tests proved that the proposed model is statistically valid.
Ad
More Related Content
Similar to Structured Program Development in C Language (20)
This document provides an overview of topics covered in a C++ programming course, including:
- Introduction to C++ language fundamentals like data types, variables, operators, control structures, functions, and classes
- Memory concepts, arithmetic, decision making, and algorithms
- Structured and object-oriented programming principles
- The basics of the C++ environment like compilers, linkers, and input/output streams
- Common library functions and concepts like headers, prototypes, and enumerations
The document serves as an introductory reference for anyone learning C++ or wanting to understand the basic building blocks of the language.
This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
This document provides an overview of primitive data types, expressions, and definite loops (for loops) in Java. It discusses Java's primitive types like int, double, char, and boolean. It covers arithmetic operators, precedence rules, and mixing numeric types. It also introduces variables, declarations, assignments, and using variables in expressions. Finally, it explains the syntax of for loops using initialization, a test condition, and an update to repeat a block of code a specified number of times.
The document discusses loops and repetition structures in C++. It explains while loops, their syntax, and how they work. A while loop repeats actions while a condition is true. Each iteration, the condition is evaluated. If true, the loop body executes and control returns to the condition. If false, execution continues after the loop. Pseudocode and C++ code examples are provided to illustrate how a while loop can be used to repeatedly purchase items from a shopping list until it is empty. Flowcharts further demonstrate the flow of control in a while loop.
The document provides an overview of computational thinking and problem solving. It discusses key concepts like algorithms, the building blocks of algorithms including statements, state, control flow, functions. It also covers different notations for representing algorithms - pseudocode, flowcharts, programming languages. Some key aspects covered include the definition of an algorithm, properties and qualities of a good algorithm. Examples are provided for different algorithm concepts like finding the minimum/maximum value, sorting cards etc.
The document discusses problem-solving and design skills needed for computer programming. It covers several key topics:
1. Candidates should understand top-down design and be able to break down computer systems into subsystems using structure diagrams, flowcharts, pseudocode, and subroutines.
2. Candidates should be able to work with algorithms - explaining them, suggesting test data, and identifying/fixing errors. They should be able to produce algorithms for problems.
3. Top-down design is described as the process of breaking down a computer system into subsystems, then breaking each subsystem into smaller subsystems, until each performs a single action.
The document is an outline from a textbook on C programming. It covers basic concepts like simple programs to print text and perform math operations, use of variables and data types, memory concepts, decision making using if statements and relational operators. It includes examples of simple C programs and explanations of the core components like main function, comments, preprocessor directives, functions etc.
The Triangle class lab involves creating a Triangle class that defines properties and methods for triangles. The Triangle class contains private data members for the three sides of the triangle. It includes public methods to calculate the area and perimeter of a triangle using the side lengths, get the side lengths, set the side lengths, determine the triangle type, and print triangle information. The main() function constructs a Triangle object and calls its methods to demonstrate the class functionality in 3 sentences or less.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
The document discusses Java's primitive data types and for loops. It introduces Java's primitive types like int, double, char, and boolean. It covers expressions, operators, and precedence. It then introduces variables, declaring and initializing variables, and using variables in expressions. Finally, it covers the for loop structure with initialization, test, and update sections to allow repetition of code.
The document is a chapter from an introductory C programming textbook. It covers basic C concepts like comments, variables, data types, functions, input/output, arithmetic operators, and conditional statements. It includes examples of simple C programs that print text, get user input, perform addition, and test for equality/relations between numbers. The chapter lays out fundamental building blocks to prepare the reader for more advanced C programming concepts covered later.
The document discusses algorithms and their implementation in computer programs. It defines algorithms as step-by-step instructions to solve a problem and provides examples like recipes and driving directions. Computer algorithms are implemented as programs through programming languages. The document also discusses different types of control structures like sequential, selection, and iteration logic that are used to control the flow and logic of algorithms and programs.
This document provides an overview of introductory concepts in C programming, including simple programs to print text and perform arithmetic. It covers basic syntax like comments, functions, variables, data types, operators, input/output, and conditional statements. Memory concepts are introduced, as well as the preprocessor, standard libraries, and control flow structures like if/else. Examples are provided to demonstrate printing text, taking user input, performing calculations, and making decisions based on relational comparisons.
This document provides an overview of problem solving and Python programming. It discusses computational thinking and problem solving, including identifying computational problems, algorithms, building blocks of algorithms, and illustrative problems. It also discusses algorithmic problem solving techniques like iteration and recursion. Finally, it briefly introduces the course titled "GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING".
This document outlines the phases of making an executable code from a problem statement. It discusses drawing a flowchart to represent the logical steps, then translating this into a program using a programming language. The key phases are:
1) Drawing a flowchart to plan the program's logic and data flows
2) Writing code by translating the flowchart into a programming language
3) Compiling and debugging the code to fix any syntax errors
4) Testing the executable program to check for logic errors
5) Documenting the program for future use and maintenance
The document discusses various software testing strategies and techniques. It begins by explaining the importance of testing software before customers use it in order to reduce errors. It then describes different testing techniques including white-box testing, which tests the internal logic and paths of a program, and black-box testing, which tests the inputs and outputs against requirements without considering internal logic. The document provides examples of specific strategies like branch coverage, basis path testing, and boundary value analysis. It also discusses test case documentation and different testing phases from unit to integration to system testing.
Introduction to ANN, McCulloch Pitts Neuron, Perceptron and its Learning
Algorithm, Sigmoid Neuron, Activation Functions: Tanh, ReLu Multi- layer Perceptron
Model – Introduction, learning parameters: Weight and Bias, Loss function: Mean
Square Error, Back Propagation Learning Convolutional Neural Network, Building
blocks of CNN, Transfer Learning, R-CNN,Auto encoders, LSTM Networks, Recent
Trends in Deep Learning.
This research is oriented towards exploring mode-wise corridor level travel-time estimation using Machine learning techniques such as Artificial Neural Network (ANN) and Support Vector Machine (SVM). Authors have considered buses (equipped with in-vehicle GPS) as the probe vehicles and attempted to calculate the travel-time of other modes such as cars along a stretch of arterial roads. The proposed study considers various influential factors that affect travel time such as road geometry, traffic parameters, location information from the GPS receiver and other spatiotemporal parameters that affect the travel-time. The study used a segment modeling method for segregating the data based on identified bus stop locations. A k-fold cross-validation technique was used for determining the optimum model parameters to be used in the ANN and SVM models. The developed models were tested on a study corridor of 59.48 km stretch in Mumbai, India. The data for this study were collected for a period of five days (Monday-Friday) during the morning peak period (from 8.00 am to 11.00 am). Evaluation scores such as MAPE (mean absolute percentage error), MAD (mean absolute deviation) and RMSE (root mean square error) were used for testing the performance of the models. The MAPE values for ANN and SVM models are 11.65 and 10.78 respectively. The developed model is further statistically validated using the Kolmogorov-Smirnov test. The results obtained from these tests proved that the proposed model is statistically valid.
Dear SICPA Team,
Please find attached a document outlining my professional background and experience.
I remain at your disposal should you have any questions or require further information.
Best regards,
Fabien Keller
Newly poured concrete opposing hot and windy conditions is considerably susceptible to plastic shrinkage cracking. Crack-free concrete structures are essential in ensuring high level of durability and functionality as cracks allow harmful instances or water to penetrate in the concrete resulting in structural damages, e.g. reinforcement corrosion or pressure application on the crack sides due to water freezing effect. Among other factors influencing plastic shrinkage, an important one is the concrete surface humidity evaporation rate. The evaporation rate is currently calculated in practice by using a quite complex Nomograph, a process rather tedious, time consuming and prone to inaccuracies. In response to such limitations, three analytical models for estimating the evaporation rate are developed and evaluated in this paper on the basis of the ACI 305R-10 Nomograph for “Hot Weather Concreting”. In this direction, several methods and techniques are employed including curve fitting via Genetic Algorithm optimization and Artificial Neural Networks techniques. The models are developed and tested upon datasets from two different countries and compared to the results of a previous similar study. The outcomes of this study indicate that such models can effectively re-develop the Nomograph output and estimate the concrete evaporation rate with high accuracy compared to typical curve-fitting statistical models or models from the literature. Among the proposed methods, the optimization via Genetic Algorithms, individually applied at each estimation process step, provides the best fitting result.
Design of Variable Depth Single-Span Post.pdfKamel Farid
Hunched Single Span Bridge: -
(HSSBs) have maximum depth at ends and minimum depth at midspan.
Used for long-span river crossings or highway overpasses when:
Aesthetically pleasing shape is required or
Vertical clearance needs to be maximized
The TRB AJE35 RIIM Coordination and Collaboration Subcommittee has organized a series of webinars focused on building coordination, collaboration, and cooperation across multiple groups. All webinars have been recorded and copies of the recording, transcripts, and slides are below. These resources are open-access following creative commons licensing agreements. The files may be found, organized by webinar date, below. The committee co-chairs would welcome any suggestions for future webinars. The support of the AASHTO RAC Coordination and Collaboration Task Force, the Council of University Transportation Centers, and AUTRI’s Alabama Transportation Assistance Program is gratefully acknowledged.
This webinar overviews proven methods for collaborating with USDOT University Transportation Centers (UTCs), emphasizing state departments of transportation and other stakeholders. It will cover partnerships at all UTC stages, from the Notice of Funding Opportunity (NOFO) release through proposal development, research and implementation. Successful USDOT UTC research, education, workforce development, and technology transfer best practices will be highlighted. Dr. Larry Rilett, Director of the Auburn University Transportation Research Institute will moderate.
For more information, visit: https://aub.ie/trbwebinars
The use of huge quantity of natural fine aggregate (NFA) and cement in civil construction work which have given rise to various ecological problems. The industrial waste like Blast furnace slag (GGBFS), fly ash, metakaolin, silica fume can be used as partly replacement for cement and manufactured sand obtained from crusher, was partly used as fine aggregate. In this work, MATLAB software model is developed using neural network toolbox to predict the flexural strength of concrete made by using pozzolanic materials and partly replacing natural fine aggregate (NFA) by Manufactured sand (MS). Flexural strength was experimentally calculated by casting beams specimens and results obtained from experiment were used to develop the artificial neural network (ANN) model. Total 131 results values were used to modeling formation and from that 30% data record was used for testing purpose and 70% data record was used for training purpose. 25 input materials properties were used to find the 28 days flexural strength of concrete obtained from partly replacing cement with pozzolans and partly replacing natural fine aggregate (NFA) by manufactured sand (MS). The results obtained from ANN model provides very strong accuracy to predict flexural strength of concrete obtained from partly replacing cement with pozzolans and natural fine aggregate (NFA) by manufactured sand.
The main purpose of the current study was to formulate an empirical expression for predicting the axial compression capacity and axial strain of concrete-filled plastic tubular specimens (CFPT) using the artificial neural network (ANN). A total of seventy-two experimental test data of CFPT and unconfined concrete were used for training, testing, and validating the ANN models. The ANN axial strength and strain predictions were compared with the experimental data and predictions from several existing strength models for fiber-reinforced polymer (FRP)-confined concrete. Five statistical indices were used to determine the performance of all models considered in the present study. The statistical evaluation showed that the ANN model was more effective and precise than the other models in predicting the compressive strength, with 2.8% AA error, and strain at peak stress, with 6.58% AA error, of concrete-filled plastic tube tested under axial compression load. Similar lower values were obtained for the NRMSE index.
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia
In the world of technology, Jacob Murphy Australia stands out as a Junior Software Engineer with a passion for innovation. Holding a Bachelor of Science in Computer Science from Columbia University, Jacob's forte lies in software engineering and object-oriented programming. As a Freelance Software Engineer, he excels in optimizing software applications to deliver exceptional user experiences and operational efficiency. Jacob thrives in collaborative environments, actively engaging in design and code reviews to ensure top-notch solutions. With a diverse skill set encompassing Java, C++, Python, and Agile methodologies, Jacob is poised to be a valuable asset to any software development team.
1. 2000 Prentice Hall, Inc. All rights reserved.
Chapter 3 - Structured Program
Development
Outline
3.1 Introduction
3.2 Algorithms
3.3 Pseudocode
3.4 Control Structures
3.5 The If Selection Structure
3.6 The If/Else Selection Structure
3.7 The While Repetition Structure
3.8 Formulating Algorithms: Case Study 1 (Counter-Controlled
Repetition)
3.9 Formulating Algorithms with Top-down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)
3.10 Formulating Algorithms with Top-down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)
3.11 Assignment Operators
3.12 Increment and Decrement Operators
2. 2000 Prentice Hall, Inc. All rights reserved.
3.1 Introduction
• Before writing a program:
– Have a thorough understanding of problem
– Carefully planned approach for solving it
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles
3. 2000 Prentice Hall, Inc. All rights reserved.
3.2 Algorithms
• Computing problems
– All can be solved by executing a series of actions in a specific
order
• Algorithm: procedure in terms of
– Actions to be executed
– Order in which these actions are to be executed
• Program control
– Specify order in which statements are to executed
4. 2000 Prentice Hall, Inc. All rights reserved.
3.3 Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding C++ program
• Consists only of executable statements
5. 2000 Prentice Hall, Inc. All rights reserved.
3.4 Control Structures
• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in sequence
– Overuse of goto led to many problems.
• Bohm and Jacopini
– All programs written in terms of 3 control structures
• Sequence structure: Built into C. Programs executed sequentially by
default.
• Selection structures: C has three types- if, if/else, and switch .
• Repetition structures: C has three types - while, do/while, and
for.
• These are C keywords
6. 2000 Prentice Hall, Inc. All rights reserved.
3.4 Control Structures (II)
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols connected by arrows
called flowlines.
– Rectangle symbol (action symbol): indicates any type of action.
– Oval symbol: indicates beginning or end of a program, or a section
of code (circles).
• Single-entry/single-exit control structures
– Connect exit point of one control structure to entry point of the
next (control-structure stacking).
– Makes programs easy to build
7. 2000 Prentice Hall, Inc. All rights reserved.
3.5 The if Selection Structure
• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode: If student’s grade is greater than or equal to 60
Print “Passed”
• If condition true
– Print statement executed and program goes on to next statement.
– If false, print statement is ignored and the program goes onto the next
statement.
– Indenting makes programs easier to read
• C ignores whitespace characters.
• Pseudocode statement in C:
if ( grade >= 60 )
printf( "Passedn" );
– C code corresponds closely to the pseudocode
8. 2000 Prentice Hall, Inc. All rights reserved.
3.5 The if Selection Structure (II)
true
false
grade >= 60 print “Passed”
• Diamond symbol (decision symbol) - indicates decision is to be made
• Contains an expression that can be true or false
• Test the condition, follow appropriate path
• if structure is a single-entry/single-exit structure.
A decision can be made on
any expression.
zero - false
nonzero - true
Example:
3 - 4 is true
9. 2000 Prentice Hall, Inc. All rights reserved.
3.6 The if/else Selection Structure
• if
– Only performs an action if the condition is true.
• if/else
– A different action when condition is true than when condition is false
• Psuedocode: If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
– Note spacing/indentation conventions
• C code: if ( grade >= 60 )
printf( "Passedn");
else
printf( "Failedn");
10. 2000 Prentice Hall, Inc. All rights reserved.
3.6 The if/else Selection Structure (II)
• Ternary conditional operator (?:)
– Takes three arguments (condition, value if true, value if false)
– Our pseudocode could be written:
printf( "%sn", grade >= 60 ? "Passed" : "Failed" );
OR
grade >= 60 ? printf( “Passedn” ) : printf( “Failedn” );
true
false
print “Failed” print “Passed”
grade >= 60
11. 2000 Prentice Hall, Inc. All rights reserved.
3.6 The if/else Selection Structure (III)
• Nested if/else structures
– Test for multiple cases by placing if/else selection structures inside
if/else selection structures
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
– Once condition is met, rest of statements skipped
– Deep indentation usually not used in practice
12. 2000 Prentice Hall, Inc. All rights reserved.
3.6 The if/else Selection Structure (IV)
• Compound statement:
– Set of statements within a pair of braces
– Example:
if ( grade >= 60 )
printf( "Passed.n" );
else {
printf( "Failed.n" );
printf( "You must take this course again.n" );
}
– Without the braces,
printf( "You must take this course again.n" );
would be automatically executed
• Block: compound statements with declarations
13. 2000 Prentice Hall, Inc. All rights reserved.
3.6 The if/else Selection Structure (V)
• Syntax errors
– Caught by compiler
• Logic errors:
– Have their effect at execution time
– Non-fatal: program runs, but has incorrect output
– Fatal: program exits prematurely
14. 2000 Prentice Hall, Inc. All rights reserved.
3.7 The while Repetition Structure
• Repetition structure
– Programmer to specifies an action to be repeated while some
condition remains true
– Psuedocode: While there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
15. 2000 Prentice Hall, Inc. All rights reserved.
3.7 The while Repetition Structure (II)
• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
product <= 1000 product = 2 * product
true
false
16. 2000 Prentice Hall, Inc. All rights reserved.
3.8 Formulating Algorithms (Counter-
Controlled Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value.
– Definite repetition: number of repetitions is known
– Example: A class of ten students took a quiz. The grades (integers in the
range 0 to 100) for this quiz are available to you. Determine the class
average on the quiz.
• Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
17. 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Initialize Variables
2. Execute Loop
3. Output results
1 /* Fig. 3.6: fig03_06.c
2 Class average program with
3 counter-controlled repetition */
4 #include <stdio.h>
5
6 int main()
7 {
8 int counter, grade, total, average;
9
10 /* initialization phase */
11 total = 0;
12 counter = 1;
13
14 /* processing phase */
15 while ( counter <= 10 ) {
16 printf( "Enter grade: " );
17 scanf( "%d", &grade );
18 total = total + grade;
19 counter = counter + 1;
20 }
21
22 /* termination phase */
23 average = total / 10;
24 printf( "Class average is %dn", average );
25
26 return 0; /* indicate program ended successfully */
27 }
18. 2000 Prentice Hall, Inc. All rights reserved.
Outline
Program Output
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
19. 2000 Prentice Hall, Inc. All rights reserved.
3.9 Formulating Algorithms with Top-Down,
Stepwise Refinement (Sentinel-Controlled
Repetition)
• Problem becomes:
Develop a class-averaging program that will process an arbitrary
number of grades each time the program is run.
– Unknown number of students
– How will the program know to end?
• Use sentinel value
– Also called signal value, dummy value, or flag value
– Indicates “end of data entry.”
– Loop ends when sentinel inputted
– Sentinel value chosen so it cannot be confused with a regular input
(such as -1 in this case)
20. 2000 Prentice Hall, Inc. All rights reserved.
3.9 Formulating Algorithms with Top-Down,
Stepwise Refinement (Sentinel-Controlled
Repetition) (II)
• Top-down, stepwise refinement
– Begin with a pseudocode representation of the top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
• Many programs have three phases
– Initialization: initializes the program variables
– Processing: inputs data values and adjusts program variables
accordingly
– Termination: calculates and prints the final results
– This Helps the breakup of programs for top-down refinement
21. 2000 Prentice Hall, Inc. All rights reserved.
3.9 Formulating Algorithms with Top-Down,
Stepwise Refinement (III)
• Refine the initialization phase from Initialize variables to:
Initialize total to zero
Initialize counter to zero
• Refine Input, sum and count the quiz grades to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
• Refine Calculate and print the class average to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
22. 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Initialize Variables
2. Get user input
2.1 Perform Loop
1 /* Fig. 3.8: fig03_08.c
2 Class average program with
3 sentinel-controlled repetition */
4 #include <stdio.h>
5
6 int main()
7 {
8 float average; /* new data type */
9 int counter, grade, total;
10
11 /* initialization phase */
12 total = 0;
13 counter = 0;
14
15 /* processing phase */
16 printf( "Enter grade, -1 to end: " );
17 scanf( "%d", &grade );
18
19 while ( grade != -1 ) {
20 total = total + grade;
21 counter = counter + 1;
22 printf( "Enter grade, -1 to end: " );
23 scanf( "%d", &grade );
24 }
23. 2000 Prentice Hall, Inc. All rights reserved.
Outline
3. Calculate Average
3.1 Print Results
Program Output
25
26 /* termination phase */
27 if ( counter != 0 ) {
28 average = ( float ) total / counter;
29 printf( "Class average is %.2f", average );
30 }
31 else
32 printf( "No grades were enteredn" );
33
34 return 0; /* indicate program ended successfully */
35 }
Enter grade, -1 to end: 75
Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
24. 2000 Prentice Hall, Inc. All rights reserved.
3.10 Nested control structures
• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students.
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2
25. 2000 Prentice Hall, Inc. All rights reserved.
3.10 Nested control structures (II)
• Top level outline
Analyze exam results and decide if tuition should be raised
• First Refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition should be raised
• Refine Initialize variables to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
26. 2000 Prentice Hall, Inc. All rights reserved.
3.10 Nested control structures (III)
• Refine Input the ten quiz grades and count passes and failures to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
• Refine Print a summary of the exam results and decide if tuition
should be raised to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
27. 2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Initialize variables
2. Input data and
count passes/failures
3. Print results
1 /* Fig. 3.10: fig03_10.c
2 Analysis of examination results */
3 #include <stdio.h>
4
5 int main()
6 {
7 /* initializing variables in declarations */
8 int passes = 0, failures = 0, student = 1, result;
9
10 /* process 10 students; counter-controlled loop */
11 while ( student <= 10 ) {
12 printf( "Enter result ( 1=pass,2=fail ): " );
13 scanf( "%d", &result );
14
15 if ( result == 1 ) /* if/else nested in while */
16 passes = passes + 1;
17 else
18 failures = failures + 1;
19
20 student = student + 1;
21 }
22
23 printf( "Passed %dn", passes );
24 printf( "Failed %dn", failures );
25
26 if ( passes > 8 )
27 printf( "Raise tuitionn" );
28
29 return 0; /* successful termination */
30 }
28. 2000 Prentice Hall, Inc. All rights reserved.
Outline
Program Output
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 1
Enter Result (1=pass,2=fail): 2
Passed 6
Failed 4
29. 2000 Prentice Hall, Inc. All rights reserved.
3.11 Assignment Operators
• Assignment operators abbreviate assignment expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
30. 2000 Prentice Hall, Inc. All rights reserved.
3.12 Increment and Decrement Operators
• Increment operator (++) - can be used instead of c+=1
• Decrement operator (--) - can be used instead of c-=1.
• Preincrement
– Operator is used before the variable (++c or --c)
– Variable is changed, then the expression it is in is evaluated
• Postincrement
– Operator is used after the variable (c++ or c--)
– Expression executes, then the variable is changed
• If c = 5, then
printf( "%d", ++c);
• Prints 6
printf( "%d", c++);
• Prints 5
– In either case, c now has the value of 6
31. 2000 Prentice Hall, Inc. All rights reserved.
3.12 Increment and Decrement Operators
(II)
• When variable not in an expression
– Preincrementing and postincrementing have the same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.