All posts by Johnny

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

Accelerated C++ Solution to Exercise 0-2

Exercise 0-2

Write a program that, when run, writes

This (") is a quote, and this (\) is a backslash.

Solution

We know from exercise 0-0 that to output a string to the console window, the statement should look like this:

cout << "Some text";

From the book we also know that certain special string literals must be preceded by a backslash (\) should we wish to display these correctly inside the two double quotes.

The (double quote) and the \ (backslash) are one of these special literals and therefore require to be preceded by a \ (backslash) – the that the character display correctly. See the book for details.

The full program therefore should look like this:


#include <iostream>
{
    std::cout << "This (\") is a quote, and this (\) is a backslash" << std::endl;
    return 0;
}

Note that we have precede the (double quote) and the \ (backslash) with a \ (backslash).

Result

Submit the program and we get the followings in the console window as required.

This (") is a quote, and this (\) is a backslash

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

Reference

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

Accelerated C++ Solution to Exercise 0-1

Exercise 0-1

What does the following statement do?

3 + 4;

Solution

The statement yields a result of integer (int) type, with the value of 7. As 3 + 4 = 7.

In Detail

  • The first operand, 3, is of type integer (int). The result is therefore of type int.
  • The addition operator, +, takes in the second operand (4) and add to the first operand (3). The second operand must be of the same (int) type for the addition operator to work.
  • The semi-colon at the end discards the result.
  • Note that the result is not expected to show in the console output window (e.g. a command window) as it is of type int. Only result of type std::ostream (standard output stream) is displayed in the console output window. For instant, if we submit the following program…
#include <iostream>
int main()
{
   3 + 4;
   return 0; 
}

We should expect to see the following output. i.e. the result of 7 does not get output to the console window.

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

To get the result to display the int result of 7, we use the std::cout (standard console output) facility, which is of type std::ostream (standard output stream).

#include <iostream>
int main()
{
   std::cout << 3 + 4;
   return 0; 
}

This now output the result to the console window.

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

Just a one-line statement and we have covered lots of ground here!

Reference

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

Accelerated C++ Solution to Exercise 0-0

Exercise 0-0

Compile and run the Hello World program.

Solution

The classic Hello World code looks like this.

// a small C++ program</p>

#include <iostream>

int main()
{
    ( (std::cout << "Hello, world!") << std::endl);
    return 0;
}

In detail

// a small C++ program
  • The double forward slashes indicates comment. Comments are ignored by the program during implementation.
<br />#include <iostream>

  • The #include directive ensures the <iostream> (input-output stream) facility is made available to the program.
int main()
{
}
  • We declare that the main function would yield an integer (int) type result. (i.e. result = 0 if success. Otherwise non-zero). The main function is the first function that is run when we implement a C++ program – so we must define one.
  • We define the main function within the two curly braces { }.
    ( (std::cout << "Hello, world!") << std::endl);
  • The expression statement create a result of type std::ostream (standard output stream), defined by its first operand std::cout (standard console output). The utility cout (console output) is in the (namespace) scope std (standard library).
  • The first (left associative) output operator << writes the string literal “Hello, world” to the std::cout. This causes a side-effect of displaying the string literal on the console command window.
  • The second (left associative) output operator << allows the manipulator std::endl (standard end line) to manipulate the standard output stream, which in this case, ends the current line of output.
  • Note that the brackets are not strictly required. I’ve included the brackets here purely to help visualising the logics associating with the left-associative output operator << .
  • The entire expression statement yields std::cout as a value (a result) which is of type std::ostream (standard output stream), and as a side effect writes the string literal (Hello, World!) onto this standard output stream (as displayed in the output command window). The std::endl manipulator ends the output line. Once it’s displayed (which is what we wanted), the semi-colon at the end of the expression statement discards the std::cout value (which is appropriate as we don’t need to keep hold of this value any more).
    return 0;
  • The return statement explicitly return an integer (int) value of 0 at the end of the main function to imply job run success. The semi-colon explicitly states that this is the end of this return statement.

Result

Once submitted the program, the following text appears in command window as expected.

Hello, world! 

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

Reference

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

Accelerated C++ Summary to Chapter 0 (Getting Started)

Chapter 0 of the Accelerated C++ book (by Koenig and Moo, reference at bottom) has provided me with an in-depth introduction of the classic Hello World C++ program in just 6 pages. As I see that there is an end of chapter exercise section and the book does not come with a solution (for good reason I guess!), I’ve decided to have a go doing these exercises and post my solutions in separate posts. Despite the book pretty much has covered it all, I would aim to include my own version of explanation for the benefit of learning and understanding. (My solution/explanation is subject to error as it’s just a scientific programming sketchbook after all!)

Although the (Hello World) program we’ve written is simple, we’ve covered a lot of ground in this chapter.

Key concepts learnt from this chapter: Hello World program; comment; #include directive; standard library vs core language; input-output stream (iostream); standard header; angle brackets; the main function; curly braces; operand type (int and std::iostream); output operator (<<); namespace (std); standard output stream (std::cout); stream manipulator (std::endl); the return statement; expression; result; side effects; operator vs operand; left-associative operator; scope; qualified name (std::cout); scope operator (::); free and non-free form structure; special string literals; escape using backslash; semicolons; expression statement; null statement.

References

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

Add new Code::Block Editor Theme: Son of Obsidian

The Code::Block IDE by default only comes with one editor scheme called “default”, which is a standard white background with code syntax highlighting. I wasn’t a fan of the default theme and wondered whether there might be a way to import a readily built alternative theme without having to go through the trouble to manually create one myself.

After doing some “Google-ing” I came across this very good Code::Block Forum which led me to Pizaro’s instruction on Exporting and Importing Code::Blocks Themes and the Son of Obsidian theme config file. So I had a go using both the instruction and the theme config file.

The end result? It worked! Now in my Code::Block I have a new Son of Obsidian Theme which is much more user friendly (and cool) to work with. It has a dark background with sharper syntax highlighting.

If you are looking to do the similar I highly recommend you to check out these articles.

Posting Source Code in WordPress Posts

Found this handy article on Posting Source Code in WordPress Posts today which I hope may enable me to start posting C++ codes via posts. It also says that for wordpress.org users (which I am) this the SyntaxHighlighter Evolved Plugin is required. I’ve decided to give it a try – to post the classic Hello World C++ Code in t his post and see what I get.


#include <iostream>

using namespace std;

int main()
{
cout << "Hello world!" << endl;
return 0;
}

Did it work?