SlideShare a Scribd company logo
1 of 26
Repetition
Michael Heron
Introduction
• The first of the real programming structures we are going to
look at is the repetition family.
• Used to repeat blocks of code.
• Used to repeat blocks of code.
• Haha, did you see what I did there??
• They’re somewhat more versatile than copy and paste.
• And also play to the fundamental traits of programmers.
The Programmer Mindset
• Good programming is based on one basic truth about
programmers.
• We’re horribly lazy.
• Anything that the computer can be doing, it should be doing.
• The less we have to do, the better.
• Repetition structures let us do that to a degree.
An Example
• Imagine a program that would give you the average of five
numbers.
• Prompt the user
• Pull in the number
• Add it to a total
• Prompt the user
• Pull in the number
• Add it to a total
• Etc
The Program
#include <iostream>
using namespace std;
int main() {
int total = 0;
int tmp;
cout << "Enter number 1" << endl;
cin >> tmp;
total = total + tmp;
cout << "Enter number 2" << endl;
cin >> tmp;
total = total + tmp;
cout << "Enter number 3" << endl;
cin >> tmp;
total = total + tmp;
cout << "Enter number 4" << endl;
cin >> tmp;
total = total + tmp;
cout << "Enter number 5" << endl;
cin >> tmp;
total = total + tmp;
total = total / 5;
cout << "Average is " << total;
}
Problems
• Not easy to read.
• Fine for five numbers, more difficult for five hundred.
• Prone to error
• How do you know you’ve repeated the code enough?
• Hard to expand
• What if we now want 500 numbers?
• Difficult to fix
• What if there’s a typo?
• Fix every line of code!
• Can’t adapt to runtime situations.
The Repetition Structure
• Repetitions are used to manage these problems.
• We provide a piece of code that says to the compiler ‘repeat
this section of code five times’
• We move responsibility for the repetition onto the compiler.
• Where it belongs.
Repetitions
• The loop we are going to talk about today is the for loop.
• It’s an example of a bounded loop
• We use it when we know, at the time the program is running,
how many times we want to loop.
• There are several parts to this structure.
• We’ll go through each in turn.
• The braces on the structure are important too.
• They denote ownership.
Parts of a For Loop
• A for loop works on a counter.
• The counter tells us how many times we have repeated.
• Or to use the correct jargon, iterated.
• In the structure of the for loop, we have three parts.
• The initialisation
• This occurs at the start of the loop and never again
• The continuation condition
• We check to see this after ever loo
• The upkeep
• We do this after each time the code has been executed.
Parts of a For Loop
• A for loop then has the following structure:
int counter; // Declaration of the counter variable
for (initialization ; continuation ; upkeep) {
// Code to be executed
}
The Braces
• Braces are used to indicate ownership.
• Not quite, but it’s a good enough explanation for now.
• The code in the braces belongs to the for loop.
• If no braces are provided, the next statement only belongs to
the for loop.
• This is not good practice.
• For loops don’t end with a semi-colon.
• A semi-colon in C++ is considered a statement all by itself.
The Continuation
• The continuation is what determines whether or not a loop
keeps iterating.
• For a for loop, we use the special symbol <
• It means less than.
• This is a comparison operator, and we’ll see more of these as we go
along.
• Usually we base our continuation on the counter variable.
• is the counter less than a set number?
• counter < 5
Rewritten Program
#include <iostream>
using namespace std;
int main() {
int total = 0;
int tmp;
int counter;
for (counter = 0; counter < 5; counter++) {
cout << "Enter number " << counter + 1 << endl;
cin >> tmp;
total = total + tmp;
}
total = total / 5;
cout << "Average is " << total;
}
Benefits
• Easier to read.
• You can tell at a glance how many times the loop will repeat.
• Easier to maintain.
• Just one section of code to alter.
• Easier to expand.
• If we need to average 500 numbers, we have much less code to
change.
• No transcription errors.
Program Style
• Our first structure brings with it our first aesthetic issue.
• Program layout
• One of the things most neglected by beginner programmers is the
layout of their code.
• At their own great cost!
• There are many different ways to layout programs.
• This module adopts one, but does not require its use.
• It does require the use of a layout though.
Module Style
• Braces on the same line as the structure.
• Indent one level per level of ownership.
• Indent the statements that belong to main by one level.
• Indent the statements that belong to the for loop that belongs to
main by two levels.
• Judicious use of white space!
• You’ll see this style in all of the lecture notes.
• It is not enforced by the compiler, but leads to more readable
programs.
This Program Does Not Work -
Why?
#include <iostream>
using namespace std;
int main() {
int total = 0;
int tmp, i;
for (i = 0; i < 5; i++) {
cout << "Enter number " << i + 1 << endl;
cin >> tmp;
total = total + tmp;
total = total / 5;
}
cout << "Average is " << total;
}
Program Style
• The more structures you have, the harder a program becomes
to read if you don’t adopt a style.
• Readable programs are programs that you can debug.
• The layout of the code gives you syntactical clues.
• It shows you where statements belong in the body of the
program.
Program Style
• Comments are also hugely important.
• These are text encoded in a program that gets ignored by the
compiler.
• They are notes for the developer.
• You can indicate a single line to be commented using two
slashes:
• // This is a comment.
• Or a block of code using /* and */
• /* This is also a comment */
Comments
• Comments should be used to explain complex code.
• It should be used to explain what you intend, not what the code
actually does.
int i;
/*
This for loop modifies a temporary variable
by the counter.
*/
int temp = 10;
for (int i = 1; i < 10; i++) {
temp = temp + i;
}
int i;
/*
This for loop gives the power of temp to
ten
*/
int temp = 10;
for (int i = 1; i < 10; i++) {
temp = temp + i;
}
Bad Better
Comments
• There are many heuristics about comments.
• Such as X% of your code should be comments
• I don’t adhere to any of these.
• I find indiscriminate commenting actually detracts from readability.
• Some guidelines:
• Comment intention where your intention is not blindingly obvious.
• Later when you start to use functions.
• Document what the function does.
• Document parameters
• Document return values
Comments
• Comments help gain big picture understanding.
• Don’t comment the obvious.
• Consider your audience.
• It’s not going to be your relatives who read your code.
• It’s going to be fellow programmers who understand the syntax.
• Comment your code like the person who ends up maintaining it is a
violent psychopath who knows where you live.
• Damian Conway
Program Style
• Good programs are readable programs.
• Good code is its own documentation.
• You should always make use of meaningful names for your
variables.
• Again, not enforced by the compiler.
• Bad variable names inhibit understanding:
• av = (av / 100) * 102.15;
• Good variable names increase understanding:
• accountValue = (accountValue / 100) * 102.15;
Program Style
• Avoid the use of magic numbers.
• Numbers embedded in your code with no explanation.
int interestRate = 102.15;
int percent = 100;
accountValue = (accountValue / percent) * interestRate;
Program Style
• I don’t want to harp on about this.
• But I’m going to anyway.
• The single worst thing you can do in a program is ignore the
aesthetics.
• The single best thing you can do is adopt a strict coding style.
• There are holy wars of formatting about which style is best.
• They’re all roughly as good as each other. It doesn’t matter what
style you adopt, it only matters that you adopt one and stick to it.
Summary
• Repetition is a powerful programming tool.
• Repetition is a powerful programming tool.
• Repetition is a powerful programming tool.
• If a joke is funny once it’s funny every time, right?
• Some jokes aren’t funny the first time.
• Program style is important!
• Don’t neglect it!
• Comment your code
• Where appropriate

More Related Content

What's hot

Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
Thinkful
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
Daniel Fagnan
 

What's hot (20)

Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
JAZOON'13 - Oliver Zeigermann - Typed JavaScript with TypeScript
JAZOON'13 - Oliver Zeigermann - Typed JavaScript with TypeScriptJAZOON'13 - Oliver Zeigermann - Typed JavaScript with TypeScript
JAZOON'13 - Oliver Zeigermann - Typed JavaScript with TypeScript
 
Algorithms and flow charts
Algorithms and flow chartsAlgorithms and flow charts
Algorithms and flow charts
 
Getting started with scala cats
Getting started with scala catsGetting started with scala cats
Getting started with scala cats
 
Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012Async CTP 3 Presentation for MUGH 2012
Async CTP 3 Presentation for MUGH 2012
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocode
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
 
Lecture 21
Lecture 21Lecture 21
Lecture 21
 
Password locker project
Password locker project Password locker project
Password locker project
 
Quiz5
Quiz5Quiz5
Quiz5
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
Tech Talk #4 : Functional Reactive Programming - Đặng Thái Sơn
Tech Talk #4 : Functional Reactive Programming - Đặng Thái SơnTech Talk #4 : Functional Reactive Programming - Đặng Thái Sơn
Tech Talk #4 : Functional Reactive Programming - Đặng Thái Sơn
 
Episode 2 conditional flows & loops
Episode 2   conditional flows & loopsEpisode 2   conditional flows & loops
Episode 2 conditional flows & loops
 
Episode 1 - PathToCode.com
Episode 1 - PathToCode.comEpisode 1 - PathToCode.com
Episode 1 - PathToCode.com
 
Jazoon2013 type script
Jazoon2013 type scriptJazoon2013 type script
Jazoon2013 type script
 
2. python basic syntax
2. python   basic syntax2. python   basic syntax
2. python basic syntax
 
Lecture 25
Lecture 25Lecture 25
Lecture 25
 
EMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with DocsEMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with Docs
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
 
Lessons learned as a software engineer working at appear.in
Lessons learned as a software engineer working at appear.inLessons learned as a software engineer working at appear.in
Lessons learned as a software engineer working at appear.in
 

Viewers also liked

1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]
tototo147
 
1.2 core programming [understand computer decision structures]
1.2 core programming [understand computer decision structures]1.2 core programming [understand computer decision structures]
1.2 core programming [understand computer decision structures]
tototo147
 
1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]
tototo147
 
1.4 core programming [understand error handling]
1.4 core programming [understand error handling]1.4 core programming [understand error handling]
1.4 core programming [understand error handling]
tototo147
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
Chris Farrell
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
vinay arora
 

Viewers also liked (9)

1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]
 
1.2 core programming [understand computer decision structures]
1.2 core programming [understand computer decision structures]1.2 core programming [understand computer decision structures]
1.2 core programming [understand computer decision structures]
 
1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]1.1 core programming [understand computer storage and data types]
1.1 core programming [understand computer storage and data types]
 
1.4 core programming [understand error handling]
1.4 core programming [understand error handling]1.4 core programming [understand error handling]
1.4 core programming [understand error handling]
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Software Development Fundamentals 1
Software Development Fundamentals 1Software Development Fundamentals 1
Software Development Fundamentals 1
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programming
 

Similar to CPP03 - Repetition

classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
ssusere336f4
 

Similar to CPP03 - Repetition (20)

classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
DAA Unit 1.pdf
DAA Unit 1.pdfDAA Unit 1.pdf
DAA Unit 1.pdf
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
CPP11 - Function Design
CPP11 - Function DesignCPP11 - Function Design
CPP11 - Function Design
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a Program
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality code
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem sloving
 
Lecture1
Lecture1Lecture1
Lecture1
 
2CPP02 - C++ Primer
2CPP02 - C++ Primer2CPP02 - C++ Primer
2CPP02 - C++ Primer
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to Work
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
 
CPP01 - Introduction to C++
CPP01 - Introduction to C++CPP01 - Introduction to C++
CPP01 - Introduction to C++
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

More from Michael Heron

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in Uganda
 
Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public AdministrationWSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
WSO2CON 2024 - How CSI Piemonte Is Apifying the Public Administration
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 

CPP03 - Repetition

  • 2. Introduction • The first of the real programming structures we are going to look at is the repetition family. • Used to repeat blocks of code. • Used to repeat blocks of code. • Haha, did you see what I did there?? • They’re somewhat more versatile than copy and paste. • And also play to the fundamental traits of programmers.
  • 3. The Programmer Mindset • Good programming is based on one basic truth about programmers. • We’re horribly lazy. • Anything that the computer can be doing, it should be doing. • The less we have to do, the better. • Repetition structures let us do that to a degree.
  • 4. An Example • Imagine a program that would give you the average of five numbers. • Prompt the user • Pull in the number • Add it to a total • Prompt the user • Pull in the number • Add it to a total • Etc
  • 5. The Program #include <iostream> using namespace std; int main() { int total = 0; int tmp; cout << "Enter number 1" << endl; cin >> tmp; total = total + tmp; cout << "Enter number 2" << endl; cin >> tmp; total = total + tmp; cout << "Enter number 3" << endl; cin >> tmp; total = total + tmp; cout << "Enter number 4" << endl; cin >> tmp; total = total + tmp; cout << "Enter number 5" << endl; cin >> tmp; total = total + tmp; total = total / 5; cout << "Average is " << total; }
  • 6. Problems • Not easy to read. • Fine for five numbers, more difficult for five hundred. • Prone to error • How do you know you’ve repeated the code enough? • Hard to expand • What if we now want 500 numbers? • Difficult to fix • What if there’s a typo? • Fix every line of code! • Can’t adapt to runtime situations.
  • 7. The Repetition Structure • Repetitions are used to manage these problems. • We provide a piece of code that says to the compiler ‘repeat this section of code five times’ • We move responsibility for the repetition onto the compiler. • Where it belongs.
  • 8. Repetitions • The loop we are going to talk about today is the for loop. • It’s an example of a bounded loop • We use it when we know, at the time the program is running, how many times we want to loop. • There are several parts to this structure. • We’ll go through each in turn. • The braces on the structure are important too. • They denote ownership.
  • 9. Parts of a For Loop • A for loop works on a counter. • The counter tells us how many times we have repeated. • Or to use the correct jargon, iterated. • In the structure of the for loop, we have three parts. • The initialisation • This occurs at the start of the loop and never again • The continuation condition • We check to see this after ever loo • The upkeep • We do this after each time the code has been executed.
  • 10. Parts of a For Loop • A for loop then has the following structure: int counter; // Declaration of the counter variable for (initialization ; continuation ; upkeep) { // Code to be executed }
  • 11. The Braces • Braces are used to indicate ownership. • Not quite, but it’s a good enough explanation for now. • The code in the braces belongs to the for loop. • If no braces are provided, the next statement only belongs to the for loop. • This is not good practice. • For loops don’t end with a semi-colon. • A semi-colon in C++ is considered a statement all by itself.
  • 12. The Continuation • The continuation is what determines whether or not a loop keeps iterating. • For a for loop, we use the special symbol < • It means less than. • This is a comparison operator, and we’ll see more of these as we go along. • Usually we base our continuation on the counter variable. • is the counter less than a set number? • counter < 5
  • 13. Rewritten Program #include <iostream> using namespace std; int main() { int total = 0; int tmp; int counter; for (counter = 0; counter < 5; counter++) { cout << "Enter number " << counter + 1 << endl; cin >> tmp; total = total + tmp; } total = total / 5; cout << "Average is " << total; }
  • 14. Benefits • Easier to read. • You can tell at a glance how many times the loop will repeat. • Easier to maintain. • Just one section of code to alter. • Easier to expand. • If we need to average 500 numbers, we have much less code to change. • No transcription errors.
  • 15. Program Style • Our first structure brings with it our first aesthetic issue. • Program layout • One of the things most neglected by beginner programmers is the layout of their code. • At their own great cost! • There are many different ways to layout programs. • This module adopts one, but does not require its use. • It does require the use of a layout though.
  • 16. Module Style • Braces on the same line as the structure. • Indent one level per level of ownership. • Indent the statements that belong to main by one level. • Indent the statements that belong to the for loop that belongs to main by two levels. • Judicious use of white space! • You’ll see this style in all of the lecture notes. • It is not enforced by the compiler, but leads to more readable programs.
  • 17. This Program Does Not Work - Why? #include <iostream> using namespace std; int main() { int total = 0; int tmp, i; for (i = 0; i < 5; i++) { cout << "Enter number " << i + 1 << endl; cin >> tmp; total = total + tmp; total = total / 5; } cout << "Average is " << total; }
  • 18. Program Style • The more structures you have, the harder a program becomes to read if you don’t adopt a style. • Readable programs are programs that you can debug. • The layout of the code gives you syntactical clues. • It shows you where statements belong in the body of the program.
  • 19. Program Style • Comments are also hugely important. • These are text encoded in a program that gets ignored by the compiler. • They are notes for the developer. • You can indicate a single line to be commented using two slashes: • // This is a comment. • Or a block of code using /* and */ • /* This is also a comment */
  • 20. Comments • Comments should be used to explain complex code. • It should be used to explain what you intend, not what the code actually does. int i; /* This for loop modifies a temporary variable by the counter. */ int temp = 10; for (int i = 1; i < 10; i++) { temp = temp + i; } int i; /* This for loop gives the power of temp to ten */ int temp = 10; for (int i = 1; i < 10; i++) { temp = temp + i; } Bad Better
  • 21. Comments • There are many heuristics about comments. • Such as X% of your code should be comments • I don’t adhere to any of these. • I find indiscriminate commenting actually detracts from readability. • Some guidelines: • Comment intention where your intention is not blindingly obvious. • Later when you start to use functions. • Document what the function does. • Document parameters • Document return values
  • 22. Comments • Comments help gain big picture understanding. • Don’t comment the obvious. • Consider your audience. • It’s not going to be your relatives who read your code. • It’s going to be fellow programmers who understand the syntax. • Comment your code like the person who ends up maintaining it is a violent psychopath who knows where you live. • Damian Conway
  • 23. Program Style • Good programs are readable programs. • Good code is its own documentation. • You should always make use of meaningful names for your variables. • Again, not enforced by the compiler. • Bad variable names inhibit understanding: • av = (av / 100) * 102.15; • Good variable names increase understanding: • accountValue = (accountValue / 100) * 102.15;
  • 24. Program Style • Avoid the use of magic numbers. • Numbers embedded in your code with no explanation. int interestRate = 102.15; int percent = 100; accountValue = (accountValue / percent) * interestRate;
  • 25. Program Style • I don’t want to harp on about this. • But I’m going to anyway. • The single worst thing you can do in a program is ignore the aesthetics. • The single best thing you can do is adopt a strict coding style. • There are holy wars of formatting about which style is best. • They’re all roughly as good as each other. It doesn’t matter what style you adopt, it only matters that you adopt one and stick to it.
  • 26. Summary • Repetition is a powerful programming tool. • Repetition is a powerful programming tool. • Repetition is a powerful programming tool. • If a joke is funny once it’s funny every time, right? • Some jokes aren’t funny the first time. • Program style is important! • Don’t neglect it! • Comment your code • Where appropriate