{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

L04 - primitive data and control structures 2

# L04 - primitive data and control structures 2 - Last time...

This preview shows pages 1–7. Sign up to view the full content.

C++ review & C++/CLI - Basics Last time, we had looked at: Primitive datatypes – standard C++ and C++/CLI – String literals, String ^ – CLI types and their relationship to standard C++ types Basic control structures and their combination – Algorithms, Pseudocode, Control Structures – Review of if, if/else – Conditional Operator – Loops (with example of counter controlled repetition using a while structure)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
C++ review & C++/CLI - Basics Counter Controlled Repetition – When we use counter controlled repetition to input data, we set a counter initially (often to 0 or to 1) and increment or decrement it each time the loop is executed • Pseudocode: – Set total to 0 – Set days counter to 1 – While counter <= 10: Input the next day’s high temperature Add this temperature to the total Increment the counter – Set the average high to (total/10) – Print the average high temperature
C++ review & C++/CLI - Basics // This program illustrates counter controlled repetition // S. Conry //January 2008 #include "stdafx.h" using namespace System; int main() { int total = 0; int days = 1; double avgtemp; while (days <= 10){ Console::Write(L"\nPlease enter the next daily high temperature: "); total = total + Int32::Parse(Console::ReadLine()); days++; } avgtemp = total / 10.0; Console::WriteLine(L"\nThe average daily high is {0}", avgtemp.ToString("F2")); return 0; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
C++ review & C++/CLI - Basics Comments on Counter Controlled Repetition Usually used when we know how many times we are interested in doing something (like 10 or 100 or some value that we have already acquired) If we have a set of data and the first thing in the set of data is a number that tells us how much more to expect, we can do a counter controlled loop for input If counters and/or totals are not initalized, the program will usually be wrong THIS IS A COMMON SOURCE OF ERRORS!! Always initialize counters and other variables When the loop terminates, the value of a counter is usually one more or less than the last “legitimate” value (depending on whether you were counting up or down) If you use the counter variable for something else later, remember this!!!