Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Problem understanding the for loop and the loop invariant.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 Katreyo   Members   -  Reputation: 103

Like
0Likes
Like

Posted 12 June 2012 - 08:35 PM

Hey guys, I'm teaching myself C++ using the Accelerated C++ book. I'm having issues understanding the authors definition of the invariant.

This is the initial code from the chapter:


#include <iostream>
#include <string>

// say what standard-library names we use
using std::cin;         using std::endl;
using std::cout;        using std::string;


int main()
{
// ask for the person's name
cout << "Please enter your first name: ";

// read the name
string name;
cin >> name;

// build the message that we intend to write
const string greeting = "Hello, " + name + "!";

// the number of blanks surrounding the greeting
const int pad = 1;

// the number of rows and columns to write
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;

// write a blank line to separate the output from the input
cout << endl;

// write `rows' rows of output
// invariant: we have written `r' rows so far
for (int r = 0; r != rows; ++r) {

string::size_type c = 0;

// invariant: we have written `c' characters so far in the current row
while (c != cols) {

// is it time to write the greeting?
if (r == pad + 1 && c == pad + 1) {
cout << greeting;
c += greeting.size();
} else {

// are we on the border?
if (r == 0 || r == rows - 1 ||
   c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}

cout << endl;
}

return 0;
}

I understand this all and fine. Then in the chapter exercises I have this question:

2-2. Change the framing program so that it uses a different amount of space to separate the sides from the greeting

than it uses to separate the top and bottom borders from the greeting.
2-3. Rewrite the framing program to ask the user to supply the amount of spacing to leave between the frame and the
greeting.

2-4. The framing program writes the mostly blank lines that separate the borders from the greeting one character at a
time. Change the program so that it writes all the spaces needed in a single output expression.

2-2 and 2-3 are the reasons why my program asks for additional user input and I had no issues with them, 2-4 sparked some issues for me. I got it to work but it feels like my code is extremely in-concise for what it does. Also when he talks about the loop invariant, in this case r being the number of rows we have written (so it's incremented to 1 when we write the first row, and c is the number of characters we have written in the current row and is updated every time we write a new character. He stated that once you add a row the invariant becomes false so you must make it true again by updating the invariant. He explained this with the while loop but in the for loop the ++r handles this implicitly for you.

Originally I had considered that the first row was written when r == 1 so thats when I would call firstlastrow but it always printed on the second row causing my output to be gibbered. I fixed it to print the first and last rows on r == 0 and r == rows - 1. But I think it goes against what he described the loop invariant to do.

For those willing to read here is a brief excerpt from his chapter on invariants

Another reason to count from 0 is that doing so makes loop invariants easier to express. In our example, counting
from 0 makes the invariant straightforward: We have written r rows of output so far. What would be the invariant if
we counted from 1?
One would be tempted to say that the invariant is that we are about to write the rth row, but that statement does not
qualify as an invariant. The reason is that the last time the while tests its condition, r is equal to rows + 1, and we
intend to write only rows rows. Therefore, we are not about to write the rth row, so the invariant is not true!
Our invariant could be that we have written r - 1 rows so far. However, if that's our invariant, why not simplify it by
starting r at 0?


For my answer to the question this is my following code. So I guess this would be a two part question:

1) Am i misunderstanding the definition of an invariant?
2) What would be a less hackish way to accomplish this exercise, as I feel my code is too cumbersome.

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::string;
using std::endl;

int main()
{
cout << "Name Plox: ";

string name;
cin >> name;

int tempint;

cout << "Spacing for top and bottom: ";
cin >> tempint;
const int topbotpad = tempint;

cout << "Spacing for left and right: ";
cin >> tempint;
const int leftrightpad = tempint;
const string greetingspaces(leftrightpad, ' ');

const string greeting = "*" + greetingspaces + "Hello, " + name + "!" + greetingspaces + "*";
const int rows = topbotpad * 2 + 3;
const string::size_type cols = greeting.size();

const string spaces(cols - 2, ' ');
const string firstlastrows(cols, '*');
const int greetingrow = (rows - 1) / 2;

cout << endl;

// Invariant: We have written r rows so far
for(int r = 0; r != rows; ++r)
{
if (r == greetingrow)
{
cout << greeting << endl;
}
else if(r == 0 || r == rows - 1)
{
cout << firstlastrows << endl;
}
else
cout << "*" << spaces << "*" << endl;
}
return 0;
}

Disclaimer: I have learnt c++ before but am trying to use tools he has taught me so far, I learnt through online tutorials that were never complete and am trying to do it the right way this time.

Thanks for reading, I know it's Lengthy, thanks in advance to helping as well!

Senjai

Sponsor:

#2 RulerOfNothing   Members   -  Reputation: 1164

Like
1Likes
Like

Posted 12 June 2012 - 09:08 PM

When the loop starts, r is equal to zero. r does not become equal to one until the loop is run once, or in other words after the first line is written. With regards to the program you have written, I can't see any obvious way to make the code less cumbersome (unfortunately some things take a lot of code to express).

#3 Katreyo   Members   -  Reputation: 103

Like
0Likes
Like

Posted 13 June 2012 - 12:10 PM

He hadnt taught else if in the book just yet so I was hesitant about using it. I understand the invariant issue now, the invariant is true before the loop starts, then you make it false with the statements in the loop, therefore you must make it true again at the end of the loop.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS