When the increment operator is used as in num1 ++ The expression is in this mode?

Chapter 5: Loops and Files

5.1 The Increment and Decrement Operators

 

++ is the increment operator.

It adds one to a variable.

val++;      is the same as val = val + 1

 

++ can be used before (prefix) or after (postfix) a variable:

++val;     val++;

-- is the decrement operator.

It subtracts one from a variable.

val--;      is the same as val = val - 1

-- can be also used before (prefix) or after (postfix) a variable:

--val;     val--;

Increment and Decrement Operators in Program 5-1


// This program demonstrates the ++ and -- operators.
#include
using namespace std;

int main()
{
   int num = 4;   // num starts out with 4.

      // Display the value in num.
   cout << "The variable num is " << num << endl;
   cout << "I will now increment num.\n\n";

      // Use postfix ++ to increment num.
   num++;
   cout << "Now the variable num is " << num << endl;
   cout << "I will increment num again.\n\n";

   // Use prefix ++ to increment num.
   ++num;
   cout << "Now the variable num is " << num << endl;
   cout << "I will now decrement num.\n\n";

      // Use postfix -- to decrement num.
   num--;
   cout << "Now the variable num is " << num << endl;
   cout << "I will decrement num again.\n\n";

      // Use prefix -- to increment num.
   --num;
   cout << "Now the variable num is " << num << endl;
   return 0;
}


Prefix vs. Postfix

++ and -- operators can be used in complex statements and expressions

  • In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable
  • In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements

Prefix vs. Postfix - Examples

  int num, val = 12;

  cout << val++; // displays 12,

    // val is now 13;

  cout << ++val; // sets val to 14,

                 // then displays it

  num = --val;   // sets val to 13,

    // stores 13 in num

  num = val--;   // stores 13 in num,

      // sets val to 12

Notes on Increment and Decrement

  •         Can be used in expressions:
    •          result = num1++ + --num2;
  •          Must be applied to something that has a location in memory. Cannot have:
    •          result = (num1 + num2)++;
  •          Can be used in relational expressions:
    •          if (++num > limit)

  pre- and post-operations will cause different comparisons

5.2  Introduction to Loops: The while Loop

  • Loop: a control structure that causes a statement or statements to repeat
  • General format of the while loop:

  while (expression)

     statement;

  •          statement; can also be a block of statements enclosed in { }

The while Loop – How It Works

while (expression)

     statement;

> expression is evaluated

–if true, then statement is executed, and expression is evaluated again

–if false, then the loop is finished and program statements following statement execute

 

Program 5-3


// This program demonstrates a simple while loop.
#include
using namespace std;

int main()
{
   int number = 0;

   while (number < 5)
   {
      cout << "Hello\n";
      number++;
   }
   cout << "That's all!\n";
   return 0;
}



The while Loop is a Pretest Loop - expression is evaluated before the loop executes.

Watch Out for Infinite Loops

  •         The loop must contain code to make expression become false
  •         Otherwise, the loop will have no way of stopping
  •         Such a loop is called an infinite loop, because it will repeat an infinite number of times

Example of an Infinite Loop

int number = 1;
while (number <= 5)
{
   cout << "Hello\n";
}

5.3  Using the while Loop for Input Validation

  •         Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid.
  •         The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered.

Using the while Loop for Input Validation

Here's the general approach, in pseudocode:

Read an item of input.
While the input is invalid
     Display an error message.
     Read the input again.
End While

cout << "Enter a number less than 10: ";
cin >> number;
while (number >= 10)
{
   cout << "Invalid Entry!"
          << "Enter a number less than 10: ";
   cin >> number;
}

Input Validation in Program 5-5


// This program calculates the number of soccer teams
// that a youth league may create from the number of
// available players. Input validation is demonstrated
// with while loops.
#include
using namespace std;

int main()
{
   // Constants for minimum and maximum players
   const int MIN_PLAYERS = 9,
             MAX_PLAYERS = 15;

   // Variables
   int players,      // Number of available players
       teamPlayers,  // Number of desired players per team
       numTeams,     // Number of teams
       leftOver;     // Number of players left over

   // Get the number of players per team.
   cout << "How many players do you wish per team? ";
   cin >> teamPlayers;

      // Validate the input.
   while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS)
   {
      // Explain the error.
      cout << "You should have at least " << MIN_PLAYERS
           << " but no more than " << MAX_PLAYERS << " per team.\n";

      // Get the input again.
      cout << "How many players do you wish per team? ";
      cin >> teamPlayers;
   }

      // Get the number of players available.
   cout << "How many players are available? ";
   cin >> players;

      // Validate the input.
   while (players <= 0)
   {
      // Get the input again.
      cout << "Please enter 0 or greater: ";
      cin >> players;
   }

   // Calculate the number of teams.
   numTeams = players / teamPlayers;

      // Calculate the number of leftover players.
   leftOver = players % teamPlayers;

      // Display the results.
   cout << "There will be " << numTeams << " teams with "
        << leftOver << " players left over.\n";
   return 0;
}

Counters

  • Counter: a variable that is incremented or decremented each time a loop repeats
  • Can be used to control execution of the loop (also known as the loop control variable)
  • Must be initialized before entering loop

A Counter Variable Controls the Loop in Program 5-6


// This program displays a list of numbers and
// their squares.
#include
using namespace std;

int main()
{
   const int MIN_NUMBER = 1,   // Starting number to square
             MAX_NUMBER = 10;  // Maximum number to square

   int num = MIN_NUMBER;       // Counter

   cout << "Number Number Squared\n";
   cout << "-------------------------\n";
   while (num <= MAX_NUMBER)
   {
      cout << num << "\t\t" << (num * num) << endl;
      num++; //Increment the counter.
   }
   return 0;
}

5.5  The do-while Loop

  • do-while: a posttest loop – execute the loop, then test the expression
  • General Format:

  do

   statement;  // or block in { }

 while (expression);

  •         Note that a semicolon is required after (expression)

An Example do-while Loop
int x = 1;
do
{
    cout << x << endl;
} while(x < 0);

Although the test expression is false, this loop will execute one time because do-while is a posttest loop.

A do-while Loop in Program 5-7


// This program averages 3 test scores. It repeats as
// many times as the user wishes.
#include
using namespace std;

int main()
{
   int score1, score2, score3; // Three scores
   double average;             // Average score
   char again;                 // To hold Y or N input

   do
   {
      // Get three scores.
      cout << "Enter 3 scores and I will average them: ";
      cin >> score1 >> score2 >> score3;

            // Calculate and display the average.
      average = (score1 + score2 + score3) / 3.0;
      cout << "The average is " << average << ".\n";

            // Does the user want to average another set?
      cout << "Do you want to average another set? (Y/N) ";
      cin >> again;
   } while (again == 'Y' || again == 'y');
   return 0;
}


do-while Loop Notes

  • Loop always executes at least once
  • Execution continues as long as expression is true, stops repetition when expression becomes false
  • Useful in menu-driven programs to bring user back to menu to make another choice (see Program 5-8 on pages 245-246)

5.6  The for Loop

  • Useful for counter-controlled loop
  • General Format:

for(initialization; test; update)
     statement; // or block in { }

  • No semicolon after the update expression or after the )

for Loop - Mechanics

for(initialization; test; update)

  statement; // or block in { }

2)Evaluate test expression 

–If true, execute statement

–If false, terminate loop execution

3)Execute update, then re-evaluate test expression

for Loop - Example
int count;

for (count = 1; count <= 5; count++)
   cout << "Hello" << endl;


A for Loop in Program 5-9

// This program displays the numbers 1 through 10 and
// their squares.
#include
using namespace std;

int main()
{
   const int MIN_NUMBER = 1,   // Starting value
             MAX_NUMBER = 10;  // Ending value
   int num;

   cout << "Number Number Squared\n";
   cout << "-------------------------\n";

   for (num = MIN_NUMBER; num <= MAX_NUMBER; num++)
      cout << num << "\t\t" << (num * num) << endl;

   return 0;
}


When to Use the for Loop

In any situation that clearly requires

–an initialization

–a false condition to stop the loop

–an update to occur at the end of each iteration


  • The for loop tests its test expression before each iteration, so it is a pretest loop.
  • The following loop will never iterate:

for (count = 11; count <= 10; count++)
   cout << "Hello" << endl;

for Loop - Modifications

You can have multiple statements in the initialization expression. Separate the statements with a comma:

int x, y;

for (x=1, y=1; x <= 5; x++)

{

cout << x << " plus " << y
        << " equals " << (x+y)
        << endl;

}

   

  •           You can also have multiple statements in the test expression. Separate the statements with a comma:

int x, y;

for (x=1, y=1; x <= 5; x++, y++)
{
   cout << x << " plus " << y
        << " equals " << (x+y)
        << endl;
}

  •          You can omit the initialization expression if it has already been done:

  int sum = 0, num = 1;

  for (; num <= 10; num++)

  sum += num;

  •          You can declare variables in the initialization expression:

  int sum = 0;

  for (int num = 0; num <= 10; num++)

  sum += num;

  The scope of the variable num is the for loop.

5.7  Keeping a Running Total

  • running total: accumulated sum of numbers from each repetition of loop
  • accumulator: variable that holds running total

int sum=0, num=1; // sum is the

while (num <= 10) // accumulator

{    sum += num;

   num++;

}

cout << "Sum of numbers 1 – 10 is"

     << sum << endl;

A Running Total in Program 5-12


// This program takes daily sales figures over a period of time
// and calculates their total.
#include
#include
using namespace std;

int main()
{
   int days;            // Number of days
   double total = 0.0;  // Accumulator, initialized with 0

   // Get the number of days.
   cout << "For how many days do you have sales figures? ";
   cin >> days;

      // Get the sales for each day and accumulate a total.
   for (int count = 1; count <= days; count++)
   {
      double sales;
      cout << "Enter the sales for day " << count << ": ";
      cin >> sales;
      total += sales;   // Accumulate the running total.
   }

      // Display the total sales.
   cout << fixed << showpoint << setprecision(2);
   cout << "The total sales are $" << total << endl;
   return 0;
}


5.8  Sentinels

  • sentinel: value in a list of values that indicates end of data
  • Special value that cannot be confused with a valid value, e.g., -999 for a test score
  • Used to terminate input when user may not know how many values will be entered

A Sentinel in Program 5-13


// This program calculates the total number of points a
// soccer team has earned over a series of games. The user
// enters a series of point values, then -1 when finished.
#include
using namespace std;

int main()
{
   int game = 1,   // Game counter
       points,     // To hold a number of points
       total = 0;  // Accumulator

   cout << "Enter the number of points your team has earned\n";
   cout << "so far in the season, then enter -1 when finished.\n\n";
   cout << "Enter the points for game " << game << ": ";
   cin >> points;

   while (points != -1)
   { 
      total += points;
      game++;
      cout << "Enter the points for game " << game << ": ";
      cin >> points;
   }
   cout << "\nThe total points are " << total << endl;
   return 0;
}


5.9  Deciding Which Loop to Use

  •          The while loop is a conditional pretest loop
    •         Iterates as long as a certain condition exits
    •         Validating input 
    •         Reading lists of data terminated by a sentinel
  •          The do-while loop is a conditional posttest loop
    •          Always iterates at least once
    •          Repeating a menu
  •          The for loop is a pretest loop
    •         Built-in expressions for initializing, testing, and updating
    •         Situations where the exact number of iterations is known

5.10  Nested Loops

  • A nested loop is a loop inside the body of another loop
  • Inner (inside), outer (outside) loops:

for (row=1; row<=3; row++)  //outer
    for (col=1; col<=3; col++)//inner
        cout << row * col << endl;

Nested for Loop in Program 5-14


// This program averages test scores. It asks the user for the
// number of students and the number of test scores per student.
#include
#include
using namespace std;

int main()
{
   int numStudents,  // Number of students
       numTests;     // Number of tests per student
   double total,     // Accumulator for total scores
          average;   // Average test score

   // Set up numeric output formatting.
   cout << fixed << showpoint << setprecision(1);

   // Get the number of students.
   cout << "This program averages test scores.\n";
   cout << "For how many students do you have scores? ";
   cin >> numStudents;

      // Get the number of test scores per student.
   cout << "How many test scores does each student have? ";
   cin >> numTests;

      // Determine each student's average score.
   for (int student = 1; student <= numStudents; student++)
   {
      total = 0;      // Initialize the accumulator.
      for (int test = 1; test <= numTests; test++)
      {
         double score;
         cout << "Enter score " << test << " for ";
         cout << "student " << student << ": ";
         cin >> score;
         total += score;
      }
      average = total / numTests;
      cout << "The average score for student " << student;
      cout << " is " << average << ".\n\n";
   }
   return 0;
}


Nested Loops - Notes

  • Inner loop goes through all repetitions for each repetition of outer loop
  • Inner loop repetitions complete sooner than outer loop
  • Total number of repetitions for inner loop is product of number of repetitions of the two loops. 

5.11  Using Files for Data Storage

  • Can use files instead of keyboard, monitor screen for program input, output
  • Allows data to be retained between program runs
  • Steps:
    • Open the file
    • Use the file (read from, write to, or both)
    • Close the file

Files: What is Needed

  • Use fstream header file for file access
  • File stream types:

ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file

  • Define file stream objects:

ifstream infile;
ofstream outfile;

Opening Files

  • Create a link between file name (outside the program) and file stream object (inside the program)
  • Use the open member function:

infile.open("inventory.dat");
outfile.open("report.txt");

  • Filename may include drive, path info.
  • Output file will be created if necessary; existing file will be erased first
  • Input file must exist for open to work

Testing for File Open Errors

  •          Can test a file stream object to detect if an open operation failed:

  infile.open("test.txt");

  if (!infile)

  {

   cout << "File open failure!";

  }

  •          Can also use the fail member function

Using Files

  •          Can use output file object and << to send data to a file:

  outfile << "Inventory report";

  •          Can use input file object and >> to copy data from file to variables:

  infile >> partNum;

  infile >> qtyInStock >> qtyOnOrder;

Using Loops to Process Files

  • The stream extraction operator >> returns true when a value was successfully read, false otherwise
  • Can be tested in a while loop to continue execution as long as values are read from the file:

  while (inputFile >> number) ...

  •          Use the close member function:

infile.close();

outfile.close();

  •         Don’t wait for operating system to close files at program end:

–may be limit on number of open files

–may be buffered output data waiting to send to file

Letting the User Specify a Filename

  • The open member function requires that you pass the name of the file as a null-terminated string, which is also known as a C-string.
  • String literals are stored in memory as null-terminated C-strings, but string objects are not.
  • string objects have a member function named c_str

–It returns the contents of the object formatted as a null-terminated C-string.

–Here is the general format of how you call the c_str function:

                    stringObject.c_str()

Letting the User Specify a Filename in Program 5-24


// This program lets the user enter a filename.
#include
#include
#include
using namespace std;

int main()
{
   ifstream inputFile;
   string filename;
   int number;

   // Get the filename from the user.
   cout << "Enter the filename: ";
   cin >> filename;

   // Open the file.
   inputFile.open(filename.c_str());

   // If the file successfully opened, process it.
   if (inputFile)
   {
      // Read the numbers from the file and
      // display them.
      while (inputFile >> number)
      {
         cout << number << endl;
      }

      // Close the file.
      inputFile.close();
   }
   else
   {
       // Display an error message.
       cout << "Error opening the file.\n";
   }
   return 0;
}


5.12 Breaking and Continuing a Loop

  • Can use break to terminate execution of a loop
  • Use sparingly if at all – makes code harder to understand and debug
  • When used in an inner loop, terminates that loop only and goes back to outer loop

The continue Statement

  • Can use continue to go to end of loop and prepare for next repetition
    • while, do-while loops: go to test, repeat loop if test passes
    • for loop: perform update step, then test, then repeat loop if test passes
  • Use sparingly – like break, can make program logic hard to follow

What is the operator used for increment?

In languages syntactically derived from B (including C and its various derivatives), the increment operator is written as ++ and the decrement operator is written as -- . Several other languages use inc(x) and dec(x) functions.

What does it mean to increment something what operator is used in C++ to do this?

In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable.

What does ++ i mean in programming?

i++ increment the variable i by 1. It is the equivalent to i = i + 1. i– decrements (decreases) the variable i by 1.

Which operator is used to increment a variable?

A program can increment by 1 the value of a variable called c using the increment operator, ++, rather than the expression c=c+1 or c+=1. An increment or decrement operator that is prefixed to (placed before) a variable is referred to as the prefix increment or prefix decrement operator, respectively.