Category Archives: Programming

Accelerated C++ Solution to Exercise 1-1

Exercise 1-1

Are the following definitions valid? Why or why not?

const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";

Solution

Yes. These definitions are valid.

The key in answering this question is to acknowledge the use of the string concatenation operator +.

  • It is left associative.
  • We can use + to concatenate a string and a string literal (and vice versa), or a string and a string, but not a string with a string literal (nor vice versa).

Line 1 defines a string variable hello with length of 5 characters (which is Hello). This line is valid.

Line 2 defines a string variable message with the concatenation operator. The logic looks like this:

message = ( ( hello + ", world" ) + "!") 
        = ( ( a string + a string literal ) + a string literal )
        = ( ( a string ) + a string literal )
        = ( a string + a string literal )
        = ( a string )

i.e. at every single stage, we have not encountered any invalid string literal + string literal scenario. The concatenation is therefore valid.

Let’s test running the following program to prove the validity of the program.

#include <iostream>
#include <string>
int main()
{
    const std::string hello = "Hello";
    const std::string message = hello + ", world" + "!";
    std::cout << message << std::endl;
    return 0;
}

Result

As expected, the program compiled okay and produce the expected output.

Hello, world!

Process returned 0 (0x0)   execution time : 0.214 s
Press any key to continue.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 1-0

Exercise 1-0

Compile, execute, and test the programs in this chapter.

Solution

I will be taking the programs directly from the book (chapter 1 – Working with Strings), test run them, and see what we get. This exercise is purely to get our hands dirty right away on writing a submitting very simple programs on handling strings. Nothing too clever.

Test (Program 1)

The goal of this program is to

  • ask for a person’s name,
  • read the name in as a string variable, and
  • output a greeting message.
// ask for a person's name, and greet the person
#include <iostream>
#include <string>

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

    // read the name
    std::string name;   //define name
    std::cin >> name;   //read into name

    // write a greeting
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}

Result (Program 1)

Run the program. The followings are produced in the console output window:

Please enter your first name:

Type in some texts (my name) on the keyboard

Please enter your first name: Johnny

Hit enter key and it gives:

Please enter your first name: Johnny
Hello, Johnny!

Process returned 0 (0x0)   execution time : 2.631 s
Press any key to continue.

Test (Program 2)

The goal of program 2 is to read in a person’s name, and generate a framed greeting like this:

******************
*                *
* Hello, Johnny! *
*                *
******************

To do this the following C++ program is taken directly from the book.

// ask for a person's name, and generate a framed greeting
#include <iostream>
#include <string>

int main()
{
    std::cout << "Please enter your first name: ";  //ask for the person's name
    std::string name;   //define name
    std::cin >> name;   //read into name

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

    // build the second and forth lines of the output
    const std::string spaces(greeting.size(),' ');
    const std::string second = "* " + spaces + " *";
    const std::string first(second.size(),'*');

    // write it all
    std::cout << std::endl;
    std::cout << first << std::endl;
    std::cout << second << std::endl;
    std::cout << "* " << greeting << " *" << std::endl;
    std::cout << second << std::endl;
    std::cout << first << std::endl;
    return 0;
}

Result (Program 2)

Run the program. The followings are produced in the console output window:

Please enter your first name:

Type in some texts (my name) on the keyboard

Please enter your first name: Johnny

Hit enter key and it gives:

Please enter your first name: Johnny

******************
*                *
* Hello, Johnny! *
*                *
******************

Process returned 0 (0x0)   execution time : 2.520 s
Press any key to continue.

Some core learning:

  • Use double quote to define string literal. Use single quote to define character (char) literal.
  • We can use + to concatenate a string and a string literal (and vice versa), or a string and a string, but not a string with a string literal (nor vice versa). i.e.
    • string + string is okay.
    • string literal + string is okay.
    • string + string literal is okay.
    • string literal + string literal is NOT okay.
  • Use the object component size() , which is a function, to determine the length (number of characters) of a string (the object itself). e.g. greeting.size gives the length of the string greeting.
  • Refer to the book to see the various ways to define a string variables, including the use of overload.
  • Keep It Simple and Stupid (KISS) – write the code in a way that is easy to write and understand. Nothing too clever.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-10

Exercise 0-10

Rewrite the Hello World program so that a newline occurs everywhere that white-space is allowed in the program.

Solution

The question essentially asks us to replace any space characters with the newline character \n.

#include <iostream>
int main()
{
    std::cout << "Hello,\nWorld!" << std::endl;
}

Result

The program compiles okay in Code::Block. It gives the followings in the console output window. Note that the newline character, \n, creates a new line after the “Hello,”.

Hello,
World!

Process returned 0 (0x0)   execution time : 0.174 s
Press any key to continue.

This concludes all 10 chapter zero end-of-chapter exercises!

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-9

Exercise 0-9

What is the shortest valid program?

Solution

According to chapter 0 (Getting Started) of the book Accelerated C++ …

On Main function:

  • Every C++ program must define exactly one function, named main, that returns an int.
  • The implementation runs the program by calling main.
  • A zero returns indicates success; a non-zero return indicates failure.
  • In general, functions must include at least one return statement and are not permitted to fall off the end of the function.
  • The main function is special: it may omit the return; if it does so, the implementation will assume a zero return value.
  • However, explicitly including a return from main is good practice.

The shortest valid program can therefore be as short as a one-liner like this (or can this be made even shorter I wonder?)

int main() {}

Result

The program compiles okay in Code::Block and gives me the following output the the console output window.

Process returned 0 (0x0)   execution time : 0.141 s
Press any key to continue.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-8

Exercise 0-8

Is this a valid program? why or why not?

#include <iostream>
int main{}
{
    // This is a comment that extends over several lines
    // by using // at the beginning of each line instead of using /*
    // or */ / to delimit comments.
       std::cout << "Does this work?" << std::endl;
       return 0;
}

Solution

Yes. This is a valid C++ Program.

Line comment starts the comment by beginning the line with the //. Whatever follows is a comment, as long as within the same line. The

Once a new line is created, the // is required at the beginning to start another comment.

You can also use the line comment in the middle of a line (so the first part of the line is not a comment, and the second part is a comment). It looks something like this:

std::cout << "Hello World!" << std::endl;  // this is a comment

What I sometimes do is to try out writing the code in an IDE like Code::Block. The auto syntax highlighting within the IDE should give us hints whether the parts in the code are comment or not, indicated by the different colour highlighting. (I would not rely 100% on this though. But it is a good and quick guide I’ve found).

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-7

Exercise 0-7

Is this a valid program? why or why not?

#include <iostream>
int main{}
{
    /* This is a comment that extends over several lines
       because it uses /* and */ as its starting and ending delimiters */
       std::cout << "Does this work?" << std::endl;
       return 0;
}

Solution

No. This is not a valid C++ Program.

The issue is the way the code treats comment. A correct block-comment looks like this.

/* this is a comment */

i.e. a correctly written comment is surround by the /* and */. Anything in between is a comment. Anything outside is not a comment.

In this case, the actual comment part is highlighted in blue below (and the remaining red part is not qualified as a comment)

/* This is a comment that extends over several lines
because it uses /* and */ as its starting and ending delimiters */

I would correct the comment to something like this (using the line comment //), should we wish to keep the comments.

// This is a comment that extends over several lines
// because it uses /* and */ as its starting and ending delimiters

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-6

Exercise 0-6

Is this a valid program? Why or why not?

#include <iostream>
int main() {{{{{{std::cout << "Hello World!" << std::endl;}}}}}}

Solution

Yes. This is a valid C++ program.

In C++ curly braces tell the implementation to treat whatever (statement) appears between them as a unit.

It is okay to have nested curly braces, as long as all the curly braces are balanced out. i.e. for every single open/left brace it is matched by a close/right brace.

Let’s run the program and see what we get?

Result

The program compiles okay. And gives us the following result in the console output window.

Hello World!

Process returned 0 (0x0)   execution time : 0.187 s
Press any key to continue.

Experiment – Nested Curly Braces

Let us, for curiosity sake to see if nested curly braces actually work? Here is a very simple program that I write for this experiment.

// Experiment with nested curly braces
#include <iostream>
int main()
{
    std::cout << "I am block 1" << std::endl;
    {
        std::cout << "I am block 1-1, son of block 1" << std::endl;
        {
            std::cout << "I am block 1-1-1, son of block 1-1, grandson of block 1." << std::endl;
            std::cout << "I am block 1-1-2, son of block 1-1, grandson of block 1." << std::endl;
        }
    }
    {
        std::cout << "I am block 1-2, son of block 1" << std::endl;
    }
}

The program compiles okay and gives us the followings in the console output window as expected.

I am block 1
I am block 1-1, son of block 1
I am block 1-1-1, son of block 1-1, grandson of block 1.
I am block 1-1-2, son of block 1-1, grandson of block 1.
I am block 1-2, son of block 1

Process returned 0 (0x0)   execution time : 0.187 s
Press any key to continue.

This experiment has demonstrated that nested curly braces essentially provides a way to group blocks of statements together, which I think is a very cool feature as it allows us breakdown tons of statements into smaller blocks. This is very handy if we are to define a chunky function.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-5

Exercise 0-5

Is this a valid program? Why or why not?

#include <iostream>
int main()   std::cout << "Hello World!" << std::endl;

Solution

No. This is not a valid C++ program.

In C++ curly braces tell the implementation to treat whatever (statement) appears between them as a unit. This program would not work unless amended / corrected. The curly braces are missing.

For instance, running this (buggy) program we get this error in the build log.

error: expected initializer before ‘std’

To correct the program, simply add the curly braces and enclose the statements within these curly braces.

In addition, let’s add the return statement at the end for good practice. (The book mentions that the main function is the only function that does not require the return statement. Having a return statement in every single function that we define is however a good practice. So let’s do it!)

#include <iostream>
int main()  
{
    std::cout << "Hello World!" << std::endl;
    return;
}

Result

The program can now be compiled and run correctly. It produces the following in the console output window.

Hello World!

Process returned 0 (0x0)   execution time : 0.205 s
Press any key to continue.

 Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-4

Exercise 0-4

Write a program that, when run, writes the Hello World program as its output.

Solution

Using the skills picked up from the previous exercises, this should be quite a straight forward exercise. There is nothing new here. Below is my code (of course, there are many ways to do this.)

#include <iostream>
int main()
{
    std::cout << "#include <iostream>" << std::endl;
    std::cout << "int main()" << std::endl;
    std::cout << "{" << std::endl;
    std::cout << "  std::cout << \"Hello World!\" << std::endl;" << std::endl;
    std::cout << "  return 0;" << std::endl;
    std::cout << "}" << std::endl;
    return 0;
}

Result

Submitting the program produces the Hello World code in the console output window.

#include <iostream>
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}

Process returned 0 (0x0)   execution time : 0.179 s
Press any key to continue.

# Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Accelerated C++ Solution to Exercise 0-3

Exercise 0-3

The string literal “\t” represents a tab character; different C++ implementations display tabs in different ways. Experiment with your implementation to learn how it treats tabs.

Experiments

I shall be running a number of experiment C++ programs to test out the tab behaviour. I am running this using the Code::Block IDE (Integrated Development Environment) on Window Vista platform. (According to a number of online forums the tab property differs depending on the platform (e.g. tab length).

Experiment 1

In this experiment I will add various number of tabs at the start of a line.


<h1>include <iostream></h1>

<p>int main()
{
    std::cout << "Start the following line with tabs" << std::endl;
    std::cout << "\tStart this line with 1 tab." << std::endl;
    std::cout << "\t\tStart this line with 2 tabs." << std::endl;
    std::cout << "\t\t\tStart this line with 3 tabs." << std::endl;
    return 0;
}

Result (experiment 1)

Submitting the program produces the following in the console output window.

Start the following line with tabs
         Start this line with 1 tab.
                 Start this line with 2 tabs.
                         Start this line with 3 tabs.

Process returned 0 (0x0)   execution time : 0.235 s
Press any key to continue.

Observations:

  • Should the line begins with 1 tab, the tab length is 8 spaces.
  • With 2 (consecutive) tabs, the second tab adds 8 spaces. i.e. total indentation is 8 + 8 = 16 spaces.
  • With 3 (consecutive) tabs, the third tab is adds spaces. i.e. total indentation is 8 + 8 + 8 = 24 spaces.

From this it appears that each tab corresponds to 8 spaces.

Experiment 2

In this experiment I will add various number of tabs within a line.

#include <iostream>
int main()
{
    std::cout << "Add tabs within the line" << std::endl;
    std::cout << "I will add 1 tabs\twithin this line line." << std::endl;
    std::cout << "I will add 2 tabs\t\twithin this line." << std::endl;
    std::cout << "I will add 3 tabs\t\t\twithin this line." << std::endl;
    return 0;
}

Result

Submitting the program produces the following in the console output window.

Add tabs within the line
I will add 1 tabs       within this line line.
I will add 2 tabs               within this line.
I will add 3 tabs                       within this line.

Process returned 0 (0x0)   execution time : 0.159 s
Press any key to continue.

Observations:

  • Should the line contains 1 tab, the tab length is 7 spaces.
  • With 2 (consecutive) tabs, the second tab adds 8 spaces. i.e. total tab length is 7 + 8 = 15 spaces.
  • With 3 (consecutive) tabs, the third tab is 8 spaces. i.e. total indentation is 7 + 8 + 8 = 23 spaces.

From this it appears that each tab is of 8 spaces, except the first tab which is of 7. (I’m not entirely sure why though.)

Conclusion

Merging experiment 1 and 2, it appears that each tab in general takes up a fix length of 8 spaces. The only exception is the first tab that is placed within a line (as seen in experiment 2), which takes up only 7 spaces (i.e. 1 space less). I am not entirely sure why at this stage.

This reminds of a message that the authors mention in chapter 0:

… string literal, … a mysterious type that we shall not even discuss until section 10.2 / page 176…

So is it something that is hidden that require deeper understanding?I hope to find out more in later chapter(s).

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000