• Google+
  • Twitter
  • YouTube
  • RSS
  • Facebook

Basic C++ Programming: Test Your Knowledge

Test your knowledge of the absolute basics of C++.

The exercises below are designed for beginners who’ve been learning C++ for just a few weeks. Or months; I’m assuming you’ve got on to creating header files, and perhaps you haven’t if you’ve only been learning a few weeks; C++ is hard!

If you get stuck anywhere, don’t be disheartened — Rome wasn’t built in a day! Check the answer, cover it up again and see if you can write the code from memory.

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.


You can click the link below each question to reveal the answer.

These exercises were created using the free CodeBlocks IDE for Windows, using the excellent GNU compiler.

1. Create a “Hello World” C++ Program.

Create a basic C++ program that simply outputs the text “Hello World”.

[spoiler show="Show answer ...."]

#include <iostream>

using namespace std;

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

What if the answer above doesn’t compile?

If you’re writing for a platform other than Windows or using a compiler other than the GNU compiler, and your compiler has different ideas about headers or the form of main(), this is that point at which you’ll most likely discover it. If you can’t compile the code given here, check Google for a “Hello World” program for your platform. Most likely you’ll have to change an include or something. After that, subsequent syntax should be identical.

The answer compiles, but the console disappears so quickly that I can’t see it!

If you run your program from your IDE, you may need to add a statement that waits for a keypress, so that your console doesn’t flash up and disappear again immediately. Consult your compiler’s docs for details. For instance, cin.get() may do the trick for you.

I used printf!

Did you use printf()? Oh no! You’re stuck in C mode! You can use printf() in C++, but really it’s a hangover from C. Use cout if you want to learn C++!

[/spoiler]

An Interactive Program

Create a program that asks the user to enter an integer. If the integer is less than 10, print the message “This number is too small”. If the integer is greater than or equal to 10, print “This number is big enough”.

Hint: use cin with an if … else statement.

[spoiler show="Show answer ...."]

#include <iostream>

using namespace std;

int main()
{
    cout << "Enter a number: " << endl;

    int value;

    cin >> value;

    if(value < 10)
    {
        cout << "This value is too small";
    }
    else
    {
        cout << "This value is big enough.";
    }

    return 0;

}

[/spoiler]

Arrays

Create a program that creates an array of five hard-coded floating-point values, then prints out just the second value.

[spoiler show="Show answer ...."]


#include <iostream>

using namespace std;

int main()
{
    double values[] = {0.154, 33.2423, 0.444, 0.75, 1.632};

    cout << values[1] << endl;

    return 0;

}


[/spoiler]

Arrays and Loops

Modify the above program so that it uses a for loop to display all the values in the array, all on the same line, each value formatted to two decimal places and followed by a space.

Hint: you can hardcode the number of elements in the array for your ‘for’ loop, OR for extra credit figure out how to use sizeof to get the number of elements in the array.

Use setprecision from the iomanip header.

If you resort to using printf(), you get half credit …. :)

But my advice is, don’t be afraid to Google the right answer. Or just peek. It’s a good way to learn.

[spoiler show="Show answer ...."]

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double values[] = {0.154, 33.2423, 0.444, 0.75, 1.632};

    for(int i=0; i < sizeof(values)/sizeof(double); i++)
    {
        cout << setprecision(2) << values[i] << " ";
    }

    cout << endl;

    return 0;

}

[/spoiler]

Two Dimensional Arrays

A bit trickier, this one. Write an application that creates a two-dimensional array of doubles, with two rows and three columns. Print the value in the second row and third column.

Hint: 2D arrays can be declared using [][] instead of []. But you’ll need to put the actual number of array elements into these square brackets. Hey, it’s not Java!

When you initialize the array (put actual numbers into it), remember that each element is an array in itself.

If while attempting this question, you suffer a severe psychotic reaction and have to be placed in a special backwards jacket for your own protection, try looking at the answer, then cover it up again and see if you can remember how to do it. Once you’ve got your arms free, that is.

[spoiler show="Show answer ...."]

#include <iostream>

using namespace std;

int main()
{
    double values[2][3] = {
                {0.4, 1.65, 4.6},
                {4.35, 10.0, 3.4}
    };

    cout << values[1][2] << endl;

    return 0;

}

[/spoiler]

Looping Through 2D Arrays

Create an application that uses two nested for loops to loop through the 2D array defined above and print the values.

Hint: Here’s the outer loop:

for(int row = 0; row < 2; row++) {
}

The inner loop should use a loop variable called “col” (or whatever you like) and should loop through the columns.

Hard code the number of columns and rows, as above.

Once again, this is one of the trickiest beginner’s tasks in C++. If you can’t work it out, check the answer, then hide it again and try to write it from memory.

[spoiler show="Show answer ...."]

#include <iostream>

using namespace std;

int main()
{
    double values[2][3] = {
                {0.4, 1.65, 4.6},
                {4.35, 10.0, 3.4}
    };

    for(int row = 0; row < 2; row++ )
    {
        for(int col = 0; col < 3; col++)
        {
            // Put a space after each value.
            cout << values[row][col] << " ";
        }

        // Put a newline after each row.
        cout << endl;
    }

    return 0;

}

[/spoiler]

Create Classes and Objects

First, create a main program as in the first exercise.

Next, define a new class in its own .cpp and .h file. Call the class Car. Give it a single method called “start”. Make the method simply print “Car started!”.

In your main program, create a new Car object and call its start() method.

Your final program should simply therefore display the text “Car started!”.

[spoiler show="Show the car header file ..."]

#ifndef CAR_H
#define CAR_H

class Car
{
    public:
        void start();
};

#endif // CAR_H

Did you remember the #ifndef … bits ? If not, no sweat. Unless you’ve been programming in C++ for a year, in which case you should tear your hair out!

They are simply there to prevent multiple inclusion of the header file, and aren’t strictly necessary in this little program.
[/spoiler]

[spoiler show="Show the car implementation file ..."]


#include <iostream>
#include "car.h"
using namespace std;

void Car::start()
{
    cout << "Car started!";
}

[/spoiler]

[spoiler show="Show the main file ...."]

#include "car.h"

int main()
{
    Car car;

    car.start();
}

[/spoiler]

Constructors

Modify the above Car class so that it has an instance variable called name of type string (or whatever kind of string or String is defined for your compiler). Add a constructor that accepts a string parameter and sets the car’s name using this parameter. Add a getName() method that returns the car’s name.

Finally, modify the main application so that it sets the car’s name via the constructor, then prints the cars name (retrieving it using getName()).

[spoiler show="Show the car header file ..."]

#ifndef CAR_H
#define CAR_H

#include <string>
using namespace std;

class Car
{
    private:
        string name;

    public:
        Car(string name);
        string getName();
        void start();
};

#endif // CAR_H

[/spoiler]

[spoiler show="Show the car implementation file ..."]


#include <iostream>
#include "car.h"

using namespace std;

Car::Car(string name): name(name)
{

}

string Car::getName()
{
    return name;
}

void Car::start()
{
    cout << "Car started!";
}

If you set the car’s name in the body of the constructor instead of in the initialization list as above, don’t worry. There’s more than one way to skin a cat.

[/spoiler]

[spoiler show="Show the main program file ..."]

#include <iostream>
#include "car.h"

using namespace std;

int main()
{
    Car car("My car.");

    cout << car.getName() << endl;

    car.start();
}

[/spoiler]

While Loops

Write an application that asks the user to enter the number ’5′ and loops over and over until ’5′ is entered.

When 5 is finally entered, print “Got it!”.

Hint: use cin.

The program will crash if you enter something that isn’t a number, but don’t worry about that.

[spoiler show="Show answer ...."]

#include <iostream>

using namespace std;

int main()
{
    int value = 0;

    while(value != 5)
    {
        cout << "Enter the number '5': ";
        cin >> value;
    }

    cout << "Got it!" << endl;
}

[/spoiler]

Crash-Proof Input

The above program crashes if a user enters something other than a number. The problem is that we blindly assume that the user will enter an integer.

Modify the program so that no input can crash it.

Hint: use cin.getline() to get a line of text, then convert the text to an int (if possible) using, for example, istringstream.

Don’t be afraid to Google this stuff.

This stuff’s so tricky in C++ that I hesitate to include it here …. but I figure that with a bit of Googling, you’ll be OK. After all, programming is as much about searching for answers as it is actually doing stuff. Or am I thinking of religion?

If this stuff is really too much for your head, feel free to skip this question! Or better still, check the answer then try to do it from memory!

[spoiler show="Show answer ...."]

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    int value = 0;
    char text[256];

    while(value != 5)
    {
        cout << "Enter the number '5': ";

        cin.getline(text, 256);

        istringstream iss(text);
        iss >> value;
    }

    cout << "Got it!" << endl;
}

[/spoiler]

Switch Statements

Write a program that asks the user to enter an integer. If the user enters ’1′, print “Got 1″. If the user enters ’66′, print “Got 66″. If the user enters something other than these two numbers, print “Got something else”.

The program should use a switch statement.

Hint: you may need to look up switch statements on Google. Use the default clause to implement the case where the user doesn’t enter ’1′ or ’66′.

[spoiler show="Show answer ...."]


#include <iostream>

using namespace std;

int main()
{
    cout << "Enter a number: ";

    int value;

    cin >> value;

    switch(value)
    {
    case 1:
        cout << "Got 1" << endl;
        break;

    case 66:
        cout << "Got 66" << endl;
        break;

    default:
        cout << "Got something else." << endl;
    }

}

[/spoiler]

Do…While Loops

A while loop checks its condition before the first iteration of the loop. A do…while loop checks the condition at the end of the loop. This means there’s always at least one iteration of the loop.

Write a program that asks the user to enter an integer, then gets the input from the user. The program should repeatedly ask the user to enter an integer until the user enters an integer greater than 10; then it should print “Integer greater than 10 detected!” and should end.

The program must contain only two cout statements!

Hint: use a do…while loop to enclose the ‘prompt’ (i.e. the text that asks the user to enter the integer) and the bit that gets the user input.

[spoiler show="Show answer ...."]


#include <iostream>

using namespace std;

int main()
{
    int value = 0;

    do
    {
        cout << "Enter a number: ";
        cin >> value;
    }
    while(value <= 10);

    cout << "Integer greater than 10 detected!" << endl;
}


[/spoiler]

Success?

Once you can do this lot from memory, you’ve mastered the absolute basics of C++. Hats off to you; C++ is tricky to learn and unforgiving. If you can do this lot, you can learn the rest of it too.

If you want a SLIGHTLY easier ride, you can always try Java; take the basic Java test here.

If you’re looking for 1-to-1 lessons in programming via Skype, don’t hesitate to contact me: check out my in-yer-face advertising hype here

I’ve been doing C++ for well over a decade now, and believe me it seemed like a black art when I first encountered it in 1997. So if you’ve having problems with it — don’t give up! It gets easier, and you’ve already got through the hardest bit!