Problem with the for loop and loop invariant concept

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

#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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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
Last edited on
closed account (o3hC5Di1)
Hi there,

I personally never really bothered about "definitions" when learning programming, to me it's always been more important to know how something works (and how you can make it work for you) rather than memorising the opinion of one person on the subject. The explanation you transcribed is also quite ambiguous and hard to read, so not an ideal explanation from a teaching point of view in my humble opinion.

Your code looks fine to me, you make use of the string constructors rather than extra loops, which is bonus points I would think.

Perhaps someone could shed their light on the use of all these constants, agreed, they are values that will not change during runtime, but would you really go about declaring all these as constants and if so, what benefit would it offer other than syntactical clarity?

Sorry - don't mean to hijack your thread - just interested.

Hope that helps.

All the best,
NwN
No problem, thank you for the input. In the book constants are said to add no benefit to the program however it can make it significantly easier to read knowing that variables wont change. It can also catch you if you try to change something you said to yourself before shouldnt be changed.

I think there is a line between knowing how something works and doing it the right way, Invariants are a pretty well accepted design term for programming, i know this because the one programming class i took in UNI for scheme stressed it a lot.

Cheers,

Senjai
Topic archived. No new replies allowed.