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

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 TypeScriptjazoon13
 
Algorithms and flow charts
Algorithms and flow chartsAlgorithms and flow charts
Algorithms and flow chartsChinnu Edwin
 
Getting started with scala cats
Getting started with scala catsGetting started with scala cats
Getting started with scala catsKnoldus Inc.
 
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 2012Sri Kanth
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocodeAsha Sari
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)Thinkful
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vbSalim M
 
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ơnNexus FrontierTech
 
Episode 2 conditional flows & loops
Episode 2   conditional flows & loopsEpisode 2   conditional flows & loops
Episode 2 conditional flows & loopsJitendra Zaa
 
Episode 1 - PathToCode.com
Episode 1 - PathToCode.comEpisode 1 - PathToCode.com
Episode 1 - PathToCode.comJitendra Zaa
 
2. python basic syntax
2. python   basic syntax2. python   basic syntax
2. python basic syntaxSoba Arjun
 
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 DocsPete Gamache
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And ComponentsDaniel Fagnan
 
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.inWalmyr Lima e Silva Filho
 

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 FundamentalsChris Farrell
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressionsvinay arora
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programmingManoj Tyagi
 

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.pptxssusere336f4
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
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 PracticesInductive Automation
 
2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method OverloadingMichael Heron
 
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 PracticesInductive Automation
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationBlue Elephant Consulting
 
CPP11 - Function Design
CPP11 - Function DesignCPP11 - Function Design
CPP11 - Function DesignMichael Heron
 
CPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramCPP02 - The Structure of a Program
CPP02 - The Structure of a ProgramMichael Heron
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality codeHayden Bleasel
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem slovingMani Kandan
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to WorkSingleStore
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software DevelopmentAndré Pitombeira
 
CPP01 - Introduction to C++
CPP01 - Introduction to C++CPP01 - Introduction to C++
CPP01 - Introduction to C++Michael Heron
 

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

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
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 SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael 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

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Recently uploaded (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

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